问:
How to use Postgres jsonb '?' operator in Laravel with index support?
I'm trying to use the jsonb exists operator '?' in Laravel's query builder, and have it use an index, but I've run into some issues.

Sample query

DB::table('table_name')->whereRaw("jsonb_column ? 'key'")->get();

Sample Index

CREATE INDEX ON table_name USING GIN(jsonb_column jsonb_ops)

The main issue seems to be that '?' is reserved for parameter replacement, so this query returns a syntax error. I've found a couple ways around this, but each are incomplete solutions.

use '??' (a way to escape the ?) ->whereRaw("jsonb_column ?? 'key'")

doesn't work with querybuilder. returns SQLSTATE[42883]: Undefined function: 7 ERROR:  operator does not exist: jsonb ?? unknown

works with raw queries, e.g. DB::select("SELECT * FROM table_name WHERE jsonb_column ?? 'key'"), but I need it to work with the query builder.

use a named function / create an alias for the operator

'?' translates to the function - jsonb_exists(jsonb, text)

->whereRaw("jsonb_exists(jsonb_column, 'key')")

CREATE OPERATOR @-> ( PROCEDURE = jsonb_exists, LEFTARG = jsonb, RIGHTARG = text );

->whereRaw("jsonb_column @-> 'key'")

these solutions both "work"... but they don't use indexes

Right now I'm researching CREATE OPERATOR CLASS, as a way to get my custom operator to use gin indexing, but it's a bit over my head. If anybody can give me some tips on how to accomplish this or, even better, some simpler solution, it'd be a huge help.

edit

using php 7.3

答:
PHP 7.4 allows you to escape the placeholder with ??: https://wiki.php.net/rfc/pdo_escape_placeholders

```<code>DB::table('table_name')->whereRaw('jsonb_column ?? ?', ['key'])->get();
</code>```

Body:
PHP 7.4 allows you to escape the placeholder with ??: https://wiki.php.net/rfc/pdo_escape_placeholders

DB::table('table_name')->whereRaw('jsonb_column ?? ?', ['key'])->get();


来源: stackexchange

问:
Incorrect appearance of encoding
```<code>from jsonrpclib import jsonrpc

url = 'https://myserver.com:443'
jpc = jsonrpc.Server('%s/jsonrpc' % url)
new_string = "金衣大俠"
jpc.editqueue("NewName", new_string, 123)
</code>```

The new_string appears as Ñc'à in my server.  The server supports foreign characters, if I copy the text in new_string I can paste and save it in the server through the UI (not using jsonrpc) and it appears just fine.  I would guess I have to encode my string a certain way for this to work.  Any ideas on how I can encode my string for it to work ?

答: Python encoding has been answered in a different stack exchange already. Kindly reference the link here and define new_string on line 5 appropriately</p>

ContentLicense: CC BY-SA 4.0

Title: Incorrect appearance of encoding

Body:
from jsonrpclib import jsonrpc

url = 'https://myserver.com:443'
jpc = jsonrpc.Server('%s/jsonrpc' % url)
new_string = "金衣大俠"
jpc.editqueue("NewName", new_string, 123)

The new_string appears as Ñc'à in my server.  The server supports foreign characters, if I copy the text in new_string I can paste and save it in the server through the UI (not using jsonrpc) and it appears just fine.  I would guess I have to encode my string a certain way for this to work.  Any ideas on how I can encode my string for it to work ?


问:
How to divide the changelog.yaml into subsections?
I would like to separate each change of the databaseChangeLog in YAML format into its own file (again YAML) and include/import it somehow. It should be in way such that I can use a FileSystemAccessor or ClassPathAccessor to load it again.

Is there some example how to do that?

Thanks,
Dieter

答:
The way to do this is described at https://www.liquibase.org/bestpractices.html

The example given shows XML formatted changelogs, but the basic idea would be the same for YAML formatted changelogs.

Leave me a comment and I can generate a sample in YAML.


问:
NumberFormatException for input string Junifer import
I have an issue where I am importing an XML file in to an external system called Junifer. The system is set to accept certain strings, integers and values based on what we have pre-defined.

The XML file being uploaded is the following:

```<code>  <Customer>
    <UniqueId>1001</UniqueId>
    <ContractId>10012</ContractId>
    <ExternalCustomerReference>CustomerREF</ExternalCustomerReference>
    <CustomerReference></CustomerReference>
    <CompanyName>Name of Company</CompanyName>
    <CompanyRegistrationNumber>0000000</CompanyRegistrationNumber>
    <CustomerClass>Non Micro</CustomerClass>
    <CreditScore></CreditScore>
    <BusinessStartDate>12/05/2009</BusinessStartDate>
    <BusinessType>Limited</BusinessType>
    <Account>
      <Contact>
        <ContactType>Primary Customer</ContactType>
        <IsPrimaryContact>True</IsPrimaryContact>
        <ContactSurname>Surname</ContactSurname>
        <ContactFirstname>Name</ContactFirstname>
        <ContactTitle>Mr</ContactTitle>
        <ContactEmailAddress>me@me.com</ContactEmailAddress>
        <ContactDateOfBirth></ContactDateOfBirth>
        <ContactPrimaryTelephoneNumber>01234567890</ContactPrimaryTelephoneNumber>
        <ContactSecondaryTelephoneNumber>01234567890</ContactSecondaryTelephoneNumber>
        <BillDeliveryMethod>E-bill</BillDeliveryMethod>
        <CommunicationDeliveryMethod>Email</CommunicationDeliveryMethod>
        <Address1>Line1</Address1>
        <Address2>Line2</Address2>
        <Address3>Line3</Address3>
        <Address4>Line4</Address4>
        <Address5></Address5>
        <AddressPostcode>PC1 2PC</AddressPostcode>
      </Contact>
      <PaymentMethod>
        <PaymentMethod>Direct Debit</PaymentMethod>
        <BillingCycle></BillingCycle>
        <BankAccountName>Bank</BankAccountName>
        <BankAccountNumber>22222222</BankAccountNumber>
        <BankSortCode>111111</BankSortCode>
        <DirectDebitPaymentDay>1</DirectDebitPaymentDay>
        <DirectDebitPayment>339.204</DirectDebitPayment>
      </PaymentMethod>
      <Property>
        <PropertyAddress1>Property</PropertyAddress1>
        <PropertyAddress2></PropertyAddress2>
        <PropertyAddress3>Property3</PropertyAddress3>
        <PropertyAddress4>Property4</PropertyAddress4>
        <PropertyAddress5>Property5</PropertyAddress5>
        <PropertyAddressPostcode>PC1 2PC</PropertyAddressPostcode>
        <SupplyCapacity>0.00</SupplyCapacity>
        <MeterPoint>
          <MeterPointIdentifier>1234567890</MeterPointIdentifier>
          <ProfileClass>03</ProfileClass>
          <Fuel>Electricity</Fuel>
          <TprMappingSet>Tracker</TprMappingSet>
          <HhRateDefinition></HhRateDefinition>
          <AnnualConsumptions>
            <Consumption>20000kWh</Consumption>
            <RateName>Standard</RateName>
          </AnnualConsumptions>
          <Agreement>
            <AgreementReference>0.0</AgreementReference>
            <AgreementStartDate>27/11/2019</AgreementStartDate>
            <AgreementEndDate>26/11/2022</AgreementEndDate>
            <AgreementTerm>36</AgreementTerm>
            <ProductBundleRef>ElecTracker</ProductBundleRef>
            <BrokerCode>BROKER1</BrokerCode>
            <BrokerAgentReference>0.0</BrokerAgentReference>
            <BrokerReference>Broker</BrokerReference>
            <DateOfSale>28/10/2019</DateOfSale>
            <ProductItems>
              <ProductItem>
                <ProductItemReference>ENERGY</ProductItemReference>
                <Rates>
                  <Rate>
                    <Rate>19.75</Rate>
                    <RateName>Standard</RateName>
                  </Rate>
                </Rates>
              </ProductItem>
              <ProductItem>
                <ProductItemReference>STANDING-CHARGE</ProductItemReference>
                <Rates>
                  <Rate>
                    <Rate>33.00</Rate>
                  </Rate>
                </Rates>
              </ProductItem>
            </ProductItems>
          </Agreement>
        </MeterPoint>
      </Property>
    </Account>
  </Customer>
</Customers>
</code>```

For some reason I'm receiving the following error:

```<code>java.lang.NumberFormatException: For input string: "
    "
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentContext.getInteger(CommercialEnrolmentContext.java:492)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentContext.resolveCustomerElement(CommercialEnrolmentContext.java:140)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentContext.build(CommercialEnrolmentContext.java:94)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentOperationsImpl.lambda$buildEnrolmentContextsFromFile$933(CommercialEnrolmentOperationsImpl.java:185)
        at com.junifer.thor.processing.task.core.DefaultTaskExecutionContext.executeSubTask(DefaultTaskExecutionContext.java:132)
        at com.junifer.thor.processing.task.core.DefaultTaskExecutionContext.executeSubTask(DefaultTaskExecutionContext.java:119)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentOperationsImpl.buildEnrolmentContextsFromFile(CommercialEnrolmentOperationsImpl.java:181)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentImportTask.executeProcessFile(CommercialEnrolmentImportTask.java:49)
        at com.junifer.thor.processing.task.core.LogicalFileBatchTaskComponent.lambda$execute$17(LogicalFileBatchTaskComponent.java:80)
        at com.junifer.thor.processing.task.core.DefaultTaskExecutionContext.executeSubTask(DefaultTaskExecutionContext.java:132)
        at com.junifer.thor.processing.task.core.LogicalFileBatchTaskComponent.execute(LogicalFileBatchTaskComponent.java:71)
        at com.junifer.thor.processing.task.core.TaskExecutor$TaskRunnable.executeTask(TaskExecutor.java:674)
        at com.junifer.thor.processing.task.core.TaskExecutor$TaskRunnable.runWithLogging(TaskExecutor.java:623)
        at com.junifer.thor.processing.task.core.TaskExecutor$TaskRunnable.run(TaskExecutor.java:595)
        at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:113)
        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
        at java.util.concurrent.FutureTask.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

</code>```

Does anybody have any advice on how to get a successful read based on the information provided in the XML?

答:
Based on that stack trace, I'd say that <CreditScore></CreditScore> should contain an integer value, eg <CreditScore>0</CreditScore>

Incidentally, £339.204 seems like too many decimal places for a <DirectDebitPayment>

And <AgreementReference> and <BrokerAgentReference> are nullable text fields, so it's unlikely (although not an error) that they would need to contain a decimal value.

Body:
I have an issue where I am importing an XML file in to an external system called Junifer. The system is set to accept certain strings, integers and values based on what we have pre-defined.

The XML file being uploaded is the following:

  <Customer>
    <UniqueId>1001</UniqueId>
    <ContractId>10012</ContractId>
    <ExternalCustomerReference>CustomerREF</ExternalCustomerReference>
    <CustomerReference></CustomerReference>
    <CompanyName>Name of Company</CompanyName>
    <CompanyRegistrationNumber>0000000</CompanyRegistrationNumber>
    <CustomerClass>Non Micro</CustomerClass>
    <CreditScore></CreditScore>
    <BusinessStartDate>12/05/2009</BusinessStartDate>
    <BusinessType>Limited</BusinessType>
    <Account>
      <Contact>
        <ContactType>Primary Customer</ContactType>
        <IsPrimaryContact>True</IsPrimaryContact>
        <ContactSurname>Surname</ContactSurname>
        <ContactFirstname>Name</ContactFirstname>
        <ContactTitle>Mr</ContactTitle>
        <ContactEmailAddress>me@me.com</ContactEmailAddress>
        <ContactDateOfBirth></ContactDateOfBirth>
        <ContactPrimaryTelephoneNumber>01234567890</ContactPrimaryTelephoneNumber>
        <ContactSecondaryTelephoneNumber>01234567890</ContactSecondaryTelephoneNumber>
        <BillDeliveryMethod>E-bill</BillDeliveryMethod>
        <CommunicationDeliveryMethod>Email</CommunicationDeliveryMethod>
        <Address1>Line1</Address1>
        <Address2>Line2</Address2>
        <Address3>Line3</Address3>
        <Address4>Line4</Address4>
        <Address5></Address5>
        <AddressPostcode>PC1 2PC</AddressPostcode>
      </Contact>
      <PaymentMethod>
        <PaymentMethod>Direct Debit</PaymentMethod>
        <BillingCycle></BillingCycle>
        <BankAccountName>Bank</BankAccountName>
        <BankAccountNumber>22222222</BankAccountNumber>
        <BankSortCode>111111</BankSortCode>
        <DirectDebitPaymentDay>1</DirectDebitPaymentDay>
        <DirectDebitPayment>339.204</DirectDebitPayment>
      </PaymentMethod>
      <Property>
        <PropertyAddress1>Property</PropertyAddress1>
        <PropertyAddress2></PropertyAddress2>
        <PropertyAddress3>Property3</PropertyAddress3>
        <PropertyAddress4>Property4</PropertyAddress4>
        <PropertyAddress5>Property5</PropertyAddress5>
        <PropertyAddressPostcode>PC1 2PC</PropertyAddressPostcode>
        <SupplyCapacity>0.00</SupplyCapacity>
        <MeterPoint>
          <MeterPointIdentifier>1234567890</MeterPointIdentifier>
          <ProfileClass>03</ProfileClass>
          <Fuel>Electricity</Fuel>
          <TprMappingSet>Tracker</TprMappingSet>
          <HhRateDefinition></HhRateDefinition>
          <AnnualConsumptions>
            <Consumption>20000kWh</Consumption>
            <RateName>Standard</RateName>
          </AnnualConsumptions>
          <Agreement>
            <AgreementReference>0.0</AgreementReference>
            <AgreementStartDate>27/11/2019</AgreementStartDate>
            <AgreementEndDate>26/11/2022</AgreementEndDate>
            <AgreementTerm>36</AgreementTerm>
            <ProductBundleRef>ElecTracker</ProductBundleRef>
            <BrokerCode>BROKER1</BrokerCode>
            <BrokerAgentReference>0.0</BrokerAgentReference>
            <BrokerReference>Broker</BrokerReference>
            <DateOfSale>28/10/2019</DateOfSale>
            <ProductItems>
              <ProductItem>
                <ProductItemReference>ENERGY</ProductItemReference>
                <Rates>
                  <Rate>
                    <Rate>19.75</Rate>
                    <RateName>Standard</RateName>
                  </Rate>
                </Rates>
              </ProductItem>
              <ProductItem>
                <ProductItemReference>STANDING-CHARGE</ProductItemReference>
                <Rates>
                  <Rate>
                    <Rate>33.00</Rate>
                  </Rate>
                </Rates>
              </ProductItem>
            </ProductItems>
          </Agreement>
        </MeterPoint>
      </Property>
    </Account>
  </Customer>
</Customers>

For some reason I'm receiving the following error:

java.lang.NumberFormatException: For input string: "
    "
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentContext.getInteger(CommercialEnrolmentContext.java:492)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentContext.resolveCustomerElement(CommercialEnrolmentContext.java:140)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentContext.build(CommercialEnrolmentContext.java:94)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentOperationsImpl.lambda$buildEnrolmentContextsFromFile$933(CommercialEnrolmentOperationsImpl.java:185)
        at com.junifer.thor.processing.task.core.DefaultTaskExecutionContext.executeSubTask(DefaultTaskExecutionContext.java:132)
        at com.junifer.thor.processing.task.core.DefaultTaskExecutionContext.executeSubTask(DefaultTaskExecutionContext.java:119)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentOperationsImpl.buildEnrolmentContextsFromFile(CommercialEnrolmentOperationsImpl.java:181)
        at com.junifer.thor.processing.task.enrolment.CommercialEnrolmentImportTask.executeProcessFile(CommercialEnrolmentImportTask.java:49)
        at com.junifer.thor.processing.task.core.LogicalFileBatchTaskComponent.lambda$execute$17(LogicalFileBatchTaskComponent.java:80)
        at com.junifer.thor.processing.task.core.DefaultTaskExecutionContext.executeSubTask(DefaultTaskExecutionContext.java:132)
        at com.junifer.thor.processing.task.core.LogicalFileBatchTaskComponent.execute(LogicalFileBatchTaskComponent.java:71)
        at com.junifer.thor.processing.task.core.TaskExecutor$TaskRunnable.executeTask(TaskExecutor.java:674)
        at com.junifer.thor.processing.task.core.TaskExecutor$TaskRunnable.runWithLogging(TaskExecutor.java:623)
        at com.junifer.thor.processing.task.core.TaskExecutor$TaskRunnable.run(TaskExecutor.java:595)
        at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:113)
        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
        at java.util.concurrent.FutureTask.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

Does anybody have any advice on how to get a successful read based on the information provided in the XML?


问:
In Office JS Add-In for Outlook or Word, is there an api to replace or change text in certain character locations?
For an Add-In for Outlook or Word, I saw the API function: Office.context.mailbox.item.body.getAsync("html", callback) to get the content of the email, but I also need a function to replace/change the text at certain character locations, something like: replaceText(startChar, endChar, replacementText).

Is there such thing?

答:
This is not possible today. We track Outlook add-in feature requests on our user-voice page.

It looks like the feature you want has been requested by others already. Please upvote the existing request. Feature requests on user-voice are considered when we go through our planning process.


问:
How do you add a favicon to HTML page?
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

```<code><title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">
</code>```

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.

答:
Code standard favicon links at the top of your template or base.html and make sure the icons are there in the directory/s :

```<code>{% load staticfiles %}

<head>
  <link rel="shortcut icon" href="{% static "img/favicon.ico" %}">
  <link rel="icon" href="{% static "img/animated_favicon1.gif" %}">
</code>```

You can use favicon-generator.org to create new favicons.

Title: How do you add a favicon to HTML page?

Body:
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

<title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.

Body:
Code standard favicon links at the top of your template or base.html and make sure the icons are there in the directory/s :

{% load staticfiles %}

<head>
  <link rel="shortcut icon" href="{% static "img/favicon.ico" %}">
  <link rel="icon" href="{% static "img/animated_favicon1.gif" %}">

You can use favicon-generator.org to create new favicons.


问:
Ruby On Rails session storage problem
Im creating a sample RUBY ON RAILS APP and storing sessions in DB

The table structure is
id:pk,autoincrement

session_id:varchar 256

data:longtext

When i click save i get following error:

"Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data."

答: Your question itself has the answer. Just increase the size of data:longtext which is data column

ContentLicense: CC BY-SA 3.0

Title: Ruby On Rails session storage problem


问:
How can I delete all rows in excel that meet a certain criteria, plus subsequent rows
Example of what I'm trying to get rid of.

I am trying to get rid of junk data in a worksheet that appears to have been formatted to be paginated.  At the beginning of every new "page" is a cell in column G saying "Page X".  The next six rows of every page are all junk data that I want to delete, and there are hundreds of "pages".

I want to be able to write a formula that will search for every cell in the worksheet that contains the text "page" (at least in column G), and then delete that row plus the next six rows.

答:
Loop through all cells in Column G

Find cells =page and....

Add these cells + the next 6 rows to a Union (collection of cells)

Delete the Union at the end

```<code>Sub Maid()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<-- Update
Dim DeleteMe As Range
Dim LR As Long

LR = ws.Range("G" & ws.Rows.Count).End(xlUp).Row

    For i = 2 To LR
        If ws.Range("G" & i) = "page" Then
            If Not DeleteMe Is Nothing Then
                Set DeleteMe = Union(ws.Range("G" & i).Resize(7), DeleteMe)
            Else
                Set DeleteMe = ws.Range("G" & i).Resize(7)
            End If
        End If
    Next i

    If Not DeleteMe Is Nothing Then
        DeleteMe.EntireColumn.Delete
    End If

End Sub
</code>```

Body:
Loop through all cells in Column G

Find cells =page and....

Add these cells + the next 6 rows to a Union (collection of cells)

Delete the Union at the end

Sub Maid()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<-- Update
Dim DeleteMe As Range
Dim LR As Long

LR = ws.Range("G" & ws.Rows.Count).End(xlUp).Row

    For i = 2 To LR
        If ws.Range("G" & i) = "page" Then
            If Not DeleteMe Is Nothing Then
                Set DeleteMe = Union(ws.Range("G" & i).Resize(7), DeleteMe)
            Else
                Set DeleteMe = ws.Range("G" & i).Resize(7)
            End If
        End If
    Next i

    If Not DeleteMe Is Nothing Then
        DeleteMe.EntireColumn.Delete
    End If

End Sub


问:
RPG 4: Cast signed integer to Date and Time
I need cast timestamp (in Signed Int) to Date and Time.
How can I do it?

Idea:

```<code>D  stampint                     10I 0     //- value: '1455554435' - input parm
D  Varprint                     10A
D  Varprint2                     8A 0

 /free
   Varprint  = %char(%date( (<cast to timestamp> stampint) :*MDY));
   Varprint2 = %char(%time( (<cast to timestamp> stampint) :*HMS));
   dsply Varprint;
   dsply Varprint;
   inlr = *on;
   return ;
 /End-free

 Objective result:
   DSPLY 02/15/2016
   DSPLY 16:40:35
</code>```

Thanks.

UPDATE: Sorry, I put the question so fast that I didn't report it correctly.

The objective is to be able to report date and time, regardless of the type of variable. Var1 can be * CHAR or numeric (Packed). Varprint and Varprint2 are a example, but I would like to know how to cast from type I to type Z.

I have tried to use:

```<code>D timestmp          Z inz('1970-01-01-00.00.00.000000')
D result            Z inz('0001-01-01-00.00.00.000000')
... code..
 /free
   result = timestmp + %seconds(stampint);
   dsply result;
 /end-free
</code>```

But result is wrong.

I've tried too:

```<code>Varprint  = %char(%date( %editc(stampint:'Z') :*MDY));
</code>```

But it give compilation error: *RNF7416- The types of the right and left hand side do not ma
the EVAL operation.

答:
Could you give us an example value for stampint? And for that value, what you want varprint and varprint2 to be?

Update. Since stampint is a number of seconds, then assuming it is the number of seconds since Jan 1 1970, do the following:

```<code>   dcl-s ts timestamp;
   dcl-s d date;
   dcl-s t time;
   dcl-s stampint int(10) inz(1000000000);

   ts = Z'1970-01-01-00.00.00' + %seconds(stampint);
   d = %date(ts);
   t = %time(ts);
   dsply (d);
   dsply (t);
   return;
</code>```

To get the date as a character value in *MDY form:

```<code>   varprint = %char(%date(ts) : *mdy);
   varprintt = %char(%time(ts) : *hms);
</code>```

Body:
I need cast timestamp (in Signed Int) to Date and Time.
How can I do it?

Idea:

D  stampint                     10I 0     //- value: '1455554435' - input parm
D  Varprint                     10A
D  Varprint2                     8A 0

 /free
   Varprint  = %char(%date( (<cast to timestamp> stampint) :*MDY));
   Varprint2 = %char(%time( (<cast to timestamp> stampint) :*HMS));
   dsply Varprint;
   dsply Varprint;
   inlr = *on;
   return ;
 /End-free

 Objective result:
   DSPLY 02/15/2016
   DSPLY 16:40:35

Thanks.

UPDATE: Sorry, I put the question so fast that I didn't report it correctly.

The objective is to be able to report date and time, regardless of the type of variable. Var1 can be * CHAR or numeric (Packed). Varprint and Varprint2 are a example, but I would like to know how to cast from type I to type Z.

I have tried to use:

D timestmp          Z inz('1970-01-01-00.00.00.000000')
D result            Z inz('0001-01-01-00.00.00.000000')
... code..
 /free
   result = timestmp + %seconds(stampint);
   dsply result;
 /end-free

But result is wrong.

I've tried too:

Varprint  = %char(%date( %editc(stampint:'Z') :*MDY));

But it give compilation error: *RNF7416- The types of the right and left hand side do not ma
the EVAL operation.

Body:
Could you give us an example value for stampint? And for that value, what you want varprint and varprint2 to be?

Update. Since stampint is a number of seconds, then assuming it is the number of seconds since Jan 1 1970, do the following:

   dcl-s ts timestamp;
   dcl-s d date;
   dcl-s t time;
   dcl-s stampint int(10) inz(1000000000);

   ts = Z'1970-01-01-00.00.00' + %seconds(stampint);
   d = %date(ts);
   t = %time(ts);
   dsply (d);
   dsply (t);
   return;

To get the date as a character value in *MDY form:

   varprint = %char(%date(ts) : *mdy);
   varprintt = %char(%time(ts) : *hms);


问:
How to obtain a user input value from an image input in Javascript?

//const choices = ['Rock', 'Paper', 'Scissors'] in image form
const choices = window.document.getElementsByClassName('Images');
console.log(choices)

var userInput = window.document.getElementsByTagName('input')
console.log(userInput)

//take the image input and use it as a variable for the playerSelection part.
function playerSelection() {
    let answer = prompt('Rock, paper, scissors').toLowerCase()
    return answer
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Options">
    <input type ="image" class="Images" src ="https://image.flaticon.com/icons/svg/925/925141.svg" alt=""/>
    <input type ="image" class="Images" src="https://image.flaticon.com/icons/svg/2583/2583491.svg" alt style="padding-left: 50px; padding-right: 50px;">
    <input type ="image" class="Images" src="https://image.flaticon.com/icons/svg/494/494672.svg" alt="">
    </div></code>```

So what I'm trying to do is obtain the user input from the HTML file when the user clicks one of the pictures. So I can then later use it in my javascript file and save it into a variable. I've tried the getElementsByTagName but nothing really shows up in the developer console. What I'm not sure of is how can I test for user input using google developer tools, just so that I know my code is operating properly.

答:
Image inputs act like buttons. You should give each input a value. Then add a click event listener that gets the value of the button that was clicked.

//const choices = ['Rock', 'Paper', 'Scissors'] in image form

const output = document.querySelector("#output");
const choices = document.querySelectorAll('.Images');

choices.forEach(i => i.addEventListener("click", function() {
  playerSelection(this.value)
}));

//take the image input and use it as a variable for the playerSelection part.
function playerSelection(answer) {
  output.innerText = answer;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Images {
  width: 100px;
  height: 100px;
}</code>```

  <input type="image" value="rock" class="Images" src="https://image.flaticon.com/icons/svg/925/925141.svg" alt="" />
  <input type="image" value="paper" class="Images" src="https://image.flaticon.com/icons/svg/2583/2583491.svg" alt style="padding-left: 50px; padding-right: 50px;">
  <input type="image" value="scissors" class="Images" src="https://image.flaticon.com/icons/svg/494/494672.svg" alt="">

You selected: ```

Body:
//const choices = ['Rock', 'Paper', 'Scissors'] in image form
const choices = window.document.getElementsByClassName('Images');
console.log(choices)

var userInput = window.document.getElementsByTagName('input')
console.log(userInput)

//take the image input and use it as a variable for the playerSelection part.
function playerSelection() {
    let answer = prompt('Rock, paper, scissors').toLowerCase()
    return answer
}

    <input type ="image" class="Images" src ="https://image.flaticon.com/icons/svg/925/925141.svg" alt=""/>
    <input type ="image" class="Images" src="https://image.flaticon.com/icons/svg/2583/2583491.svg" alt style="padding-left: 50px; padding-right: 50px;">
    <input type ="image" class="Images" src="https://image.flaticon.com/icons/svg/494/494672.svg" alt="">

So what I'm trying to do is obtain the user input from the HTML file when the user clicks one of the pictures. So I can then later use it in my javascript file and save it into a variable. I've tried the getElementsByTagName but nothing really shows up in the developer console. What I'm not sure of is how can I test for user input using google developer tools, just so that I know my code is operating properly.

Body:
Image inputs act like buttons. You should give each input a value. Then add a click event listener that gets the value of the button that was clicked.

//const choices = ['Rock', 'Paper', 'Scissors'] in image form

const output = document.querySelector("#output");
const choices = document.querySelectorAll('.Images');

choices.forEach(i => i.addEventListener("click", function() {
  playerSelection(this.value)
}));

//take the image input and use it as a variable for the playerSelection part.
function playerSelection(answer) {
  output.innerText = answer;
}

.Images {
  width: 100px;
  height: 100px;
}

<div class="Options">
  <input type="image" value="rock" class="Images" src="https://image.flaticon.com/icons/svg/925/925141.svg" alt="" />
  <input type="image" value="paper" class="Images" src="https://image.flaticon.com/icons/svg/2583/2583491.svg" alt style="padding-left: 50px; padding-right: 50px;">
  <input type="image" value="scissors" class="Images" src="https://image.flaticon.com/icons/svg/494/494672.svg" alt="">
</div>
You selected: <span id="output"></span>


问:
Memory Leak warning while addSubView to Current ViewController
I get memory leak warning when I addsubView to Current ViewController....This is my code..

```<code>     NoOfGolferViewController *objNoOfGolferViewController = [[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil];
     [objNoOfGolferViewController setParent:self];
     [objNoOfGolferViewController.view setFrame:CGRectMake(15, 110, 290, 330)];
     [self.view addSubview:objNoOfGolferViewController.view];
</code>```

and when I release object

```<code>      [objNoOfGolferViewController release];
</code>```

Application get crashed by giving EXE_BAD_ACCESS message.

How can I solve this memory leak warning?

Thanks in advance..

答:
Typically you get this message when you are releasing an object that has been released already. I've been using the methods below (found here on SO at iOS4 - fast context switching) to track down these kind of issues in the past:

```<code>#pragma mark - RETAIN DEBUG MAGIC
// -----------------------------------------------------------------------------

- (id)retain
{
  NSLog(@"retain \t%s \tretainCount: %i", __PRETTY_FUNCTION__ , [self retainCount]);
  return [super retain];
}
- (void)release
{
  NSLog(@"release \t%s \tretainCount: %i", __PRETTY_FUNCTION__ , [self retainCount]);
  [super release];
}
- (id)autorelease
{
  NSLog(@"autorelease \t%s \tretainCount: %i", __PRETTY_FUNCTION__ , [self retainCount]);
  return [super autorelease];
}
</code>```

I wrote about this a couple of days ago here at SO using a similar example (I was having issues retaining and releasing some views). Follow this link if you are interested: Understanding iOS Instruments

Good luck!

Body:
I get memory leak warning when I addsubView to Current ViewController....This is my code..

     NoOfGolferViewController *objNoOfGolferViewController = [[NoOfGolferViewController alloc]initWithNibName:@"NoOfGolferViewController" bundle:nil];
     [objNoOfGolferViewController setParent:self];
     [objNoOfGolferViewController.view setFrame:CGRectMake(15, 110, 290, 330)];
     [self.view addSubview:objNoOfGolferViewController.view];

and when I release object

      [objNoOfGolferViewController release];

Application get crashed by giving EXE_BAD_ACCESS message.

How can I solve this memory leak warning?

Thanks in advance..

Body:
Typically you get this message when you are releasing an object that has been released already. I've been using the methods below (found here on SO at iOS4 - fast context switching) to track down these kind of issues in the past:

#pragma mark - RETAIN DEBUG MAGIC
// -----------------------------------------------------------------------------

- (id)retain
{
  NSLog(@"retain \t%s \tretainCount: %i", __PRETTY_FUNCTION__ , [self retainCount]);
  return [super retain];
}
- (void)release
{
  NSLog(@"release \t%s \tretainCount: %i", __PRETTY_FUNCTION__ , [self retainCount]);
  [super release];
}
- (id)autorelease
{
  NSLog(@"autorelease \t%s \tretainCount: %i", __PRETTY_FUNCTION__ , [self retainCount]);
  return [super autorelease];
}

I wrote about this a couple of days ago here at SO using a similar example (I was having issues retaining and releasing some views). Follow this link if you are interested: Understanding iOS Instruments

Good luck!


问:
Stop script from prompting for my password over and over
We have a script I use at work, that I did not write, that when its doing it thing prompts for same password about 5-6 times. I'd like to write something into it that when it asks for the password the first time, it stores the pw and autocompletes it each time thereafter. Is it possible to do this is a bash script? My understanding us the script is doing an ssh to another server and running an update on a file to make sure it has the most current version and if you are entering more than one user into the file it need to ask every time it updates. </p>

答:
First off, remember this is TERRIBLE SECURITY PRACTICE!!! With that in mind, what is the reason for the password prompt? When using sudo, you can always do this:

```<code>#!/bin/bash
read -s PASSWORD
echo $PASSWORD | sudo -S <whatever you want to do that prompts for password>
</code>```

Explanation:

sudo -S reads password from stdin

Source: https://superuser.com/questions/67765/sudo-with-password-in-one-command-line

So in conclusion, you can use sudo along with password from stdin to whatever you want to do.

I hope this helps!

Body:
First off, remember this is TERRIBLE SECURITY PRACTICE!!! With that in mind, what is the reason for the password prompt? When using sudo, you can always do this:

#!/bin/bash
read -s PASSWORD
echo $PASSWORD | sudo -S <whatever you want to do that prompts for password>

Explanation:

sudo -S reads password from stdin

Source: https://superuser.com/questions/67765/sudo-with-password-in-one-command-line

So in conclusion, you can use sudo along with password from stdin to whatever you want to do.

I hope this helps!


问:
Amazon AWS CLI not allowing valid JSON in payload parameter
I am getting an error when I try and invoke a lambda function from the AWS CLI. I am using version 2 of the CLI.
I understand that I should pass the --payload argument as a string containing a JSON object.

aws lambda invoke --function-name testsms  --invocation-type Event --payload '{"key": "test"}' response.json
```
<p>I get the following error:</p>
```Invalid base64: "{"key": "test"}"
```

I have tried all sorts of variants for the JSON escaping characters etc. I have also tried to use the file://test.json option I receive the same error.

答:
Looks like awscli v2 requires some parameters be base64-encoded.

By default, the AWS CLI version 2 now passes all binary input and binary output parameters as base64-encoded strings. A parameter that requires binary input has its type specified as blob (binary large object) in the documentation.

The payload parameter to lamba invoke is one of these blob types that must be base64-encoded.

--payload (blob)
The JSON that you want to provide to your Lambda function as input.

One solution is to use openssl base64 to encode your payload.

echo '{"key": "test"}' > clear_payload
openssl base64 -out encoded_payload -in clear_payload
aws lambda invoke --function-name testsms  --invocation-type Event --payload file://~/encoded_payload response.json
```

Body:
I am getting an error when I try and invoke a lambda function from the AWS CLI. I am using version 2 of the CLI.
I understand that I should pass the --payload argument as a string containing a JSON object.

aws lambda invoke --function-name testsms  --invocation-type Event --payload '{"key": "test"}' response.json

I get the following error:

Invalid base64: "{"key": "test"}"

I have tried all sorts of variants for the JSON escaping characters etc. I have also tried to use the file://test.json option I receive the same error.


问:
Passing values from Django template to javascript-ajax function
Now my template displays a table having a link on each row to display more details. Each row passes unique column_name, db_name, schema_name, tablenm combination to get more details.

```<code><td>
    <a href="{% url 'moreDetails' column_name=row.colname db_name=row.dbname schema_name=row.schemaname table_name=row.tablenm %} " target="_blank">
        Values
    </a>
</td>
</code>```

The above code works , but open a new window for the result set. But, I would like to route it through a javascript(Jquery-django) and capture the result back in Javascript and display the result as a javascript message without refreshing the complete page.

How Can I pass there values (column_name, db_name, schema_name, tablenm) to the java script on the click event

I tried replacing href with button and set a value to it

```<code><td>
    <input type="button" value={% row.colname |","| row.dbname |","| row.schemaname |","| row.tablenm %} class="apireq" />
<td>
</code>```

But seems not working. I welcome any help on this . Thanks In advance

答:
Why not set them as data attributes?

```<code><input type="button" class="apireq"
       data-colname="{{row.colname}}"
       data-dbname="{{row.dbname}}"
       data-schemaname="{{row.schemaname}}"
       data-tablenm="{{row.tablenm}}"
/>
</code>```

Then in your click event handler you will have a reference to the button that generated the event, all you need to to is read the attributes off of it. And they are already parsed out so no worries there too.

Body:
Now my template displays a table having a link on each row to display more details. Each row passes unique column_name, db_name, schema_name, tablenm combination to get more details.

        Values

The above code works , but open a new window for the result set. But, I would like to route it through a javascript(Jquery-django) and capture the result back in Javascript and display the result as a javascript message without refreshing the complete page.

How Can I pass there values (column_name, db_name, schema_name, tablenm) to the java script on the click event

I tried replacing href with button and set a value to it

    <input type="button" value={% row.colname |","| row.dbname |","| row.schemaname |","| row.tablenm %} class="apireq" />

But seems not working. I welcome any help on this . Thanks In advance

Body:
Why not set them as data attributes?

<input type="button" class="apireq"
       data-colname="{{row.colname}}"
       data-dbname="{{row.dbname}}"
       data-schemaname="{{row.schemaname}}"
       data-tablenm="{{row.tablenm}}"
/>

Then in your click event handler you will have a reference to the button that generated the event, all you need to to is read the attributes off of it. And they are already parsed out so no worries there too.


问:
Rails multiple developers environments
In our company, people are using different operating systems. I am using Linux and have line in development.rb like:

Paperclip.options[:command_path] = "/usr/bin"

Designer, who is on Windows need different line. Is there any way, how to manage different developers in ruby on rails? Thanks a lot!

答:
One solution:
Create a folder in config called "personal", and put a file in it, the contents of which are set to be ignored in whatever source control system you use.  Then within that, each developer can set their own options which override the above.  To make sure that it doesn't matter which line gets evaluated first, you set it up like:

```<code>#in config/development.rb
Paperclip.options[:command_path] ||= "/usr/bin"

#in config/personal/overrides.rb
if RAILS_ENV == "development"
  Paperclip.options[:command_path] = "/my/local/path"
end
</code>```

Now, if overrides runs first, the line in development.rb won't  override it.

I do something similar in this in one of my projects to send out emails in dev mode using a gmail account i own instead of the usual email sending system.

Title: Rails multiple developers environments

Body:
One solution:
Create a folder in config called "personal", and put a file in it, the contents of which are set to be ignored in whatever source control system you use.  Then within that, each developer can set their own options which override the above.  To make sure that it doesn't matter which line gets evaluated first, you set it up like:

#in config/development.rb
Paperclip.options[:command_path] ||= "/usr/bin"

#in config/personal/overrides.rb
if RAILS_ENV == "development"
  Paperclip.options[:command_path] = "/my/local/path"
end

Now, if overrides runs first, the line in development.rb won't  override it.

I do something similar in this in one of my projects to send out emails in dev mode using a gmail account i own instead of the usual email sending system.


问:
group collide does not work on platform scroller with Pygame
I following this tutorial and I have added class Opponent() to class Platform() as shown here. Next I have been trying to add groupcollide_and_loop_for to the complete code so that the opponent is removed when hit by the bullet. I have been looking at this question about using groupcollide within class Opponent() itself. I tried several ways to call groupcollide inside def main in while not done but I didn't get any results or any errors, it just didn't work.

groupcollide_and_loop_for:

```<code>    collided_opponents = pygame.sprite.groupcollide(opponents, bullet_list, False, True)
    for opponent, bullets in collided_opponents.items():
        for bullet in bullets:
            score += 1  # Increment the score.
            opponent.lives -= 1  # Decrement the lives.
            pygame.display.set_caption(str(score))
</code>```

Deploy the groupcollide and for loop above to the code below:

```<code>import pygame

# Global constants
bulletpicture = pygame.image.load("bullet.png")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

class Player(pygame.sprite.Sprite):
    """
    This class represents the bar at the bottom that the player controls.
    """

    # -- Methods
    def __init__(self):
        """ Constructor function """

        # Call the parent's constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        width = 40
        height = 60
        self.image = pygame.Surface([width, height])
        self.image.fill(RED)

        # Set a referance to the image rect.
        self.rect = self.image.get_rect()

        # Set speed vector of player
        self.change_x = 0
        self.change_y = 0

        # List of sprites we can bump against
        self.level = None

    def update(self):
        """ Move the player. """
        # Gravity
        self.calc_grav()

        # Move left/right
        self.rect.x += self.change_x

        # See if we hit anything
        block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
        for block in block_hit_list:
            # If we are moving right,
            # set our right side to the left side of the item we hit
            if self.change_x > 0:
                self.rect.right = block.rect.left
            elif self.change_x < 0:
                # Otherwise if we are moving left, do the opposite.
                self.rect.left = block.rect.right

        # Move up/down
        self.rect.y += self.change_y

        # Check and see if we hit anything
        block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
        for block in block_hit_list:

            # Reset our position based on the top/bottom of the object.
            if self.change_y > 0:
                self.rect.bottom = block.rect.top
            elif self.change_y < 0:
                self.rect.top = block.rect.bottom

            # Stop our vertical movement
            self.change_y = 0

    def calc_grav(self):
        """ Calculate effect of gravity. """
        if self.change_y == 0:
            self.change_y = 1
        else:
            self.change_y += .35

        # See if we are on the ground.
        if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
            self.change_y = 0
            self.rect.y = SCREEN_HEIGHT - self.rect.height

    def jump(self):
        """ Called when user hits 'jump' button. """

        # move down a bit and see if there is a platform below us.
        # Move down 2 pixels because it doesn't work well if we only move down 1
        # when working with a platform moving down.
        self.rect.y += 2
        platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
        self.rect.y -= 2

        # If it is ok to jump, set our speed upwards
        if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
            self.change_y = -10

    # Player-controlled movement:
    def go_left(self):
        """ Called when the user hits the left arrow. """
        self.change_x = -6

    def go_right(self):
        """ Called when the user hits the right arrow. """
        self.change_x = 6

    def stop(self):
        """ Called when the user lets off the keyboard. """
        self.change_x = 0

class Platform(pygame.sprite.Sprite):
    """ Platform the user can jump on """

    def __init__(self, width, height):
        """ Platform constructor. Assumes constructed with user passing in
            an array of 5 numbers like what's defined at the top of this code.
            """
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(GREEN)

        self.rect = self.image.get_rect()

class Level():
    """ This is a generic super-class used to define a level.
        Create a child class for each level with level-specific
        info. """

    def __init__(self, player):
        """ Constructor. Pass in a handle to player. Needed for when moving
            platforms collide with the player. """
        self.platform_list = pygame.sprite.Group()
        self.enemy_list = pygame.sprite.Group()
        self.player = player

        # How far this world has been scrolled left/right
        self.world_shift = 0

    # Update everythign on this level
    def update(self):
        """ Update everything in this level."""
        self.platform_list.update()
        self.enemy_list.update()

    def draw(self, screen):
        """ Draw everything on this level. """

        # Draw the background
        screen.fill(BLUE)

        # Draw all the sprite lists that we have
        self.platform_list.draw(screen)
        self.enemy_list.draw(screen)

    def shift_world(self, shift_x):
        """ When the user moves left/right and we need to scroll
        everything: """

        # Keep track of the shift amount
        self.world_shift += shift_x

        # Go through all the sprite lists and shift
        for platform in self.platform_list:
            platform.rect.x += shift_x

        for enemy in self.enemy_list:
            enemy.rect.x += shift_x

class Bullet(pygame.sprite.Sprite):
    """This class represents the bullet."""

    def __init__(self,x,y):
        super().__init__()
        self.image = bulletpicture

        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
    def update(self):
        """Move the bullet."""
        self.rect.y -= 5
        # Remove the bullet if it flies up off the screen
        if self.rect.y < -12:
            self.kill()  # Remove the sprite from all sprite groups.

class Opponent(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()
        self.image = pygame.image.load("cowboy.png") #.convert()
        self.rect = self.image.get_rect()
        self.lives = 1
        self.rect.x = 50
        self.rect.y = 280
        self.change_x = 1
        self.change_y = 0
        # List of sprites we can bump against
        self.level = None

        pass
    def update(self):
        if self.lives <= 0:
            self.kill()  # Remove the sprite from all sprite groups.
        self.rect.x += self.change_x
        if self.rect.x > 280:
           self.change_x *= -1
           self.rect.x += self.change_x
        if self.rect.x < 0:
           self.change_x *= -1
           self.rect.x += self.change_x
        pass

# Create platforms for the level
class Level_01(Level):
    """ Definition for level 1. """

    def __init__(self, player):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = -1000

        # Array with width, height, x, and y of platform
        level = [[210, 70, 500, 500],
                 [210, 70, 800, 400],
                 [210, 70, 1000, 500],
                 [210, 70, 1120, 280],
                 ]

        # Go through the array above and add platforms
        for platform in level:
            block = Platform(platform[0], platform[1])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            block.player = self.player
            self.platform_list.add(block)

        for enemy in level:
            opponent = Opponent()
            opponent.rect.x = 150
            opponent.rect.y = 280
            opponent.player = self.player
            self.enemy_list.add(opponent)

# Create platforms for the level
class Level_02(Level):
    """ Definition for level 2. """

    def __init__(self, player):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = -1000

        # Array with type of platform, and x, y location of the platform.
        level = [[210, 30, 450, 570],
                 [210, 30, 850, 420],
                 [210, 30, 1000, 520],
                 [210, 30, 1120, 280],
                 ]

        # Go through the array above and add platforms
        for platform in level:
            block = Platform(platform[0], platform[1])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            block.player = self.player
            self.platform_list.add(block)

def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("Side-scrolling Platformer")

    # Create the player
    player = Player()

    # Create all the levels
    level_list = []
    level_list.append(Level_01(player))
    level_list.append(Level_02(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 340
    player.rect.y = SCREEN_HEIGHT - player.rect.height
    active_sprite_list.add(player)

    # --- NEW
    bullet_list = pygame.sprite.Group()
    player_list = pygame.sprite.Group()
    player_list.add(player)
    opponent = Opponent()
    opponents = pygame.sprite.Group()
    opponents.add(opponent)
    score = 0

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                 # Click a mouse button to instantiate a bullet.
                 bullet = Bullet(player.rect.x,player.rect.y)
                 bullet_list.add(bullet)
                 active_sprite_list.add(bullet)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # Update the player.
        active_sprite_list.update()
 #  ----- The code commented below is what I tried in many ways
        #collided_opponents = pygame.sprite.groupcollide(opponents, bullet_list, False, True)
        #for opponent, bullets in collided_opponents.items():
        #    for bullet in bullets:
        #        score += 1  # Increment the score.
        #        opponent.lives -= 1  # Decrement the lives.
        #        pygame.display.set_caption(str(score))

        # Update items in the level
        current_level.update()

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.right >= 500:
            diff = player.rect.right - 500
            player.rect.right = 500
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.left <= 120:
            diff = 120 - player.rect.left
            player.rect.left = 120
            current_level.shift_world(diff)

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list)-1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        active_sprite_list.draw(screen)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()

if __name__ == "__main__":
    main()
</code>```

答:
I used print() to see position for opponent and bullet. And I found that opponent never change position.

After digging in code I found you create two opponents.

in main() you create opponent which is not added to active_sprite_list so it doesn't move and it isn't displayed but you use it to check collision

in Level_01() you create opponent which is added to active_sprite_list so it moves and it is displayed on screen but you don't use it to check collision.

Because you check collision with opponent which never move so it never collide with bullet.

In main() you have to remove

```<code>opponent = Opponent()
opponents = pygame.sprite.Group()
opponents.add(opponent)
</code>```

and use

```<code>#opponents = level_list[current_level_no].enemy_list
opponents = current_level.enemy_list
</code>```

And use it also when you change level

```<code>current_level_no += 1
current_level = level_list[current_level_no]

#opponents = level_list[current_level_no].enemy_list
opponents = current_level.enemy_list
</code>```

Body:
I following this tutorial and I have added class Opponent() to class Platform() as shown here. Next I have been trying to add groupcollide_and_loop_for to the complete code so that the opponent is removed when hit by the bullet. I have been looking at this question about using groupcollide within class Opponent() itself. I tried several ways to call groupcollide inside def main in while not done but I didn't get any results or any errors, it just didn't work.

groupcollide_and_loop_for:

    collided_opponents = pygame.sprite.groupcollide(opponents, bullet_list, False, True)
    for opponent, bullets in collided_opponents.items():
        for bullet in bullets:
            score += 1  # Increment the score.
            opponent.lives -= 1  # Decrement the lives.
            pygame.display.set_caption(str(score))

Deploy the groupcollide and for loop above to the code below:

import pygame

# Global constants
bulletpicture = pygame.image.load("bullet.png")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

class Player(pygame.sprite.Sprite):
    """
    This class represents the bar at the bottom that the player controls.
    """

    # -- Methods
    def __init__(self):
        """ Constructor function """

        # Call the parent's constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        width = 40
        height = 60
        self.image = pygame.Surface([width, height])
        self.image.fill(RED)

        # Set a referance to the image rect.
        self.rect = self.image.get_rect()

        # Set speed vector of player
        self.change_x = 0
        self.change_y = 0

        # List of sprites we can bump against
        self.level = None

    def update(self):
        """ Move the player. """
        # Gravity
        self.calc_grav()

        # Move left/right
        self.rect.x += self.change_x

        # See if we hit anything
        block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
        for block in block_hit_list:
            # If we are moving right,
            # set our right side to the left side of the item we hit
            if self.change_x > 0:
                self.rect.right = block.rect.left
            elif self.change_x < 0:
                # Otherwise if we are moving left, do the opposite.
                self.rect.left = block.rect.right

        # Move up/down
        self.rect.y += self.change_y

        # Check and see if we hit anything
        block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
        for block in block_hit_list:

            # Reset our position based on the top/bottom of the object.
            if self.change_y > 0:
                self.rect.bottom = block.rect.top
            elif self.change_y < 0:
                self.rect.top = block.rect.bottom

            # Stop our vertical movement
            self.change_y = 0

    def calc_grav(self):
        """ Calculate effect of gravity. """
        if self.change_y == 0:
            self.change_y = 1
        else:
            self.change_y += .35

        # See if we are on the ground.
        if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
            self.change_y = 0
            self.rect.y = SCREEN_HEIGHT - self.rect.height

    def jump(self):
        """ Called when user hits 'jump' button. """

        # move down a bit and see if there is a platform below us.
        # Move down 2 pixels because it doesn't work well if we only move down 1
        # when working with a platform moving down.
        self.rect.y += 2
        platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
        self.rect.y -= 2

        # If it is ok to jump, set our speed upwards
        if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
            self.change_y = -10

    # Player-controlled movement:
    def go_left(self):
        """ Called when the user hits the left arrow. """
        self.change_x = -6

    def go_right(self):
        """ Called when the user hits the right arrow. """
        self.change_x = 6

    def stop(self):
        """ Called when the user lets off the keyboard. """
        self.change_x = 0

class Platform(pygame.sprite.Sprite):
    """ Platform the user can jump on """

    def __init__(self, width, height):
        """ Platform constructor. Assumes constructed with user passing in
            an array of 5 numbers like what's defined at the top of this code.
            """
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(GREEN)

        self.rect = self.image.get_rect()

class Level():
    """ This is a generic super-class used to define a level.
        Create a child class for each level with level-specific
        info. """

    def __init__(self, player):
        """ Constructor. Pass in a handle to player. Needed for when moving
            platforms collide with the player. """
        self.platform_list = pygame.sprite.Group()
        self.enemy_list = pygame.sprite.Group()
        self.player = player

        # How far this world has been scrolled left/right
        self.world_shift = 0

    # Update everythign on this level
    def update(self):
        """ Update everything in this level."""
        self.platform_list.update()
        self.enemy_list.update()

    def draw(self, screen):
        """ Draw everything on this level. """

        # Draw the background
        screen.fill(BLUE)

        # Draw all the sprite lists that we have
        self.platform_list.draw(screen)
        self.enemy_list.draw(screen)

    def shift_world(self, shift_x):
        """ When the user moves left/right and we need to scroll
        everything: """

        # Keep track of the shift amount
        self.world_shift += shift_x

        # Go through all the sprite lists and shift
        for platform in self.platform_list:
            platform.rect.x += shift_x

        for enemy in self.enemy_list:
            enemy.rect.x += shift_x

class Bullet(pygame.sprite.Sprite):
    """This class represents the bullet."""

    def __init__(self,x,y):
        super().__init__()
        self.image = bulletpicture

        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
    def update(self):
        """Move the bullet."""
        self.rect.y -= 5
        # Remove the bullet if it flies up off the screen
        if self.rect.y < -12:
            self.kill()  # Remove the sprite from all sprite groups.

class Opponent(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()
        self.image = pygame.image.load("cowboy.png") #.convert()
        self.rect = self.image.get_rect()
        self.lives = 1
        self.rect.x = 50
        self.rect.y = 280
        self.change_x = 1
        self.change_y = 0
        # List of sprites we can bump against
        self.level = None

        pass
    def update(self):
        if self.lives <= 0:
            self.kill()  # Remove the sprite from all sprite groups.
        self.rect.x += self.change_x
        if self.rect.x > 280:
           self.change_x *= -1
           self.rect.x += self.change_x
        if self.rect.x < 0:
           self.change_x *= -1
           self.rect.x += self.change_x
        pass

# Create platforms for the level
class Level_01(Level):
    """ Definition for level 1. """

    def __init__(self, player):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = -1000

        # Array with width, height, x, and y of platform
        level = [[210, 70, 500, 500],
                 [210, 70, 800, 400],
                 [210, 70, 1000, 500],
                 [210, 70, 1120, 280],
                 ]

        # Go through the array above and add platforms
        for platform in level:
            block = Platform(platform[0], platform[1])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            block.player = self.player
            self.platform_list.add(block)

        for enemy in level:
            opponent = Opponent()
            opponent.rect.x = 150
            opponent.rect.y = 280
            opponent.player = self.player
            self.enemy_list.add(opponent)

# Create platforms for the level
class Level_02(Level):
    """ Definition for level 2. """

    def __init__(self, player):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = -1000

        # Array with type of platform, and x, y location of the platform.
        level = [[210, 30, 450, 570],
                 [210, 30, 850, 420],
                 [210, 30, 1000, 520],
                 [210, 30, 1120, 280],
                 ]

        # Go through the array above and add platforms
        for platform in level:
            block = Platform(platform[0], platform[1])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            block.player = self.player
            self.platform_list.add(block)

def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("Side-scrolling Platformer")

    # Create the player
    player = Player()

    # Create all the levels
    level_list = []
    level_list.append(Level_01(player))
    level_list.append(Level_02(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 340
    player.rect.y = SCREEN_HEIGHT - player.rect.height
    active_sprite_list.add(player)

    # --- NEW
    bullet_list = pygame.sprite.Group()
    player_list = pygame.sprite.Group()
    player_list.add(player)
    opponent = Opponent()
    opponents = pygame.sprite.Group()
    opponents.add(opponent)
    score = 0

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                 # Click a mouse button to instantiate a bullet.
                 bullet = Bullet(player.rect.x,player.rect.y)
                 bullet_list.add(bullet)
                 active_sprite_list.add(bullet)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # Update the player.
        active_sprite_list.update()
 #  ----- The code commented below is what I tried in many ways
        #collided_opponents = pygame.sprite.groupcollide(opponents, bullet_list, False, True)
        #for opponent, bullets in collided_opponents.items():
        #    for bullet in bullets:
        #        score += 1  # Increment the score.
        #        opponent.lives -= 1  # Decrement the lives.
        #        pygame.display.set_caption(str(score))

        # Update items in the level
        current_level.update()

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.right >= 500:
            diff = player.rect.right - 500
            player.rect.right = 500
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.left <= 120:
            diff = 120 - player.rect.left
            player.rect.left = 120
            current_level.shift_world(diff)

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list)-1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        active_sprite_list.draw(screen)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()

if __name__ == "__main__":
    main()

Body:
I used print() to see position for opponent and bullet. And I found that opponent never change position.

After digging in code I found you create two opponents.

in main() you create opponent which is not added to active_sprite_list so it doesn't move and it isn't displayed but you use it to check collision

in Level_01() you create opponent which is added to active_sprite_list so it moves and it is displayed on screen but you don't use it to check collision.

Because you check collision with opponent which never move so it never collide with bullet.

In main() you have to remove

opponent = Opponent()
opponents = pygame.sprite.Group()
opponents.add(opponent)

and use

#opponents = level_list[current_level_no].enemy_list
opponents = current_level.enemy_list

And use it also when you change level

current_level_no += 1
current_level = level_list[current_level_no]

#opponents = level_list[current_level_no].enemy_list
opponents = current_level.enemy_list


问:
open Print Server Properties menu with C#
I'm looking for a way to open with C# "Print Server Properties Menu"

With the following code i can open the setting menu for printers:

```<code>Process.Start("ms-settings:printers");
</code>```

I can't find what code i need to open the "print server properties menu"

答:
you can load printui.dll with the rundll32 library loader and execute PrintUIEntry with the /s flag:

```<code>            var psi = new ProcessStartInfo()
            {
                FileName = "rundll32",
                Arguments = "printui.dll, PrintUIEntry /s",
                UseShellExecute = false
            };
            Process.Start(psi);
</code>```

This can help:

https://learn.microsoft.com/it-it/windows-server/administration/windows-commands/rundll32-printui

Body:
I'm looking for a way to open with C# "Print Server Properties Menu"

With the following code i can open the setting menu for printers:

Process.Start("ms-settings:printers");

I can't find what code i need to open the "print server properties menu"

Body:
you can load printui.dll with the rundll32 library loader and execute PrintUIEntry with the /s flag:

            var psi = new ProcessStartInfo()
            {
                FileName = "rundll32",
                Arguments = "printui.dll, PrintUIEntry /s",
                UseShellExecute = false
            };
            Process.Start(psi);

This can help:

https://learn.microsoft.com/it-it/windows-server/administration/windows-commands/rundll32-printui


问:
What is the most efficient / best practise to Upsert 5000+ rows without Merge in SQL Server?
I have a web application which receives about 50 hits per second, and on each hit I am upsert'ing around 10 records in a central SQL Server database. Roughly once every 3 seconds I am upserting 5000+ rows for a single inbound connection.

Currently I have a stored procedure which takes XML as a parameter. I do an INSERT into my main table from my XML where a row field doesn't match, then update the whole table with values from my XML.

The operation isn't slow by any means, but I really would like to know the best way to do this. I am running on SQL Server 2005 so I don't have the MERGE operation.

答:
I would do the UPDATE first otherwise you'll update the rows you've just inserted

```<code>SELECT .. INTO #temp FROM (shredXML)

BEGIN TRAN

UPDATE ... FROM WHERE (matches using #temp)

INSERT ... SELECT ... FROM #temp WHERE NOT EXISTS

COMMIT
</code>```

I'd also consider changing the XML to a temp table and use SQLBulkCopy. We've found this to be more efficient then parsing XML generally for more than a few hundred rows. If you can't change this then do you shred the XML into a temp table first?

Body:
I would do the UPDATE first otherwise you'll update the rows you've just inserted

SELECT .. INTO #temp FROM (shredXML)

BEGIN TRAN

UPDATE ... FROM WHERE (matches using #temp)

INSERT ... SELECT ... FROM #temp WHERE NOT EXISTS

COMMIT

I'd also consider changing the XML to a temp table and use SQLBulkCopy. We've found this to be more efficient then parsing XML generally for more than a few hundred rows. If you can't change this then do you shred the XML into a temp table first?


问:
"An error occurred: LogGroup - <resource name> already exists" while trying to deploy Serverless
after running sls deploy -v && sls s3deploy as I normally do, I ran into this issue:

```<code>...

CloudFormation - CREATE_FAILED - AWS::Logs::LogGroup - CallTextractLogGroup

...

CloudFormation - CREATE_FAILED - AWS::IAM::Role - IamRoleStateMachineExecution
CloudFormation - CREATE_FAILED - AWS::Logs::LogGroup - StartTextractStateMachineLogGroup
CloudFormation - CREATE_FAILED - AWS::Lambda::LayerVersion - Boto3LayerLambdaLayer

...

  Serverless Error ---------------------------------------

  An error occurred: StartTextractStateMachineLogGroup - /aws/lambda/textract-service-dev-startTextractStateMachine already exists.

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com

  Your Environment Information ---------------------------
     OS:                     linux
     Node Version:           12.2.0
     Serverless Version:     1.42.3
</code>```

I don't remember changing anything at all before deployment, other than adding Retry sections to my Step Function States, which shouldn't have messed with CF logs at all.

I tried running sls remove and then my deployment command again, no luck there.

Also tried adding cfLogs: true to my provider section in the YAML, no love!

I tried manually deleting the LogGroup in the CloudWatch console, but it's not even there.

Here is my serverless.yml:

```<code>service: textract-service

provider:
  name: aws
  runtime: python3.7
  timeout: 10
  region: us-east-1
  cfLogs: true
  environment:
    STATE_MACHINE_ARN: ${self:resources.Outputs.TextractStepFunctions.Value}
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "s3:PutObject"
        - "states:*"
      Resource:
        Fn::Join:
          - ""
          - - "the-chumiest-bucket-ARN or *"
            - ${self:resources.Outputs.TextractStepFunctions.Value}

plugins:
  - serverless-plugin-existing-s3
  - serverless-step-functions
  - serverless-pseudo-parameters
  - serverless-plugin-existing-s3
layers:
  boto3Layer:
    package:
      artifact: boto3_layer.zip
    allowedAccounts:
      - "*"

functions:
  startTextractStateMachine:
    handler: src/start_textract_state_machine.lambda_handler
    role: the-chumiest-bucket-role
    layers:
      - {Ref: Boto3LayerLambdaLayer}
    events:
      - existingS3:
          bucket: the-chumiest-bucket
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: input1/
            - suffix: .pdf
  callTextract:
    handler: src/call_textract.lambda_handler
    role: the-chumiest-bucket-role

    layers:
      - {Ref: Boto3LayerLambdaLayer}
  getTextractOutput:
    handler: src/get_textract_output.lambda_handler
    role: the-chumiest-bucket-role

    layers:
      - {Ref: Boto3LayerLambdaLayer}
  parseTextractOutput:
    handler: src/parse_textract_output.lambda_handler
    role: the-chumiest-bucket-role

    layers:
      - {Ref: Boto3LayerLambdaLayer}

stepFunctions:
  stateMachines:
    textractStepFunc:
      name: TextractStepFunctions
      definition:
        Comment: A state machine for the Textract OCR process.
        StartAt: StartTextractStateMachine
        States:
          StartTextractStateMachine:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-startTextractStateMachine"
            Next: CallTextract
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
          CallTextract:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-callTextract"
            Next: GetTextractOutput
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
          GetTextractOutput:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-getTextractOutput"
            Next: ParseTextractOutput
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
          ParseTextractOutput:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-parseTextractOutput"
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
            End: true

resources:
  Outputs:
    TextractStepFunctions:
      Description: The ARN of the state machine
      Value:
        Ref: TextractStepFunctions
</code>```

答: I hit this with a rename of the service, just had to delete the CloudFormation Stack of the old named service.</p>

Body:
after running sls deploy -v && sls s3deploy as I normally do, I ran into this issue:

...

CloudFormation - CREATE_FAILED - AWS::Logs::LogGroup - CallTextractLogGroup

...

CloudFormation - CREATE_FAILED - AWS::IAM::Role - IamRoleStateMachineExecution
CloudFormation - CREATE_FAILED - AWS::Logs::LogGroup - StartTextractStateMachineLogGroup
CloudFormation - CREATE_FAILED - AWS::Lambda::LayerVersion - Boto3LayerLambdaLayer

...

  Serverless Error ---------------------------------------

  An error occurred: StartTextractStateMachineLogGroup - /aws/lambda/textract-service-dev-startTextractStateMachine already exists.

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com

  Your Environment Information ---------------------------
     OS:                     linux
     Node Version:           12.2.0
     Serverless Version:     1.42.3

I don't remember changing anything at all before deployment, other than adding Retry sections to my Step Function States, which shouldn't have messed with CF logs at all.

I tried running sls remove and then my deployment command again, no luck there.

Also tried adding cfLogs: true to my provider section in the YAML, no love!

I tried manually deleting the LogGroup in the CloudWatch console, but it's not even there.

Here is my serverless.yml:

service: textract-service

provider:
  name: aws
  runtime: python3.7
  timeout: 10
  region: us-east-1
  cfLogs: true
  environment:
    STATE_MACHINE_ARN: ${self:resources.Outputs.TextractStepFunctions.Value}
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "s3:PutObject"
        - "states:*"
      Resource:
        Fn::Join:
          - ""
          - - "the-chumiest-bucket-ARN or *"
            - ${self:resources.Outputs.TextractStepFunctions.Value}

plugins:
  - serverless-plugin-existing-s3
  - serverless-step-functions
  - serverless-pseudo-parameters
  - serverless-plugin-existing-s3
layers:
  boto3Layer:
    package:
      artifact: boto3_layer.zip
    allowedAccounts:
      - "*"

functions:
  startTextractStateMachine:
    handler: src/start_textract_state_machine.lambda_handler
    role: the-chumiest-bucket-role
    layers:
      - {Ref: Boto3LayerLambdaLayer}
    events:
      - existingS3:
          bucket: the-chumiest-bucket
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: input1/
            - suffix: .pdf
  callTextract:
    handler: src/call_textract.lambda_handler
    role: the-chumiest-bucket-role

    layers:
      - {Ref: Boto3LayerLambdaLayer}
  getTextractOutput:
    handler: src/get_textract_output.lambda_handler
    role: the-chumiest-bucket-role

    layers:
      - {Ref: Boto3LayerLambdaLayer}
  parseTextractOutput:
    handler: src/parse_textract_output.lambda_handler
    role: the-chumiest-bucket-role

    layers:
      - {Ref: Boto3LayerLambdaLayer}

stepFunctions:
  stateMachines:
    textractStepFunc:
      name: TextractStepFunctions
      definition:
        Comment: A state machine for the Textract OCR process.
        StartAt: StartTextractStateMachine
        States:
          StartTextractStateMachine:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-startTextractStateMachine"
            Next: CallTextract
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
          CallTextract:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-callTextract"
            Next: GetTextractOutput
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
          GetTextractOutput:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-getTextractOutput"
            Next: ParseTextractOutput
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
          ParseTextractOutput:
            Type: Task
            Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-parseTextractOutput"
            Retry:
              - ErrorEquals:
                - HandledError
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
              - ErrorEquals:
                - States.ALL
                IntervalSeconds: 1
                MaxAttempts: 1
                BackoffRate: 2
            End: true

resources:
  Outputs:
    TextractStepFunctions:
      Description: The ARN of the state machine
      Value:
        Ref: TextractStepFunctions


问:
Can't access to Object Value
I'm building my React Component and got this error when I tried to use a axios request and add that response data to an object. But when I tried to console.log the object, it showed me the value when I expanded the object, but still display null.

```<code>let id, title, channel;

  let details = {
    timestamp: null,
    views: null,
    likes: null,
    description: null
  };

  if (active == undefined) {
    active = {};
  } else {
    id = active.id;
    title = active.title;
    channel = active.channel;
    let dataObject = API.get(`videos/${id}`, {
      params: {
        api_key: "ab4d78b8-e8ff-4392-bff8-21d1058cd420"
      }
    });
    dataObject.then(result => {
      let data = result.data;
      details.timestamp = data.timestamp;
      details.views = data.views;
      details.likes = data.likes;
      details.description = data.description;
    });
  }
  return (
    <div className="videoContent">
      <h1 className="videoContent__title">{title}</h1>
      <div className="videoContent__details">
        <div className="videoContent__details--user">
          <p className="channel">By {channel}</p>
          <p className="timestamp">{dateFormat(details.timestamp)}</p>
        </div>
        <div className="videoContent__details--social">
          <p className="views">
            <img src={viewIcon} alt=""></img>
            {/* {details.views} */}
          </p>
          <p className="likes">
            <img src={likeIcon} alt=""></img>
            {/* {props.details.likes.toLocaleString()} */}
          </p>
        </div>
      </div>
      <div className="videoContent__description">
        {/* <p>{details.description}</p> */}
      </div>
    </div>
  );
}
</code>```

And this is what I got from the console:

```<code>{
  timestamp: null,
  views: null,
  likes: null,
  description: null
}
</code>```

```<code>timestamp: 1537003624000
views: "2,043,765"
likes: "400,058"
description: "Luxury is something everyone deserves from time to time. Such
an indulgence can make a vacation a truly rejuvenating experience. This video will
focus a lot on helping the first time or inexperienced traveler head out prepared and
confident in themselves."
__proto__: Object
</code>```

Edit: My axios call:

```<code>import axios from "axios";

export default axios.create({
  baseURL: "https://project-2-api.herokuapp.com/",
  responseType: "json"
});
</code>```

答:
JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

to solve your problem you should use promises or Async/await,try to modify your code like below:

```<code>let dataObject = () => {
    return new Promise((resolve, reject) => {
        API.get(`videos/${id}`, {
            params:{
                api_key: "ab4d78b8-e8ff-4392-bff8-21d1058cd420"
            }
        }, function(error, response, data){
            if (error) reject(error);

            let content = JSON.parse(data);
            let result = content.value;
            resolve(result);
          })
        }
    );
};

dataObject(url)
.then(result => {
    let data = result.data;
    details.timestamp = data.timestamp;
    details.views = data.views;
    details.likes = data.likes;
    details.description = data.description;
    return (<div>...</div>)
})
.catch(err => {
    console.(error)
});
</code>```

Title: Can't access to Object Value

Body:
I'm building my React Component and got this error when I tried to use a axios request and add that response data to an object. But when I tried to console.log the object, it showed me the value when I expanded the object, but still display null.

let id, title, channel;

  let details = {
    timestamp: null,
    views: null,
    likes: null,
    description: null
  };

  if (active == undefined) {
    active = {};
  } else {
    id = active.id;
    title = active.title;
    channel = active.channel;
    let dataObject = API.get(`videos/${id}`, {
      params: {
        api_key: "ab4d78b8-e8ff-4392-bff8-21d1058cd420"
      }
    });
    dataObject.then(result => {
      let data = result.data;
      details.timestamp = data.timestamp;
      details.views = data.views;
      details.likes = data.likes;
      details.description = data.description;
    });
  }
  return (

{title}

By {channel}

{dateFormat(details.timestamp)}

            {/* {details.views} */}

            {/* {props.details.likes.toLocaleString()} */}

        {/*
{details.description}
 */}

  );
}

And this is what I got from the console:

{
  timestamp: null,
  views: null,
  likes: null,
  description: null
}

timestamp: 1537003624000
views: "2,043,765"
likes: "400,058"
description: "Luxury is something everyone deserves from time to time. Such
an indulgence can make a vacation a truly rejuvenating experience. This video will
focus a lot on helping the first time or inexperienced traveler head out prepared and
confident in themselves."
__proto__: Object

Edit: My axios call:

import axios from "axios";

export default axios.create({
  baseURL: "https://project-2-api.herokuapp.com/",
  responseType: "json"
});

Body:
JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

to solve your problem you should use promises or Async/await,try to modify your code like below:

let dataObject = () => {
    return new Promise((resolve, reject) => {
        API.get(`videos/${id}`, {
            params:{
                api_key: "ab4d78b8-e8ff-4392-bff8-21d1058cd420"
            }
        }, function(error, response, data){
            if (error) reject(error);

            let content = JSON.parse(data);
            let result = content.value;
            resolve(result);
          })
        }
    );
};

dataObject(url)
.then(result => {
    let data = result.data;
    details.timestamp = data.timestamp;
    details.views = data.views;
    details.likes = data.likes;
    details.description = data.description;
    return (<div>...</div>)
})
.catch(err => {
    console.(error)
});


问:
Balance sheet measure DAX (fill blanks)
Background I'm trying to build a balance sheet in Power BI based on a transaction file. My report has a transaction table containing classic accounting transactions (account number, amount, description, date etc.), an allocation table which allocates accounts to a balance sheet, P&L or cashflow hierarchy (account, PLlvl1, PLlvl2 etc.) and a calendar table.

Constructing a proper running total measure to sum all previous transactions creating a basic balance measure is pretty straight forward, see code below.

```<code>Balance =
    CALCULATE(
        SUM ( data[Amount] ) ;
        FILTER(
            ALL( '$Calendar' );
            '$Calendar'[Date] <= MAX( '$Calendar'[Date] )
        )
    )
</code>```

Problem This works fine at low resolutions (year) however, when making a month on month overview, the summation only show a value in periods where there was a mutation, all other months remain empty.

Desired solution In this simplified example, my desired result would be for the the blanks to carry over values from the previous period, the -350 also showing in February and March, the -700 in May and June etc. etc. but I cant seem to figure a way to do it properly.

Attempts So far I've tried creating a huge cross table between the calendar table and the accounts table but this makes the report grind to a halt pretty fast as soon as I import more data. Furthermore I tried using LASTNONBLANK(), TOTALYTD() and others in several ways even trying a more manual approach like:

```<code>Attempt 6 =
var LastNonBlankDate=
    CALCULATE(
        MAX('$Calendar'[Date]);
        FILTER(
            ALL('$Calendar'[Date]);
            '$Calendar'[Date]<=MAX('$Calendar'[Date]) && SUM(data[Amount])<>0)
        )
RETURN
    CALCULATE(SUM(data[Amount]);
    FILTER(ALL('$Calendar');'$Calendar'[Date]=LastNonBlankDate))
</code>```

Nothing seems to do what I want..

Can somebody help me in the right direction?

A fiddle is temporary available here

答:
Just change your data model relations into "single" from "both":

Never, ever use bi-directional relations unless you have no other choice (which almost never happens except some very rare situations, which is not the case here).

You can also simplify your measure a bit:

```<code>Attempt 3 =
VAR Current_Date = MAX( '$Calendar'[Date] )
RETURN
    CALCULATE(
        SUM ( data[Amount] ) ,
        '$Calendar'[Date] <= Current_Date
    )
</code>```

Result:

Title: Balance sheet measure DAX (fill blanks)

Body:
Background I'm trying to build a balance sheet in Power BI based on a transaction file. My report has a transaction table containing classic accounting transactions (account number, amount, description, date etc.), an allocation table which allocates accounts to a balance sheet, P&L or cashflow hierarchy (account, PLlvl1, PLlvl2 etc.) and a calendar table.

Constructing a proper running total measure to sum all previous transactions creating a basic balance measure is pretty straight forward, see code below.

Balance =
    CALCULATE(
        SUM ( data[Amount] ) ;
        FILTER(
            ALL( '$Calendar' );
            '$Calendar'[Date] <= MAX( '$Calendar'[Date] )
        )
    )

Problem This works fine at low resolutions (year) however, when making a month on month overview, the summation only show a value in periods where there was a mutation, all other months remain empty.

Desired solution In this simplified example, my desired result would be for the the blanks to carry over values from the previous period, the -350 also showing in February and March, the -700 in May and June etc. etc. but I cant seem to figure a way to do it properly.

Attempts So far I've tried creating a huge cross table between the calendar table and the accounts table but this makes the report grind to a halt pretty fast as soon as I import more data. Furthermore I tried using LASTNONBLANK(), TOTALYTD() and others in several ways even trying a more manual approach like:

Attempt 6 =
var LastNonBlankDate=
    CALCULATE(
        MAX('$Calendar'[Date]);
        FILTER(
            ALL('$Calendar'[Date]);
            '$Calendar'[Date]<=MAX('$Calendar'[Date]) && SUM(data[Amount])<>0)
        )
RETURN
    CALCULATE(SUM(data[Amount]);
    FILTER(ALL('$Calendar');'$Calendar'[Date]=LastNonBlankDate))

Nothing seems to do what I want..

Can somebody help me in the right direction?

A fiddle is temporary available here

Body:
Just change your data model relations into "single" from "both":

Never, ever use bi-directional relations unless you have no other choice (which almost never happens except some very rare situations, which is not the case here).

You can also simplify your measure a bit:

Attempt 3 =
VAR Current_Date = MAX( '$Calendar'[Date] )
RETURN
    CALCULATE(
        SUM ( data[Amount] ) ,
        '$Calendar'[Date] <= Current_Date
    )

Result: