问:
Qualtrics Javascript Convert to ISO Date
I'm trying to set up email triggers for surveys on Qualtrics but it's not properly converting to ISOformat. Below is the code.</p>

```<code>Qualtrics.SurveyEngine.addOnload(function()
{
var date1Container = "${q://QID38/ChoiceTextEntryValue}".split("-");
console.log(date1Container);
var date2Container = "${q://QID40/ChoiceTextEntryValue}".split("-");

var date2 = new Date(date2Container[0], date2Container[1],
date2Container[2] );
    date2.setHours(12,0);
    var date1 = new Date(date1Container[0], date1Container[1],
date1Container[2] );
    date1.setHours(12,0);

var REM2 = new Date(date2);
    REM2.setDate(date2.getDate() - 1 );
    REM2.setMonth(date2.getMonth() - 1);
    REM2.setHours(8,30);
var REM1 = new Date(date1);
    REM1.setDate(date1.getDate() -1 );
    REM1.setMonth(date1.getMonth() - 1);
    REM1.setHours(8,30);

Qualtrics.SurveyEngine.setEmbeddedData( 'R1', REM1.toISOString() );
Qualtrics.SurveyEngine.setEmbeddedData( 'R2', REM2.toISOString() );

});
</code>```

答:
You should consider using moment.js. Load moment.js in the survey header, then it can be used to parse and format the date: </p>

```<code>var REM1 = moment("${q://QID38/ChoiceTextEntryValue}").toISOString();
</code>```

Body:
I'm trying to set up email triggers for surveys on Qualtrics but it's not properly converting to ISOformat. Below is the code.

Qualtrics.SurveyEngine.addOnload(function()
{
var date1Container = "${q://QID38/ChoiceTextEntryValue}".split("-");
console.log(date1Container);
var date2Container = "${q://QID40/ChoiceTextEntryValue}".split("-");

var date2 = new Date(date2Container[0], date2Container[1],
date2Container[2] );
    date2.setHours(12,0);
    var date1 = new Date(date1Container[0], date1Container[1],
date1Container[2] );
    date1.setHours(12,0);

var REM2 = new Date(date2);
    REM2.setDate(date2.getDate() - 1 );
    REM2.setMonth(date2.getMonth() - 1);
    REM2.setHours(8,30);
var REM1 = new Date(date1);
    REM1.setDate(date1.getDate() -1 );
    REM1.setMonth(date1.getMonth() - 1);
    REM1.setHours(8,30);

Qualtrics.SurveyEngine.setEmbeddedData( 'R1', REM1.toISOString() );
Qualtrics.SurveyEngine.setEmbeddedData( 'R2', REM2.toISOString() );

});

Body:
You should consider using moment.js. Load moment.js in the survey header, then it can be used to parse and format the date:

var REM1 = moment("${q://QID38/ChoiceTextEntryValue}").toISOString();


来源: stackexchange

问:
Pasting Extra Characters to Each element of a List Using Purrr Package R
I have a list I want to iterate over and add characters to the end of each word. However, depending on the element in the list I would like to change the word being added. I am also looking for some intuition behind the answer. Lastly, I am looking for an answer using functional programming from the purrr package.

```<code>#Here is the output without using purrr

my.list = list(first = c("AAPL", "MSFT"),
               second = c("AMZN", "NFLX"))

paste(my.list[["first"]][1], ".O")
paste(my.list[["first"]][2], ".O")
paste(my.list[["second"]][1], ".P")
paste(my.list[["second"]][2], ".P")
</code>```

Desired Output would be a list that would like so.

```<code>$first
"AAPL.O" "MSFT.O"

$second
"AMZN.P" "NFLX.P"
</code>```

The first vector in my list receives ".O" at the end of each word in the vector.
The second vector in my list receives ".P" at the end of each word.

Thank you.

答:
You can iterate over 2 list/vector of the same size using purrr::map2. paste0 works like paste but concatenates without spaces. paste/paste0 is vectorized so something like test <- letters[1:5]; paste0(test, "test") works.

```<code>suffix <- c(".O", ".P")
purrr::map2(my.list, suffix, ~paste0(.x, .y))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list I want to iterate over and add characters to the end of each word. However, depending on the element in the list I would like to change the word being added. I am also looking for some intuition behind the answer. Lastly, I am looking for an answer using functional programming from the purrr package.

#Here is the output without using purrr

my.list = list(first = c("AAPL", "MSFT"),
               second = c("AMZN", "NFLX"))

paste(my.list[["first"]][1], ".O")
paste(my.list[["first"]][2], ".O")
paste(my.list[["second"]][1], ".P")
paste(my.list[["second"]][2], ".P")

Desired Output would be a list that would like so.

$first
"AAPL.O" "MSFT.O"

$second
"AMZN.P" "NFLX.P"

The first vector in my list receives ".O" at the end of each word in the vector.
The second vector in my list receives ".P" at the end of each word.

Thank you.

Body:
You can iterate over 2 list/vector of the same size using purrr::map2. paste0 works like paste but concatenates without spaces. paste/paste0 is vectorized so something like test <- letters[1:5]; paste0(test, "test") works.

suffix <- c(".O", ".P")
purrr::map2(my.list, suffix, ~paste0(.x, .y))


问:
How do I support Internet Explorer in an Angular 8 application?
When I generate a project with Angular CLI (8.0.0), I run ng serve, open the application up in Internet Explorer and I am presented with a blank screen.

I had a look at the polyfills.ts files and I uncommented the following lines:

```<code>    import 'classlist.js';
    import 'web-animations-js';
</code>```

I've also removed all core.js imports as Angular 8 supports core.js 3.0 directly.

I've also ran npm i.

package.json:

```<code>"dependencies": {
    "@angular/animations": "~8.0.0",
    "@angular/common": "~8.0.0",
    "@angular/compiler": "~8.0.0",
    "@angular/core": "~8.0.0",
    "@angular/forms": "~8.0.0",
    "@angular/platform-browser": "~8.0.0",
    "@angular/platform-browser-dynamic": "~8.0.0",
    "@angular/router": "~8.0.0",
    "classlist.js": "^1.1.20150312",
    "rxjs": "~6.4.0",
    "tslib": "^1.9.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0",
    "@angular/cli": "~8.0.0",
    "@angular/compiler-cli": "~8.0.0",
    "@angular/language-service": "~8.0.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.4.3"
  }
</code>```

tsconfig.json:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
</code>```

EDIT:

browserlists:

```<code># This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries

# You can see what browsers were selected by your queries by running:
#   npx browserslist

> 0.5%
last 2 versions
Firefox ESR
not dead
IE 9-11 # For IE 9-11 support, remove 'not'.
</code>```

EDIT 2:

The console in Internet Explorer (11) shows the following errors:

polyfills.js:
Syntax error (3168, 5)
(line 3168 beginning) -> class Zone {

vendor.js:
Syntax error (156, 1)
(line 156 beginning) -> class PlatformLocation {

main.ts:
Syntax error (95, 20)
(points to the AppComponent)

What else do I need to do?

答:
This really bothered me so I wrote a nodeJs script that will enable the "workaround" defined here: ng github

Being an enterprise dev that turns out tons of angular apps its not ok to do development locally against chrome and firefox only.  Anyone that's done web dev for more than a minute knows that just because it looks cool in chrome doesn't mean IE will be happy.  OK rant over just install the script and serve it in IE every now and then and check your app in IE locally before pushing  to dev.

Body:
When I generate a project with Angular CLI (8.0.0), I run ng serve, open the application up in Internet Explorer and I am presented with a blank screen.

I had a look at the polyfills.ts files and I uncommented the following lines:

    import 'classlist.js';
    import 'web-animations-js';

I've also removed all core.js imports as Angular 8 supports core.js 3.0 directly.

I've also ran npm i.

package.json:

"dependencies": {
    "@angular/animations": "~8.0.0",
    "@angular/common": "~8.0.0",
    "@angular/compiler": "~8.0.0",
    "@angular/core": "~8.0.0",
    "@angular/forms": "~8.0.0",
    "@angular/platform-browser": "~8.0.0",
    "@angular/platform-browser-dynamic": "~8.0.0",
    "@angular/router": "~8.0.0",
    "classlist.js": "^1.1.20150312",
    "rxjs": "~6.4.0",
    "tslib": "^1.9.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0",
    "@angular/cli": "~8.0.0",
    "@angular/compiler-cli": "~8.0.0",
    "@angular/language-service": "~8.0.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.4.3"
  }

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

EDIT:

browserlists:

# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries

# You can see what browsers were selected by your queries by running:
#   npx browserslist

> 0.5%
last 2 versions
Firefox ESR
not dead
IE 9-11 # For IE 9-11 support, remove 'not'.

EDIT 2:

The console in Internet Explorer (11) shows the following errors:

polyfills.js:
Syntax error (3168, 5)
(line 3168 beginning) -> class Zone {

vendor.js:
Syntax error (156, 1)
(line 156 beginning) -> class PlatformLocation {

main.ts:
Syntax error (95, 20)
(points to the AppComponent)

What else do I need to do?


问:
Sharepoint ItemStyle.xsl for CQWP using images from a content type
I'm building a custom Content Query Web Part to display rollup information from an employee content type.  This content type has a Publishing Image site column called EmpPhoto.  My CQWP is working great and all the site columns I need are available.

I am now creating a custom xsl template to render the information correctly but am stuck using the EmpPhoto image.

If I use the code:

```<code><xsl:value-of select="@EmpPhoto" disable-output-escaping="yes" />
</code>```

... I get a correctly rendered image which is great.  However I want to build an onmouseover event for this image and this approach will not work.

I thought to create an xsl variable to grab the actual image URL then build my own html img and write the onmouseover into that e.g.

```<code><xsl:variable name="EmpPhotoUrl">
    <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
        <xsl:with-param name="UrlColumnName" select="@EmpPhoto"/>
    </xsl:call-template>
</xsl:variable>
</code>```

...

```<code><img src="{$EmpPhotoUrl}" onmouseover="" alt="test" />
</code>```

This doesn't get the URL from the EmpPhoto site column however.  I am new to xsl so I might well be missing an obvious solution!

Any help much appreciated,

Jonny

答:
This is cheating... and it's making assumptions about the src attribute.  But here it is!</p>

```<code><xsl:variable name="EmpPhotoUrl" select="substring-before(substring-after(@EmpPhoto, 'src="'), '"')" />
</code>```

OwnerDisplayName: Jonny

ContentLicense: CC BY-SA 2.5

Body:
I'm building a custom Content Query Web Part to display rollup information from an employee content type.  This content type has a Publishing Image site column called EmpPhoto.  My CQWP is working great and all the site columns I need are available.

I am now creating a custom xsl template to render the information correctly but am stuck using the EmpPhoto image.

If I use the code:

<xsl:value-of select="@EmpPhoto" disable-output-escaping="yes" />

... I get a correctly rendered image which is great.  However I want to build an onmouseover event for this image and this approach will not work.

I thought to create an xsl variable to grab the actual image URL then build my own html img and write the onmouseover into that e.g.

<xsl:variable name="EmpPhotoUrl">
    <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
        <xsl:with-param name="UrlColumnName" select="@EmpPhoto"/>
    </xsl:call-template>
</xsl:variable>

...

This doesn't get the URL from the EmpPhoto site column however.  I am new to xsl so I might well be missing an obvious solution!

Any help much appreciated,

Jonny

Body:
This is cheating... and it's making assumptions about the src attribute.  But here it is!

<xsl:variable name="EmpPhotoUrl" select="substring-before(substring-after(@EmpPhoto, 'src=&quot;'), '&quot;')" />

OwnerDisplayName: John Liu


问:
How to stub any instances for a given class using Rspec Mocks
The following code raises an error: undefined method 'any_instance' for String:Class

```<code>require 'rspec'

RSpec.configure do |config|
  config.mock_with :rspec
end

describe String do
  it 'stubs' do
    String.any_instance.stub(:foo).and_return(1)
    ''.foo.should eq(1)
  end
end
</code>```

How can I include the Mocks module into the Class or Object class?

答:
With RSpec Mocks in versions previous to 2.6.0, you cannot do it. However you can use any_instance with Mocha(as seen here) or in later versions of Rspec.

In your spec/spec_helper.rb

Make sure you have this line:

config.mock_with :mocha

uncommented.

ContentLicense: CC BY-SA 3.0

Body:
The following code raises an error: undefined method 'any_instance' for String:Class

require 'rspec'

RSpec.configure do |config|
  config.mock_with :rspec
end

describe String do
  it 'stubs' do
    String.any_instance.stub(:foo).and_return(1)
    ''.foo.should eq(1)
  end
end

How can I include the Mocks module into the Class or Object class?


问:
Python test class stuck on 'Instantiating tests'
My test class produces the required plot, but I have to manually stop execution every time - the console continues to show 'Instantiating tests'; can anyone spot why the execution never halts? Any tips on increasing my code's 'Pythonic-ness' would also be appreciated!

(Python 3.5 running in PyCharm CE 2016.2.1 on Mac OS X 10.11.6)

```<code># A program to test various sorting algorithms. It generates random lists of various sizes,
# sorts them, and then tests that:
#   a. the list is in ascending order
#   b. the set of elements is the same as the original list
#   c. record the time taken

import random
import timeit
from unittest import TestCase

import matplotlib.pyplot as plt

from Sorter import insertionsort, mergesort, quicksort

class TestSort(TestCase):
    def test_sorting(self):

        times_insertionsort = []   # holds the running times for insertion sort
        times_quicksort = []       # holds the running times for quick sort
        times_mergesort = []       # holds the running times for merge sort
        lengths = []               # holds the array lengths

        # determine the number of lists to be created
        for i in range(0, 13):

            # initialise a new empty list
            pre_sort = []

            # determine the list's length, then populate the list with 'random' data
            for j in range(0, i * 100):
                pre_sort.append(random.randint(0, 1000))

            # record the length of the list
            lengths.append(len(pre_sort))

            # record the time taken by quicksort to sort the list
            start_time = timeit.default_timer()
            post_quicksort = quicksort(pre_sort)
            finish_time = timeit.default_timer()
            times_quicksort.append((finish_time - start_time) * 1000)

            # record the time taken by insertionsort to sort the list
            start_time = timeit.default_timer()
            post_insertionsort = insertionsort(pre_sort)
            finish_time = timeit.default_timer()
            times_insertionsort.append((finish_time - start_time) * 1000)

            # record the time taken by mergesort to sort the list
            start_time = timeit.default_timer()
            post_mergesort = mergesort(pre_sort)
            finish_time = timeit.default_timer()
            times_mergesort.append((finish_time - start_time) * 1000)

            # check that:
            #   a. the list is in ascending order
            #   b. the set of elements is the same as the original list
            for k in range(0, len(pre_sort) - 1):
                self.assertTrue(post_insertionsort[k] in pre_sort)
                self.assertTrue(post_insertionsort[k] <= post_insertionsort[k + 1])
                self.assertTrue(post_mergesort[k] == post_insertionsort[k])
                self.assertTrue(post_mergesort[k] == post_quicksort[k])

        # plot the results
        plt.plot(lengths, times_insertionsort, 'r')
        plt.plot(lengths, times_quicksort, 'g')
        plt.plot(lengths, times_mergesort, 'b')
        plt.xlabel('List size')
        plt.ylabel('Execution time (ms)')
        plt.show()
</code>```

答: I had the same error in Django. I found one of the migrations weren't applied.</p>

Body:
My test class produces the required plot, but I have to manually stop execution every time - the console continues to show 'Instantiating tests'; can anyone spot why the execution never halts? Any tips on increasing my code's 'Pythonic-ness' would also be appreciated!

(Python 3.5 running in PyCharm CE 2016.2.1 on Mac OS X 10.11.6)

# A program to test various sorting algorithms. It generates random lists of various sizes,
# sorts them, and then tests that:
#   a. the list is in ascending order
#   b. the set of elements is the same as the original list
#   c. record the time taken

import random
import timeit
from unittest import TestCase

import matplotlib.pyplot as plt

from Sorter import insertionsort, mergesort, quicksort

class TestSort(TestCase):
    def test_sorting(self):

        times_insertionsort = []   # holds the running times for insertion sort
        times_quicksort = []       # holds the running times for quick sort
        times_mergesort = []       # holds the running times for merge sort
        lengths = []               # holds the array lengths

        # determine the number of lists to be created
        for i in range(0, 13):

            # initialise a new empty list
            pre_sort = []

            # determine the list's length, then populate the list with 'random' data
            for j in range(0, i * 100):
                pre_sort.append(random.randint(0, 1000))

            # record the length of the list
            lengths.append(len(pre_sort))

            # record the time taken by quicksort to sort the list
            start_time = timeit.default_timer()
            post_quicksort = quicksort(pre_sort)
            finish_time = timeit.default_timer()
            times_quicksort.append((finish_time - start_time) * 1000)

            # record the time taken by insertionsort to sort the list
            start_time = timeit.default_timer()
            post_insertionsort = insertionsort(pre_sort)
            finish_time = timeit.default_timer()
            times_insertionsort.append((finish_time - start_time) * 1000)

            # record the time taken by mergesort to sort the list
            start_time = timeit.default_timer()
            post_mergesort = mergesort(pre_sort)
            finish_time = timeit.default_timer()
            times_mergesort.append((finish_time - start_time) * 1000)

            # check that:
            #   a. the list is in ascending order
            #   b. the set of elements is the same as the original list
            for k in range(0, len(pre_sort) - 1):
                self.assertTrue(post_insertionsort[k] in pre_sort)
                self.assertTrue(post_insertionsort[k] <= post_insertionsort[k + 1])
                self.assertTrue(post_mergesort[k] == post_insertionsort[k])
                self.assertTrue(post_mergesort[k] == post_quicksort[k])

        # plot the results
        plt.plot(lengths, times_insertionsort, 'r')
        plt.plot(lengths, times_quicksort, 'g')
        plt.plot(lengths, times_mergesort, 'b')
        plt.xlabel('List size')
        plt.ylabel('Execution time (ms)')
        plt.show()


问:
Trigger function that Updates some columns after update of a specific column
I have the table Ticketsforsale:

```<code>Ticketsforsale(ticket_id, starting_date, price)
</code>```

I need to create a trigger function which , in case of update on "starting_date" , will replace the old "starting_date" with the updated one in addition to lowering the "price" by 20% .

The trigger function I've came up with so far is the following :

```<code> create or replace function automatic_update()
RETURNS TRIGGER AS $$
begin
IF new.starting_date != ticketsforsale.starting_date
THEN old.starting_date = new.starting_date ,
     ticketsforsale.price = ticketsforsale.price * (20/100) ;
END IF ;
RETURN NEW ;
END ;
$$
LANGUAGE plpgsql ;

CREATE TRIGGER automation
BEFORE INSERT OR UPDATE ON public.ticketsforsale
FOR EACH ROW EXECUTE PROCEDURE automatic_update()
</code>```

The trigger function code is running properly without any errors.

But when I update the value of a "starting_date" column and try to save the change , I get the following error :

Missing FROM-clause entry on table 'ticketsforsale' LINE 1 :SELECT
  new.starting_date != ticketsforsale.starting_date * QUERY: SELECT
  new.starting_date != ticketsforsale.starting_date CONTEXT: PL/pgsql
  function automatic_update() line 3 at IF

I've tinkered with the function pretty much . However I didn't seem to get it right , thanks .

答:
You can use the old pseudo record to access the values before the update. It doesn't make sense to set old values though. And such a trigger makes no sense for INSERT as there is no old value that can change here. And you're not lowering the price by 20% you set it to 20%.

Something like the following should work as you want.

```<code>CREATE OR REPLACE FUNCTION automatic_update()
                           RETURNS TRIGGER
AS
$$
BEGIN
  IF new.starting_date <> old.starting_date THEN
    new.price := old.price * .8;
  END IF;

  RETURN new;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER automation
               BEFORE UPDATE
               ON public.ticketsforsale
               FOR EACH ROW
               EXECUTE PROCEDURE automatic_update();
</code>```

You could also move the condition to the triggers WHEN.

```<code>CREATE OR REPLACE FUNCTION automatic_update()
                           RETURNS TRIGGER
AS
$$
BEGIN
  new.price := old.price * .8;

  RETURN new;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER automation
               BEFORE UPDATE
               ON public.ticketsforsale
               FOR EACH ROW
               WHEN (new.starting_date <> old.starting_date)
               EXECUTE PROCEDURE automatic_update();
</code>```

Body:
I have the table Ticketsforsale:

Ticketsforsale(ticket_id, starting_date, price)

I need to create a trigger function which , in case of update on "starting_date" , will replace the old "starting_date" with the updated one in addition to lowering the "price" by 20% .

The trigger function I've came up with so far is the following :

 create or replace function automatic_update()
RETURNS TRIGGER AS $$
begin
IF new.starting_date != ticketsforsale.starting_date
THEN old.starting_date = new.starting_date ,
     ticketsforsale.price = ticketsforsale.price * (20/100) ;
END IF ;
RETURN NEW ;
END ;
$$
LANGUAGE plpgsql ;

CREATE TRIGGER automation
BEFORE INSERT OR UPDATE ON public.ticketsforsale
FOR EACH ROW EXECUTE PROCEDURE automatic_update()

The trigger function code is running properly without any errors.

But when I update the value of a "starting_date" column and try to save the change , I get the following error :

Missing FROM-clause entry on table 'ticketsforsale' LINE 1 :SELECT
  new.starting_date != ticketsforsale.starting_date * QUERY: SELECT
  new.starting_date != ticketsforsale.starting_date CONTEXT: PL/pgsql
  function automatic_update() line 3 at IF

I've tinkered with the function pretty much . However I didn't seem to get it right , thanks .

Body:
You can use the old pseudo record to access the values before the update. It doesn't make sense to set old values though. And such a trigger makes no sense for INSERT as there is no old value that can change here. And you're not lowering the price by 20% you set it to 20%.

Something like the following should work as you want.

CREATE OR REPLACE FUNCTION automatic_update()
                           RETURNS TRIGGER
AS
$$
BEGIN
  IF new.starting_date <> old.starting_date THEN
    new.price := old.price * .8;
  END IF;

  RETURN new;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER automation
               BEFORE UPDATE
               ON public.ticketsforsale
               FOR EACH ROW
               EXECUTE PROCEDURE automatic_update();

You could also move the condition to the triggers WHEN.

CREATE OR REPLACE FUNCTION automatic_update()
                           RETURNS TRIGGER
AS
$$
BEGIN
  new.price := old.price * .8;

  RETURN new;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER automation
               BEFORE UPDATE
               ON public.ticketsforsale
               FOR EACH ROW
               WHEN (new.starting_date <> old.starting_date)
               EXECUTE PROCEDURE automatic_update();


问:
I need help converting awk to stand alone bash script
Need help converting the following to stand alone code.

```<code>awk '{ for (i=1; i<=NF; i++) {a[NR,i] = $i} }
    NF>p { p = NF }
    END {
        for(j=1; j<=p; j++) {
            str=a[1,j]
            for(i=2; i<=NR; i++)
        {str=str"   "a[i,j];}
        printf str"\n"}
    }' $temp_input
</code>```

Clarification: I meant stand alone bash script not utilizing AWK. I wrote this utilizing AWK but cant figure out how to structure this without AWK. I played around with this to get it to work, it does but can never replicate this in Bash script. that is why i said stand alone code.

the end format of the returned data never matches when AWK is translated into Bash. it appears to be the same however during testing they are different when writen in Bash not using AWK.

答:
I'm not entirely sure I understand the question correctly. If you want a script that executes that awk code on whatever file is supplied as a parameter, you don't need bash at all; you can just make an awk script:

```<code>#!/usr/bin/awk -f
{ for (i=1; i<=NF; i++) {a[NR,i] = $i} }
NF>p { p = NF }
END {
    for(j=1; j<=p; j++) {
        str=a[1,j]
        for(i=2; i<=NR; i++)
    {str=str"   "a[i,j];}
    printf str"\n"}
}
</code>```

If you want a bash wrapper around it, you could do something like this:

```<code>#!/bin/bash
awk '{ for (i=1; i<=NF; i++) {a[NR,i] = $i} }
    NF>p { p = NF }
    END {
        for(j=1; j<=p; j++) {
            str=a[1,j]
            for(i=2; i<=NR; i++)
        {str=str"   "a[i,j];}
        printf str"\n"}
    }' "$@"
</code>```

(Note that "$@" is the standard way to pass on parameter(s) passed to the script.)

In either case, you should add execute permission to the script (e.g. if you named the script rotatefields, you'd use chmod +x rotatefields). Then either place it in one of the directories in your $PATH and just run it by name (e.g. rotatefields filetorotate), or run it from the same directory it's in with ./rotatefields filetorotate, or if it's in some other directory specify the full path (/path/to/rotatefields filetorotate).

(Note: Do not run them with sh rotatefields -- that overrides the shebang line and runs it with plain sh, which can cause trouble.)

Body:
Need help converting the following to stand alone code.

awk '{ for (i=1; i<=NF; i++) {a[NR,i] = $i} }
    NF>p { p = NF }
    END {
        for(j=1; j<=p; j++) {
            str=a[1,j]
            for(i=2; i<=NR; i++)
        {str=str"   "a[i,j];}
        printf str"\n"}
    }' $temp_input

Clarification: I meant stand alone bash script not utilizing AWK. I wrote this utilizing AWK but cant figure out how to structure this without AWK. I played around with this to get it to work, it does but can never replicate this in Bash script. that is why i said stand alone code.

the end format of the returned data never matches when AWK is translated into Bash. it appears to be the same however during testing they are different when writen in Bash not using AWK.

Body:
I'm not entirely sure I understand the question correctly. If you want a script that executes that awk code on whatever file is supplied as a parameter, you don't need bash at all; you can just make an awk script:

#!/usr/bin/awk -f
{ for (i=1; i<=NF; i++) {a[NR,i] = $i} }
NF>p { p = NF }
END {
    for(j=1; j<=p; j++) {
        str=a[1,j]
        for(i=2; i<=NR; i++)
    {str=str"   "a[i,j];}
    printf str"\n"}
}

If you want a bash wrapper around it, you could do something like this:

#!/bin/bash
awk '{ for (i=1; i<=NF; i++) {a[NR,i] = $i} }
    NF>p { p = NF }
    END {
        for(j=1; j<=p; j++) {
            str=a[1,j]
            for(i=2; i<=NR; i++)
        {str=str"   "a[i,j];}
        printf str"\n"}
    }' "$@"

(Note that "$@" is the standard way to pass on parameter(s) passed to the script.)

In either case, you should add execute permission to the script (e.g. if you named the script rotatefields, you'd use chmod +x rotatefields). Then either place it in one of the directories in your $PATH and just run it by name (e.g. rotatefields filetorotate), or run it from the same directory it's in with ./rotatefields filetorotate, or if it's in some other directory specify the full path (/path/to/rotatefields filetorotate).

(Note: Do not run them with sh rotatefields -- that overrides the shebang line and runs it with plain sh, which can cause trouble.)


问:
What is Firebase Remote Config Developer Mode
I am adding Firebase Remote Config to an app and I am confused about the purpose of .setMinimumFetchIntervalInSeconds(...) &  .setDeveloperModeEnabled(true/false) . The docs talk about a developer mode, but I'm not sure they clearly explain what it actually does. Does it have to be used in tandem with setMinimumFetchIntervalInSeconds or can it be used on its own , and if on its own, what does it then do?

Secondly I'm testing my test boolean value in a debug build of the app, with values set to 5 minutes or hours but still I always  get my value within 3 seconds. when I set setDeveloperModeEnabled to false or not add the FirebaseRemoteConfigSettings to my instance at all, I still have not observed the famed throttle exception and I get my values immediately. It basically looks like my cache settings are being ignored and I always get fresh data from the backend and I can set the cache as low as I want.

答:
setDeveloperModeEnabled() is deprecated. They use setMinimumFetchIntervalInSeconds() instead now to set the cache expiration delay.

Check your gradle for this line and make sure it's version 19.1.4 (as of today) or newer:
implementation 'com.google.firebase:firebase-config:19.1.4'

Firebase has a quota for the number of fetch requests you can make. Developer mode is a way to greenlight your own device to be able to fetch at any time without restriction but you can't release your app with developer mode enabled (in which you still have to specify the interval)

if you are on v17.0.0, use this code by changing the cacheExpiration value to your desired one.

```<code>long cacheExpiration = 3600;
    mFirebaseRemoteConfig.setConfigSettingsAsync(new FirebaseRemoteConfigSettings.Builder()
       .setMinimumFetchIntervalInSeconds(cacheExpiration)
       .build());

//** deprecated */
//mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);

mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);

mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
    @Override
    public void onComplete(@NonNull Task<Boolean> task) {
        if (task.isSuccessful()) {
            boolean updated = task.getResult();
            Log.d(TAG, "Config params updated: " + updated);
            Toast.makeText(MainActivity.this, "Fetch and activate succeeded " + updated,
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Fetch failed",
                    Toast.LENGTH_SHORT).show();
        }
        updateConfig();
    }
});
</code>```

setDeveloperModeEnabled is not supported anymore, which is probably why you didn't observe any change in its behaviour

Body:
setDeveloperModeEnabled() is deprecated. They use setMinimumFetchIntervalInSeconds() instead now to set the cache expiration delay.

Check your gradle for this line and make sure it's version 19.1.4 (as of today) or newer:
implementation 'com.google.firebase:firebase-config:19.1.4'

Firebase has a quota for the number of fetch requests you can make. Developer mode is a way to greenlight your own device to be able to fetch at any time without restriction but you can't release your app with developer mode enabled (in which you still have to specify the interval)

if you are on v17.0.0, use this code by changing the cacheExpiration value to your desired one.

long cacheExpiration = 3600;
    mFirebaseRemoteConfig.setConfigSettingsAsync(new FirebaseRemoteConfigSettings.Builder()
       .setMinimumFetchIntervalInSeconds(cacheExpiration)
       .build());

//** deprecated */
//mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);

mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);

mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
    @Override
    public void onComplete(@NonNull Task<Boolean> task) {
        if (task.isSuccessful()) {
            boolean updated = task.getResult();
            Log.d(TAG, "Config params updated: " + updated);
            Toast.makeText(MainActivity.this, "Fetch and activate succeeded " + updated,
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Fetch failed",
                    Toast.LENGTH_SHORT).show();
        }
        updateConfig();
    }
});

setDeveloperModeEnabled is not supported anymore, which is probably why you didn't observe any change in its behaviour


问:
Spring-Data-Rest exposing RepositoryRestResource fails randomly when two Repository-Interfaces exist for the same domain-type
Hello stack overflow

I am creating a demo application for myself using spring-data-jpa and spring-data-rest. I have two repository interfaces:

```<code>interface PersonRepository : PagingAndSortingRepository<Person, Long>

@RepositoryRestResource(path = "people", collectionResourceRel = "people", exported = true)
interface PeopleRepository : PagingAndSortingRepository<Person, Long>
</code>```

I changed the repositoryDetectionStrategy to RepositoryDetectionStrategies.ANNOTATED.

I created for the personRepository a self-made RestController for the peopleRepository I want it to be created by spring and exposed at localhost:8080/   by hateos

Problem

Just randomly the peopleRepository is exposed(not working at all).

After debugging I can say for sure that RepositoryRestMvcConfiguration's Bean Repositories is the reason for the problem.

org.springframework.data.repository.support.Repositories's method populateRepositoryFactoryInformation gets over all Repositories since I have two for the same Class the inner map.put overrides my desired behavior depending which bean comes first.

So is this a bug or spring does not support several Repository-Interfaces with spring-data-rest or did I misconfigure my setup?

答:
Sadly, it seems that SpringData does not handle well this kind of scenario (I was using spring-boot 1.5.8, when I found the same problem as you... I tried to upgrade my spring version to see if this was fixed, but I begin to get other compilation/deployments issues. so I quit that idea...)

You can get more info in these links:

One entity Two Repositories

DataRest Issue/Improvement Ticket

Body:
Hello stack overflow

I am creating a demo application for myself using spring-data-jpa and spring-data-rest. I have two repository interfaces:

interface PersonRepository : PagingAndSortingRepository<Person, Long>

@RepositoryRestResource(path = "people", collectionResourceRel = "people", exported = true)
interface PeopleRepository : PagingAndSortingRepository<Person, Long>

I changed the repositoryDetectionStrategy to RepositoryDetectionStrategies.ANNOTATED.

I created for the personRepository a self-made RestController for the peopleRepository I want it to be created by spring and exposed at localhost:8080/   by hateos

Problem

Just randomly the peopleRepository is exposed(not working at all).

After debugging I can say for sure that RepositoryRestMvcConfiguration's Bean Repositories is the reason for the problem.

org.springframework.data.repository.support.Repositories's method populateRepositoryFactoryInformation gets over all Repositories since I have two for the same Class the inner map.put overrides my desired behavior depending which bean comes first.

So is this a bug or spring does not support several Repository-Interfaces with spring-data-rest or did I misconfigure my setup?


问:
Signal on X11 Logout
I am writing an application that will occasionally save data. The Problem is now, when a user logs out of X11 and my application did not yet save the changes, is there a way to detect the logout and write the changes to disk? I tried inmplementing a signal handler for SIGHUP and SIGQUIT without success. Is there a signal that gets emitted or is there a way to lsiten for a logout?

答:
Basile's recommendation of looking at your toolkit's relevant classes (QSessionManager and GtkApplication) is good. I'm thankful he posted that because it helped me find the specific stuff I was looking for.

But if it's as you say, and your toolkit doesn't have built-in session management support, the relevant specification is not EWMH, but rather XSMP. There's a small amount of additional information included in ICCCM that you should also watch out for.

This is far from being a couple years of work. The relevant client-side portions of the session manager protocol should only take a few hours, maybe a couple days if you're unfamiliar with integrating low-level X11 protocols into an existing application stack.

Title: Signal on X11 Logout


问:
how do I create a line of arbitrary thickness using Bresenham?
I am currently using Bresenham's algorithm to draw lines but they are (of course) one pixel in thickness. My question is what is the most efficient way to draw lines of arbitrary thickness?

The language I am using is C.

答:
For those who want a Python version here goes the code (based on the answer of @Fabel):

def drawline(x1,y1,x2,y2,**kwargs):
    if kwargs.get('thickness')==None:
        thickness=1
    else:
        thickness=kwargs['thickness']
    if kwargs.get('roundcap')==None:
        roundcap=False
    else:
        roundcap=True
    angle = np.arctan2(y2-y1,x2-x1)
    xx = np.zeros(4)
    yy = np.zeros(4)
    xx[0] = np.round(x1 + thickness*np.cos(angle+np.pi/2))
    yy[0] = np.round(y1 + thickness*np.sin(angle+np.pi/2))
    xx[1] = np.round(x1 + thickness*np.cos(angle-np.pi/2))
    yy[1] = np.round(y1 + thickness*np.sin(angle-np.pi/2))
    xx[2] = np.round(x2 + thickness*np.cos(angle-np.pi/2))
    yy[2] = np.round(y2 + thickness*np.sin(angle-np.pi/2))
    xx[3] = np.round(x2 + thickness*np.cos(angle+np.pi/2))
    yy[3] = np.round(y2 + thickness*np.sin(angle+np.pi/2))
    u,v=polygon(xx,yy)
    if roundcap:
        temp1x, temp1y = circle(x1,y1,thickness)
        temp2x, temp2y = circle(x1,y1,thickness)
        u = np.append(u,temp1x,temp2x)
        v = np.append(v,temp1y,temp2y)
    return u,v
```
<p>When calling the function you can optionally specify thickness and roundcap. For example:</p>
<pre class="lang-Python prettyprint-override"><code>drawline(10,10,50,50,thickness=3,roundcap=False)
</code>```

Body:
For those who want a Python version here goes the code (based on the answer of @Fabel):

def drawline(x1,y1,x2,y2,**kwargs):
    if kwargs.get('thickness')==None:
        thickness=1
    else:
        thickness=kwargs['thickness']
    if kwargs.get('roundcap')==None:
        roundcap=False
    else:
        roundcap=True
    angle = np.arctan2(y2-y1,x2-x1)
    xx = np.zeros(4)
    yy = np.zeros(4)
    xx[0] = np.round(x1 + thickness*np.cos(angle+np.pi/2))
    yy[0] = np.round(y1 + thickness*np.sin(angle+np.pi/2))
    xx[1] = np.round(x1 + thickness*np.cos(angle-np.pi/2))
    yy[1] = np.round(y1 + thickness*np.sin(angle-np.pi/2))
    xx[2] = np.round(x2 + thickness*np.cos(angle-np.pi/2))
    yy[2] = np.round(y2 + thickness*np.sin(angle-np.pi/2))
    xx[3] = np.round(x2 + thickness*np.cos(angle+np.pi/2))
    yy[3] = np.round(y2 + thickness*np.sin(angle+np.pi/2))
    u,v=polygon(xx,yy)
    if roundcap:
        temp1x, temp1y = circle(x1,y1,thickness)
        temp2x, temp2y = circle(x1,y1,thickness)
        u = np.append(u,temp1x,temp2x)
        v = np.append(v,temp1y,temp2y)
    return u,v

When calling the function you can optionally specify thickness and roundcap. For example:

drawline(10,10,50,50,thickness=3,roundcap=False)


问:
Run a batch file on EC2 from a (python) lambda
I can see a generic way of starting an EC2 from lambda in Start and Stop Instances at Scheduled Intervals Using Lambda and CloudWatch.

Suppose I use that method to start an EC2, and suppose the AMI is a windows server 2019 customised to have a .bat file on the desktop, and also suppose I'm using a python lambda.

How can I execute this batch file from the lambda? (i.e. just as though someone had RDP'd into the instance and double-clicked on it)

Note: To be very clear, basically I want to start the EC2 using the method given in the AWS docs (above), and right after the instance has started, to run the batch file that will be sitting on the instance's desktop

答:
I think you have a few concepts mixed together.

AWS Lambda functions run on the Lambda service, without having to use Amazon EC2 instances. This is what makes them "serverless".

If you have a batch file on an Amazon EC2 instance, you would presumably want to run that batch file on the EC2 instance itself, without involving Lambda (since you have got a server).

If you wish to run a script on an EC2 instance when it launches for the first time, you can provide a PowerShell or Command-Line script via the User Data field. Software on the AMI will automatically execute this script the first time that the instance starts.

This script could do all the work itself, or it could simply call another script that is stored on the disk. Some people use the script to download another script from a repository (eg Amazon S3 or GitHub) and then execute the downloaded script.

For more information, see: Running Commands on Your Windows Instance at Launch - Amazon Elastic Compute Cloud

If the Amazon EC2 instance is already running and you wish to trigger a script to execute, you can use the AWS Systems Manager Run Command. This works by having an agent on the instance which can be remotely triggered, thereby running scripts without having to login to the instance.


问:
Show an element... unless the user has javascript turned on, then fade it in nice and pretty?
I have an element which shows important text to the user, as such I'd like to animate it in to the pane (motion draws the eye) rather than just have it somewhere where the user may miss it.

How can I have it showing by default (for the 1% or so of users who surf with javascript off), but animated in for the rest?

Using

```<code>    $(document).ready(function(){
        $('#messagecenter').hide();
        $('#messagecenter').show('fade', 'slow');
    })
</code>```

Causes the element to load visible, then disapear, then fade.

```<code>display:hidden;

    $(document).ready(function(){
        $('#messagecenter').show('fade', 'slow');
    })
</code>```

Will of course hide it for users with no Javascript.

Is there any good way to do this?

答:
Easiest answer: Don't wait for document.ready to show it.  Just put that code at the bottom of your  and it should hardly be noticeable.

Be sure to chain your queries too.

```<code>$('#messagecenter').hide().fadeIn('slow');
</code>```

Body:
I have an element which shows important text to the user, as such I'd like to animate it in to the pane (motion draws the eye) rather than just have it somewhere where the user may miss it.

How can I have it showing by default (for the 1% or so of users who surf with javascript off), but animated in for the rest?

Using

    $(document).ready(function(){
        $('#messagecenter').hide();
        $('#messagecenter').show('fade', 'slow');
    })

Causes the element to load visible, then disapear, then fade.

display:hidden;

    $(document).ready(function(){
        $('#messagecenter').show('fade', 'slow');
    })

Will of course hide it for users with no Javascript.

Is there any good way to do this?

Body:
Easiest answer: Don't wait for document.ready to show it.  Just put that code at the bottom of your <body> and it should hardly be noticeable.

Be sure to chain your queries too.

$('#messagecenter').hide().fadeIn('slow');


问:
How do I fix a button to bottom screen in NativeScript
I have a multi-page form and I would like the continue button to be fixed in one spot throughout the form.

Below is a pic that shows what I am trying to do.

On the pages that are short, I still want the button on bottom. Same with long pages, still want it there.

Can anyone help me with a prototype?

Thank you.

John

答:
You could use flexbox to do that.

main {
  height: 400px;
  background-color: limegreen;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.actions {
  background-color: yellow;
  padding: 10px;
  margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class="content">
    <h1>Hello</h1>

    <p>Here some content</p>
  </div>
  <div class="actions">
    <button>Submit</button>
  </div>
</main></code>```

Body:
You could use flexbox to do that.

main {
  height: 400px;
  background-color: limegreen;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.actions {
  background-color: yellow;
  padding: 10px;
  margin: 5px;
}

<main>
  <div class="content">
    <h1>Hello</h1>

    <p>Here some content</p>
  </div>
  <div class="actions">
    <button>Submit</button>
  </div>
</main>


问:
Issue with money counting script
I've got an issue with my money counting script.
It works fine but I need to format output in two ways but I cannot use any string functions including format but I suppose to use math lib floor ceil function.

```<code>import math

coins1 = int(input("Quantity of 1 cent coins ? ")) * 0.01

coins2 = int(input("Quantity of 2 cent coins ? ")) * 0.02

coins3 = int(input("Quantity of 5 cent coins ? ")) * 0.05

coins4 = int(input("Quantity of 10 cent coins ? ")) * 0.10

coins5 = int(input("Quantity of 20 cent coins ? ")) * 0.20

coins6 = int(input("Quantity of 50 cent coins ? ")) * 0.50

coins7 = int(input("Quantity of 1 euro coins ? ")) * 1

coins8 = int(input("Quantity of 2 euro coins ? ")) * 2

bills1 = int(input("Quantity of 5 euro bills ? ")) * 5

bills2 = int(input("Quantity of 10 euro bills ? ")) * 10

bills3 = int(input("Quantity of 20 euro bills ? ")) * 20

bills4 = int(input("Quantity of 50 euro bills ? ")) * 50

total = coins1 + coins2 + coins3 + coins4 + coins5 + coins6 + coins7 + coins8 + coins1 + bills2 + bills3 + bills4

print("You've got", total, "euro and",)
</code>```

My current output is:

```<code>You've got 32792039464.8 euro and
</code>```

My goal is:

```<code>You've got 32792039464 euro and 80 cents.
$32.792.39.464,80
</code>```

答:
You first need to multiply total%1 by 100 to get the value of cents in well, cents.

```<code>cents = math.ceil(total%1 * 100) ## for 32792039464.8 cents will be 0.8. times 100 is 80.
total = math.floor(total - cents/100) ## round the number down

print("You've got", total, "euro and ", cents, " cents.")
</code>```

You could also use this:

```<code>cents = round(total%1 * 100) ## for 32792039464.8 cents will be 0.8. times 100 is 80 cents.
total = round(total - cents/100) ## round the total down. 32792039464.8 to 32792039464

print("You've got", total, "euro and ", cents, " cents")
</code>```

Title: Issue with money counting script

Body:
I've got an issue with my money counting script.
It works fine but I need to format output in two ways but I cannot use any string functions including format but I suppose to use math lib floor ceil function.

import math

coins1 = int(input("Quantity of 1 cent coins ? ")) * 0.01

coins2 = int(input("Quantity of 2 cent coins ? ")) * 0.02

coins3 = int(input("Quantity of 5 cent coins ? ")) * 0.05

coins4 = int(input("Quantity of 10 cent coins ? ")) * 0.10

coins5 = int(input("Quantity of 20 cent coins ? ")) * 0.20

coins6 = int(input("Quantity of 50 cent coins ? ")) * 0.50

coins7 = int(input("Quantity of 1 euro coins ? ")) * 1

coins8 = int(input("Quantity of 2 euro coins ? ")) * 2

bills1 = int(input("Quantity of 5 euro bills ? ")) * 5

bills2 = int(input("Quantity of 10 euro bills ? ")) * 10

bills3 = int(input("Quantity of 20 euro bills ? ")) * 20

bills4 = int(input("Quantity of 50 euro bills ? ")) * 50

total = coins1 + coins2 + coins3 + coins4 + coins5 + coins6 + coins7 + coins8 + coins1 + bills2 + bills3 + bills4

print("You've got", total, "euro and",)

My current output is:

You've got 32792039464.8 euro and

My goal is:

You've got 32792039464 euro and 80 cents.
$32.792.39.464,80

Body:
You first need to multiply total%1 by 100 to get the value of cents in well, cents.

cents = math.ceil(total%1 * 100) ## for 32792039464.8 cents will be 0.8. times 100 is 80.
total = math.floor(total - cents/100) ## round the number down

print("You've got", total, "euro and ", cents, " cents.")

You could also use this:

cents = round(total%1 * 100) ## for 32792039464.8 cents will be 0.8. times 100 is 80 cents.
total = round(total - cents/100) ## round the total down. 32792039464.8 to 32792039464

print("You've got", total, "euro and ", cents, " cents")


问:
How do I use setTimeout or setInterval while iterating over an array?
I need to continuously iterate over an array (which actually contains ids used to generate canvax images).

So I need to iterate over the array of keys over and over again, with ids being set with a delay.

```<code>function animateCanvas() {
    keys = getKeys();
    let offset = 0;
    keys.forEach(function(key){
        setTimeout(function(){
            animateFrame(key);
        }, 2000 + offset);
        offset += 2000;
        keys = [];
    });
}

function animateFrame(id) {
    const animationCanvas = document.querySelector(`.canvas-animation`);
    const animationContext = animationCanvas.getContext('2d');
    const canvas1 = document.getElementById(id);
    animationContext.clearRect(0, 0, animationCanvas.width, animationCanvas.height);
    animationContext.drawImage(canvas1, 0,0, 170, 170, 0, 0 , 150, 150);
}
</code>```

Expected result would be endless setting another image to canvas via animateFrame(key) with a delay of 2 seconds

答:
This approach won't work as you want to continuously iterate over images. I would suggest user setInterval for it.

try the below piece of code

```<code>// This is your array of images
var x = [1, 2, 3, 4];

// This is your canvas displaying function
function something(x) {console.log(x)}

setInterval(() => {
  // It checks if we have reached the end
  if(curr == x.length - 1)
    curr = 0;

  something(x[curr]);
  curr++;
}, 2000)
</code>```

Body:
I need to continuously iterate over an array (which actually contains ids used to generate canvax images).

So I need to iterate over the array of keys over and over again, with ids being set with a delay.

function animateCanvas() {
    keys = getKeys();
    let offset = 0;
    keys.forEach(function(key){
        setTimeout(function(){
            animateFrame(key);
        }, 2000 + offset);
        offset += 2000;
        keys = [];
    });
}

function animateFrame(id) {
    const animationCanvas = document.querySelector(`.canvas-animation`);
    const animationContext = animationCanvas.getContext('2d');
    const canvas1 = document.getElementById(id);
    animationContext.clearRect(0, 0, animationCanvas.width, animationCanvas.height);
    animationContext.drawImage(canvas1, 0,0, 170, 170, 0, 0 , 150, 150);
}

Expected result would be endless setting another image to canvas via animateFrame(key) with a delay of 2 seconds

Body:
This approach won't work as you want to continuously iterate over images. I would suggest user setInterval for it.

try the below piece of code

// This is your array of images
var x = [1, 2, 3, 4];

// This is your canvas displaying function
function something(x) {console.log(x)}

setInterval(() => {
  // It checks if we have reached the end
  if(curr == x.length - 1)
    curr = 0;

  something(x[curr]);
  curr++;
}, 2000)


问:
Trying to append a column in numpy array, getting ValueError
I am trying to append column for the following arrays

```<code>train = np.append(train_data, train_labels, axis=1)

(60000, 784)
(60000,)
</code>```

And I get the error

```<code>ValueError: all the input arrays must have same number of dimensions
</code>```

I cannot understand what the issue is...
I need output of

```<code>(60000, 785)
</code>```

答:
I think you should use axis=0.

```<code>>>> np.append((1,2),(2,),axis=0)
array([1, 2, 2])
</code>```

If those tuples that you have posted are array shapes, then you can use

```<code>train = np.append(train_data, train_labels[:,None], axis=1)
</code>```

The arrays must have the same number of dimensions (2 in this case). Using None in indexing for non-existing dimension adds a singleton dimension to a an array.

```<code>>>> train_labels[:,None].shape
(60000, 1)
</code>```

Body:
I am trying to append column for the following arrays

train = np.append(train_data, train_labels, axis=1)

(60000, 784)
(60000,)

And I get the error

ValueError: all the input arrays must have same number of dimensions

I cannot understand what the issue is...
I need output of

(60000, 785)

Body:
I think you should use axis=0.

>>> np.append((1,2),(2,),axis=0)
array([1, 2, 2])

If those tuples that you have posted are array shapes, then you can use

train = np.append(train_data, train_labels[:,None], axis=1)

The arrays must have the same number of dimensions (2 in this case). Using None in indexing for non-existing dimension adds a singleton dimension to a an array.

>>> train_labels[:,None].shape
(60000, 1)


问:
Library to generate a CHM file
I have been looking for a library that will expose functionality to allow me to generate CHM files. As far as I can tell, that does not exist and I will have to rely on CHMBuilder (in SandCastle) but I thought I would ask before going that route. </p>

答: There is a lib, and a (cross-platfomr) commandtool in Free Pascal. It is in Pascal (Delphi dialect) though.</p>

Title: Library to generate a CHM file


问:
NoReverseMatch at /sitemap.xml Django
Django Noob here.

NoReverseMatch at /sitemap.xml Reverse for 'article_detail' not found. 'article_detail' is not a valid view function or pattern name.

See models.py screenshot (code) to understand the error.

I don't know what I should put in place of article_details (see the code for explanation). Your help will appreciable.

Error-

Project Structure-

Code-

Dipesh_Pal Module Code-

settings.py-

```<code>INSTALLED_APPS = [
'django.contrib.sitemaps',
'django.contrib.sites',
]
SITE_ID = 1
</code>```

urls.py-

home Module Code-

sitemaps.py-

urls.py-

models.py-

The error in line 37. I am not exactly sure what I should put in place
  of "article_detail" or I am not sure what exactly wrong in my code.

For your information, I am referring this YouTube video- Click Here

My Github Repo for this App- Click Here

答:
NoReverseMatch at /sitemap.xml Reverse for 'article_detail' not found.
  'article_detail' is not a valid view function or pattern name.

This means that when it went looking for the view article_detail it could not be found. In your urls.py you have the line:

url(r'^(?P<slug>[w\-]+)/$', views.article_detail, name="article-detail")

You never included your views.py and this the question is in general formatted pretty poorly, but from what we can see it appears you just never declare that view (even though you reference it in the urls.py)

EDIT: There is also the possibility that you aren't passing the objects to index in your sitemap when you create the Sitemap, but again.. As the formatting isn't everything we need. We can only speculate.

So, definitely check that article_detail is working in general. If it is, go to where you are creating the data for your Sitemap object and make sure that you're passing an object with the url.

Title: NoReverseMatch at /sitemap.xml Django

Body:
Django Noob here.

NoReverseMatch at /sitemap.xml Reverse for 'article_detail' not found. 'article_detail' is not a valid view function or pattern name.

See models.py screenshot (code) to understand the error.

I don't know what I should put in place of article_details (see the code for explanation). Your help will appreciable.

Error-

Project Structure-

Code-

Dipesh_Pal Module Code-

settings.py-

INSTALLED_APPS = [
'django.contrib.sitemaps',
'django.contrib.sites',
]
SITE_ID = 1

urls.py-

home Module Code-

sitemaps.py-

urls.py-

models.py-

The error in line 37. I am not exactly sure what I should put in place
  of "article_detail" or I am not sure what exactly wrong in my code.

For your information, I am referring this YouTube video- Click Here

My Github Repo for this App- Click Here


问:
How to unzip s3 file through lambda and chain with other lambda functions using nodejs?
Two Issues over here:-
I have a zip file which once uploaded to s3 should trigger an event and
1. unzip the file
2. After unzip second lambda should trigger and call api.</p>

答:
If you want an AWS Lambda function to "unzip to S3", then the Lambda function would need to:

Download the Zip file to local storage

Unzip the files

Loop through the files and upload each one to Amazon S3

Please note that there is a maximum of 500MB of disk storage space available to Lambda functions (in the /tmp/ directory), and this space needs to hold both the zip file and the extracted zip files.

Also, you'll need to extend the timeout setting to give adequate time for the function to perform all of the above operations.


问:
Second async function never finishes
Here is a simplified version of some code I am writing for an electron app. I need two function to run, one after the other. Each needs to make an API call, and then wait for the response before finishing.

```<code>async function build_page()
{
    await func_1()
    await func_2()
}

async function func_1()
{
    console.log("1 Start")

    await send().then(
        function (response)
        {
            console.log("1 Middle")
        }
    )
    console.log("1 End")
}

async function func_2()
{
    console.log("2 Start")

    await send().then(
        function (response)
        {
            console.log("2 Middle")
        }
    )
    console.log("2 End")
}

function send()
{

    const request = require("request-promise-native")

    return request({
        url: "http://localhost:7296/Categories",
        method: "POST",
        json: true,
        body: {"token": localStorage.getItem("token")}
    })

}
</code>```

I want the console to print "1 Start, 1 Middle, 1 End, 2 Start, 2 Middle, 2 End", but currently, it only makes it to "2 Start". I am unsure why func_2 is not finishing. When I comment out the call to func_1, func_2 finishes as expected, and when I swap the calls to func_1 and func_2, then func_1 only makes it to "1 Start".

答:
The problem must of been something related to the request-promise-native library, because I was able to fix the issue by porting it to use the fetch library instead.

I replaced the body of the send function with the following code:

```<code>return fetch(
    "http://localhost:7296/".concat(endpoint),
    {
        method: method,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(input)
    }
).then(response => response.json())
</code>```

Title: Second async function never finishes

Body:
Here is a simplified version of some code I am writing for an electron app. I need two function to run, one after the other. Each needs to make an API call, and then wait for the response before finishing.

async function build_page()
{
    await func_1()
    await func_2()
}

async function func_1()
{
    console.log("1 Start")

    await send().then(
        function (response)
        {
            console.log("1 Middle")
        }
    )
    console.log("1 End")
}

async function func_2()
{
    console.log("2 Start")

    await send().then(
        function (response)
        {
            console.log("2 Middle")
        }
    )
    console.log("2 End")
}

function send()
{

    const request = require("request-promise-native")

    return request({
        url: "http://localhost:7296/Categories",
        method: "POST",
        json: true,
        body: {"token": localStorage.getItem("token")}
    })

}

I want the console to print "1 Start, 1 Middle, 1 End, 2 Start, 2 Middle, 2 End", but currently, it only makes it to "2 Start". I am unsure why func_2 is not finishing. When I comment out the call to func_1, func_2 finishes as expected, and when I swap the calls to func_1 and func_2, then func_1 only makes it to "1 Start".

Body:
The problem must of been something related to the request-promise-native library, because I was able to fix the issue by porting it to use the fetch library instead.

I replaced the body of the send function with the following code:

return fetch(
    "http://localhost:7296/".concat(endpoint),
    {
        method: method,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(input)
    }
).then(response => response.json())


问:
Unable to find Windows Docker Jenkins admin password
I ran docker jenkins image on my Windows using this command from command prompt:

```<code>F:\Docker\Jenkins>docker run -v "F:\Docker\Jenkins":/var/jenkins_home -p 8081:8080 -p 50001:50000 jenkins/jenkins
</code>```

The docker jenkins started fine & i then closed the command prompt without saving the output.

I am able to access the jenkins console using : http://localhost:8081/login?from=%2F

However, it is asking me for the admin password which I am not able to find.

Output below:

Unlock Jenkins
  To ensure Jenkins is securely set up by the administrator, a password has been written to the log (not sure where to find it?) and this file on the server:

/var/jenkins_home/secrets/initialAdminPassword

Please copy the password from either location and paste it below.

Below are the queries I have.

Question 1: How can I login in interactive mode to this running container so i can view the password from this file: /var/jenkins_home/secrets/initialAdminPassword

I don't want to stop and run in interactive mode but would like to interact with the running containers directly.

Question 2: I get the below error running this command.

```<code>F:\Docker\Jenkins>docker run -it "F:\Docker\Jenkins":/var/jenkins_home -p 8082:8080 -p 50002:50000 jenkins/jenkins
docker: invalid reference format.
See 'docker run --help'.
</code>```

I also tried -i -t but same error. Any suggestions there ?

答:
You don't have to login into docker machine.
The file is under F:\Docker\Jenkins\secrets\initialAdminPassword

-v "F:\Docker\Jenkins":/var/jenkins_home - it's bind mount a volume between docker disc and your disc on windows

Body:
I ran docker jenkins image on my Windows using this command from command prompt:

F:\Docker\Jenkins>docker run -v "F:\Docker\Jenkins":/var/jenkins_home -p 8081:8080 -p 50001:50000 jenkins/jenkins

The docker jenkins started fine & i then closed the command prompt without saving the output.

I am able to access the jenkins console using : http://localhost:8081/login?from=%2F

However, it is asking me for the admin password which I am not able to find.

Output below:

Unlock Jenkins
  To ensure Jenkins is securely set up by the administrator, a password has been written to the log (not sure where to find it?) and this file on the server:

/var/jenkins_home/secrets/initialAdminPassword

Please copy the password from either location and paste it below.

Below are the queries I have.

Question 1: How can I login in interactive mode to this running container so i can view the password from this file: /var/jenkins_home/secrets/initialAdminPassword

I don't want to stop and run in interactive mode but would like to interact with the running containers directly.

Question 2: I get the below error running this command.

F:\Docker\Jenkins>docker run -it "F:\Docker\Jenkins":/var/jenkins_home -p 8082:8080 -p 50002:50000 jenkins/jenkins
docker: invalid reference format.
See 'docker run --help'.

I also tried -i -t but same error. Any suggestions there ?


问:
Kotlin FP : Convert List<String> to Map<String,Int>
I have a List of String, I want to transform into a Map of occurrences. ( ~ The Map values are the count of many times the String was repeated in the List)

The imperative way, I'd write like the following

```<code>fun transformMap(list: List<String>): Map<String, Int> {
    val map = mutableMapOf<String,Int>()
    for(n in list){
        map.put(n,map.getOrDefault(n,0) + 1)
    }
    return map.toMap()
}
</code>```

How to write this in Functional Programming way ?

In Java 8+, this will be written like this

```<code>String[] note;
Map<String, Integer> noteMap = Arrays.stream(note)
         .collect(groupingBy(Function.identity(),
          collectingAndThen(counting(), Long::intValue)));
</code>```

答:
You can use Kotlin's Grouping to do this in one line via the Iterable<T>.groupingBy extension:

```<code>val myList = listOf("a", "b", "c", "a", "b", "a")
val myMap = myList.groupingBy { it }.eachCount()

println(myMap)
// Prints {a=3, b=2, c=1}
</code>```

Body:
I have a List of String, I want to transform into a Map of occurrences. ( ~ The Map values are the count of many times the String was repeated in the List)

The imperative way, I'd write like the following

fun transformMap(list: List<String>): Map<String, Int> {
    val map = mutableMapOf<String,Int>()
    for(n in list){
        map.put(n,map.getOrDefault(n,0) + 1)
    }
    return map.toMap()
}

How to write this in Functional Programming way ?

In Java 8+, this will be written like this

String[] note;
Map<String, Integer> noteMap = Arrays.stream(note)
         .collect(groupingBy(Function.identity(),
          collectingAndThen(counting(), Long::intValue)));

Body:
You can use Kotlin's Grouping to do this in one line via the Iterable<T>.groupingBy extension:

val myList = listOf("a", "b", "c", "a", "b", "a")
val myMap = myList.groupingBy { it }.eachCount()

println(myMap)
// Prints {a=3, b=2, c=1}


问:
How to decrypt a bitcoin.com json AES wallet backup?
Given you have a bitcoin wallet.json backup in the following format:

```<code>{
  "ct" : "xyz",
  "iter" : 10000,
  "adata" : "",
  "salt" : "xyz",
  "cipher" : "aes",
  "ks" : 128,
  "v" : 1,
  "mode" : "ccm",
  "iv" : "xyz",
  "ts" : 64
}
</code>```

where xyz are unique values and the wallet is encrypted with a password. What tools can you use to decrypt this wallet format?

答:
You can use an old version of the Bitgo NodeJS package to decrypt the wallet:

```<code>// index.js
var BitGoJS = require('./node_modules/bitgo/src/index.js');
var bitgo = new BitGoJS.BitGo();

console.log('Decrypting...');
var password = 'passw0rd';
var encryptedWallet = '{"iv":"xyz","v":1,"iter":10000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"xyz","ct":"xyz"}';
var decryptedString = bitgo.decrypt({ password: password, input: encryptedWallet });

console.log('Private key:', decryptedString);

</code>```

```<code>// package.json
{
  "name": "Decrypt",
  "version": "1.0.0",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "bitgo": "1.0.0"
  }
}
</code>```

After replacing the password and encryptedWallet vars with your own values, you can then npm install and npm start to decrypt the wallet.

Body:
Given you have a bitcoin wallet.json backup in the following format:

{
  "ct" : "xyz",
  "iter" : 10000,
  "adata" : "",
  "salt" : "xyz",
  "cipher" : "aes",
  "ks" : 128,
  "v" : 1,
  "mode" : "ccm",
  "iv" : "xyz",
  "ts" : 64
}

where xyz are unique values and the wallet is encrypted with a password. What tools can you use to decrypt this wallet format?

Body:
You can use an old version of the Bitgo NodeJS package to decrypt the wallet:

// index.js
var BitGoJS = require('./node_modules/bitgo/src/index.js');
var bitgo = new BitGoJS.BitGo();

console.log('Decrypting...');
var password = 'passw0rd';
var encryptedWallet = '{"iv":"xyz","v":1,"iter":10000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"xyz","ct":"xyz"}';
var decryptedString = bitgo.decrypt({ password: password, input: encryptedWallet });

console.log('Private key:', decryptedString);

// package.json
{
  "name": "Decrypt",
  "version": "1.0.0",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "bitgo": "1.0.0"
  }
}

After replacing the password and encryptedWallet vars with your own values, you can then npm install and npm start to decrypt the wallet.


问:
How to reverse an animation on mouse out after hover
So, it is possible to have reverse animation on mouse out such as:

```<code>.class{
   transform: rotate(0deg);

}
.class:hover{
   transform: rotate(360deg);
}
</code>```

but, when using @keyframes animation, I couldn't get it to work, e.g:

```<code>.class{
   animation-name: out;
   animation-duration:2s;

}
.class:hover{
   animation-name: in;
   animation-duration:5s;
   animation-iteration-count:infinite;

}
@keyframe in{
    to {transform: rotate(360deg);}
}

@keyframe out{
    to {transform: rotate(0deg);}
}
</code>```

What is the optimal solution, knowing that I'd need iterations and animation itself?

http://jsfiddle.net/khalednabil/eWzBm/

答:
we can use requestAnimationFrame to reset animation and reverse it when browser paints in next frame.

Also use onmouseenter and onmouseout event handlers to reverse animation direction

As per

Any rAFs queued in your event handlers will be executed in the same
  frame. Any rAFs queued in a rAF will be executed in the next frame.

function fn(el, isEnter) {
  el.className = "";
   requestAnimationFrame(() => {
    requestAnimationFrame(() => {
        el.className = isEnter? "in": "out";
    });
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.in{
  animation: k 1s forwards;
}

.out{
  animation: k 1s forwards;
  animation-direction: reverse;
}

@keyframes k
{
from {transform: rotate(0deg);}
to   {transform: rotate(360deg);}
}</code>```

```

Body:
So, it is possible to have reverse animation on mouse out such as:

.class{
   transform: rotate(0deg);

}
.class:hover{
   transform: rotate(360deg);
}

but, when using @keyframes animation, I couldn't get it to work, e.g:

.class{
   animation-name: out;
   animation-duration:2s;

}
.class:hover{
   animation-name: in;
   animation-duration:5s;
   animation-iteration-count:infinite;

}
@keyframe in{
    to {transform: rotate(360deg);}
}

@keyframe out{
    to {transform: rotate(0deg);}
}

What is the optimal solution, knowing that I'd need iterations and animation itself?

http://jsfiddle.net/khalednabil/eWzBm/

Body:
we can use requestAnimationFrame to reset animation and reverse it when browser paints in next frame.

Also use onmouseenter and onmouseout event handlers to reverse animation direction

As per

Any rAFs queued in your event handlers will be executed in the same
  frame. Any rAFs queued in a rAF will be executed in the next frame.

function fn(el, isEnter) {
  el.className = "";
   requestAnimationFrame(() => {
    requestAnimationFrame(() => {
        el.className = isEnter? "in": "out";
    });
  });
}

.in{
  animation: k 1s forwards;
}

.out{
  animation: k 1s forwards;
  animation-direction: reverse;
}

@keyframes k
{
from {transform: rotate(0deg);}
to   {transform: rotate(360deg);}
}

<div style="width:100px; height:100px; background-color:red"
  onmouseenter="fn(this, true)"
   onmouseleave="fn(this, false)"
     ></div>


问:
How to split a file and keep the first line in each of the pieces?
Given: One big text-data file (e.g. CSV format) with a 'special' first line (e.g., field names).

Wanted: An equivalent of the coreutils split -l command, but with the additional requirement that the header line from the original file appear at the beginning of each of the resulting pieces.

I am guessing some concoction of split and head will do the trick?

答:
Inspired by @Arkady's comment on a one-liner.

MYFILE variable simply to reduce boilerplate

split doesn't show file name, but the --additional-suffix option allows us to easily control what to expect

removal of intermediate files via rm $part (assumes no files with same suffix)

MYFILE=mycsv.csv && for part in $(split -n4 --additional-suffix=foo $MYFILE; ls *foo); do cat <(head -n1 $MYFILE) $part > $MYFILE.$part; rm $part; done

Evidence:

```<code>-rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xaafoo
-rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xabfoo
-rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xacfoo
-rw-rw-r--  1 ec2-user ec2-user  32040110 Jun  1 23:18 mycsv.csv.xadfoo
</code>```

and of course head -2 *foo to see the header is added.

Body:
Inspired by @Arkady's comment on a one-liner.

MYFILE variable simply to reduce boilerplate

split doesn't show file name, but the --additional-suffix option allows us to easily control what to expect

removal of intermediate files via rm $part (assumes no files with same suffix)

MYFILE=mycsv.csv && for part in $(split -n4 --additional-suffix=foo $MYFILE; ls *foo); do cat <(head -n1 $MYFILE) $part > $MYFILE.$part; rm $part; done

Evidence:

-rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xaafoo
-rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xabfoo
-rw-rw-r--  1 ec2-user ec2-user  32040108 Jun  1 23:18 mycsv.csv.xacfoo
-rw-rw-r--  1 ec2-user ec2-user  32040110 Jun  1 23:18 mycsv.csv.xadfoo

and of course head -2 *foo to see the header is added.


问:
How not to erase data from a file during serialization?
Good evening,

I realize an application currently using the C # language and I had to resort to serialization using XmlSerializer.

I had to be able to save a list in an xml file. It was then necessary that I could recover the data of this file to be able to recover the list. I managed to do all this and here is my code:

To save the list:

Stream stream = File.OpenWrite(chemin);
           XmlSerializer xmlSer = new XmlSerializer(typeof(List<Utilisateur>));
           xmlSer.Serialize(stream,listeUtilisateurs);
           stream.Close();
```

<p>To retrieve the list:</p>

<pre class="lang-cs prettyprint-override"><code>Stream stream = File.OpenRead(chemin);
            XmlSerializer xmlSer = new XmlSerializer(typeof(List<Utilisateur>));
            List<Utilisateur> listrecuperee = (List<Utilisateur>)xmlSer.Deserialize(stream);
            listeUtilisateurs = listrecuperee;
            stream.Close();
</code>```

However, the problem is that every time I save the list, the data that was before it go away, I want to keep it, I actually want it to write after the file. Would you have a solution please? Cordially.

答:
Yes, we can do what you want.

Code to serialize to the same file:

```<code>var xmlSer = new XmlSerializer(typeof(List<Utilisateur>));

var xmlWriterSettings = new XmlWriterSettings
{
    OmitXmlDeclaration = true,
    Indent = true // need only for pretty print
};

bool append = File.Exists("test.txt");

using (var streamWriter = new StreamWriter("test.txt", append))
using (var xmlWriter = XmlWriter.Create(streamWriter, xmlWriterSettings))
{
    xmlSer.Serialize(xmlWriter, listeUtilisateurs);
    streamWriter.WriteLine(); // need only for pretty print
}
</code>```

Code for reading a set of data:

```<code>int orderNumber = 2; // for example, read the second data collection in order

var xmlReaderSettings = new XmlReaderSettings
{
    ConformanceLevel = ConformanceLevel.Fragment
};

using (var reader = XmlReader.Create("test.txt", xmlReaderSettings))
{
    int count = 0;
    while (reader.ReadToFollowing("ArrayOfUtilisateur"))
    {
        count++;
        if (count == orderNumber)
            break;
    }
    var list = (List<Utilisateur>)xmlSer.Deserialize(reader);
}
</code>```

Of course, you need to add the necessary checks when reading.

This way of using a single file is pretty ugly, though it works. Therefore, consider other options for saving your data.

Body:
Good evening,

I realize an application currently using the C # language and I had to resort to serialization using XmlSerializer.

I had to be able to save a list in an xml file. It was then necessary that I could recover the data of this file to be able to recover the list. I managed to do all this and here is my code:

To save the list:

Stream stream = File.OpenWrite(chemin);
           XmlSerializer xmlSer = new XmlSerializer(typeof(List<Utilisateur>));
           xmlSer.Serialize(stream,listeUtilisateurs);
           stream.Close();

To retrieve the list:

Stream stream = File.OpenRead(chemin);
            XmlSerializer xmlSer = new XmlSerializer(typeof(List<Utilisateur>));
            List<Utilisateur> listrecuperee = (List<Utilisateur>)xmlSer.Deserialize(stream);
            listeUtilisateurs = listrecuperee;
            stream.Close();

However, the problem is that every time I save the list, the data that was before it go away, I want to keep it, I actually want it to write after the file. Would you have a solution please? Cordially.

Body:
Yes, we can do what you want.

Code to serialize to the same file:

var xmlSer = new XmlSerializer(typeof(List<Utilisateur>));

var xmlWriterSettings = new XmlWriterSettings
{
    OmitXmlDeclaration = true,
    Indent = true // need only for pretty print
};

bool append = File.Exists("test.txt");

using (var streamWriter = new StreamWriter("test.txt", append))
using (var xmlWriter = XmlWriter.Create(streamWriter, xmlWriterSettings))
{
    xmlSer.Serialize(xmlWriter, listeUtilisateurs);
    streamWriter.WriteLine(); // need only for pretty print
}

Code for reading a set of data:

int orderNumber = 2; // for example, read the second data collection in order

var xmlReaderSettings = new XmlReaderSettings
{
    ConformanceLevel = ConformanceLevel.Fragment
};

using (var reader = XmlReader.Create("test.txt", xmlReaderSettings))
{
    int count = 0;
    while (reader.ReadToFollowing("ArrayOfUtilisateur"))
    {
        count++;
        if (count == orderNumber)
            break;
    }
    var list = (List<Utilisateur>)xmlSer.Deserialize(reader);
}

Of course, you need to add the necessary checks when reading.

This way of using a single file is pretty ugly, though it works. Therefore, consider other options for saving your data.


问:
Check first radiobutton using PHP
I would like to check the first radiobutton element in PHP. The radiobuttons are populated from a MySQL database. </p>

```<code><?php
echo('<ul id="radio" class="input-list">');
     $stmt = mysqli_prepare($link, "SELECT name, price FROM cases ORDER BY price");
     $stmt->execute();
     $stmt->bind_result($case_name, $case_price);
     $isFirst = true;
     while($stmt->fetch()) {
         echo '<li>
        <input class="selectedoptions" id="'.$case_name.'" name="config-case" value="'.$case_price.'" type="radio"'.$isFirst?' checked':''.' onchange="updateImage(this.id);">
        <label class="sub-label" for="'.$case_name.'">'.$case_name.' [£'.$case_price.']</label>
        </li>';
        $isFirst = false;
     }
     $stmt->close();
?>
</code>```

<p>This outputs "checked" for each row, as opposed to the radiobutton and label. What am I doing wrong? Thank you. </p>

答:
Enclose your ternary operation in parenthesis to evaluate it first.

```<code>.... . ($isFirst ? ' checked' : '') . ...
</code>```

Otherwise the concatenation operations take precedence.

Title: Check first radiobutton using PHP

Body:
I would like to check the first radiobutton element in PHP. The radiobuttons are populated from a MySQL database.

<?php
echo('
');
     $stmt = mysqli_prepare($link, "SELECT name, price FROM cases ORDER BY price");
     $stmt->execute();
     $stmt->bind_result($case_name, $case_price);
     $isFirst = true;
     while($stmt->fetch()) {
         echo '

        <input class="selectedoptions" id="'.$case_name.'" name="config-case" value="'.$case_price.'" type="radio"'.$isFirst?' checked':''.' onchange="updateImage(this.id);">
        '.$case_name.' [£'.$case_price.']

';
        $isFirst = false;
     }
     $stmt->close();
?>

This outputs "checked" for each row, as opposed to the radiobutton and label. What am I doing wrong? Thank you.

Body:
Enclose your ternary operation in parenthesis to evaluate it first.

.... . ($isFirst ? ' checked' : '') . ...

Otherwise the concatenation operations take precedence.


问:
How to align text vertically in a div displayed like a grid?
I've been trying to align vertically some text that I've putted in a div, but I wasn't able to do it.

I've already tried to display the div as a table, and display the inner divs as table-cell but this didn't worked because I'm displaying the div that contains the other divs as a grid, nonetheless I setted some css attributes that in theory it should allow me to vertical align the text, but it doesn't worked as well.

/* CSS */

/* TABLA */

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto auto auto auto;
  grid-template-rows: 80px 300px;
  grid-gap: 10px;
  background-color: #424242;
  padding: 10px;
  margin: 50px;
}

.grid-container>div {
  background-color: #D0D3D4;
  text-align: center;
  padding: 20px 0;
  font-size: 25px;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif, Haettenschweiler, 'Arial Narrow Bold', sans-serif, Geneva, Tahoma, sans-serif;
}

#align {
  text-align: center;
  vertical-align: middle;
  line-height: 90px;
}

/* IMAGENES */

.resize {
  width: 300px;
  height: 250px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->

<div class="grid-container">
  <!-- TITULOS -->
  <div>Portada</div>
  <div>Nombre</div>
  <div>Artista</div>
  <div>Precio</div>
  <div>Cantidad</div>
  <div>Total</div>
  <div>Cancelar</div>
  <!-- CONTENIDOS -->
  <div><img src="rsc/parachutes.jpg" class="resize"></div>
  <div class="align">Parachutes</div>
  <div>Coldplay</div>
  <div>S/100</div>
  <div>1</div>
  <div>S/100</div>
  <div><button>Eliminar</button></div>
  <div><img src="rsc/dookie.jpg" class="resize"></div>
  <div>Dookie</div>
  <div>Green Day</div>
  <div>S/115</div>
  <div>1</div>
  <div>S/115</div>
  <div><button>Eliminar</button></div>
</div></code>```

I want to get the text of each row centered (including the image), but instead I ended up getting this.

答:
I think you are looking for something like this...?

```<code>.grid-container>div {
  display: flex;
  justify-content: center;
  align-items: center;
  ...
}
</code>```

https://codepen.io/DOMUSNETWORK/pen/byOmrG

Body:
I've been trying to align vertically some text that I've putted in a div, but I wasn't able to do it.

I've already tried to display the div as a table, and display the inner divs as table-cell but this didn't worked because I'm displaying the div that contains the other divs as a grid, nonetheless I setted some css attributes that in theory it should allow me to vertical align the text, but it doesn't worked as well.

/* CSS */

/* TABLA */

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto auto auto auto;
  grid-template-rows: 80px 300px;
  grid-gap: 10px;
  background-color: #424242;
  padding: 10px;
  margin: 50px;
}

.grid-container>div {
  background-color: #D0D3D4;
  text-align: center;
  padding: 20px 0;
  font-size: 25px;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif, Haettenschweiler, 'Arial Narrow Bold', sans-serif, Geneva, Tahoma, sans-serif;
}

#align {
  text-align: center;
  vertical-align: middle;
  line-height: 90px;
}

/* IMAGENES */

.resize {
  width: 300px;
  height: 250px;
}

Portada

Nombre

Artista

Precio

Cantidad

Total

Cancelar

Parachutes

Coldplay

S/100

1

S/100

<button>Eliminar</button>

Dookie

Green Day

S/115

1

S/115

<button>Eliminar</button>

I want to get the text of each row centered (including the image), but instead I ended up getting this.

Body:
I think you are looking for something like this...?

.grid-container>div {
  display: flex;
  justify-content: center;
  align-items: center;
  ...
}

https://codepen.io/DOMUSNETWORK/pen/byOmrG


问:
Getting React-Viro Build working on android
I am new to react-native development.

I have been trying to get a React-Viro project to successfully build onto my mobile S8 android device and have been struggling a lot. I am in a windows 10 environment using git-bash.

First Approach
I have been following the steps on the react-viro quickstart website.

1) react-native init ProjectAR --version0.57.7

2) cd ViroSample

3) npm install -S -E react-viro

4) copy the files from node_modules\react-viro\bin\files\javascript* to the root

5) In App.js assign API Key.

6) In index.android.js change to the name of my project
AppRegistry.registerComponent('ProjectAR', () => App);

When I run react-native run-android I get the error on my phone

Unable to resolve module 'react-native/Libraries/DeprecatedPropTypes/DeprecatedStyleSheetPropType from ...\ProjectAR\node_modules\react-viro\components\ViroImage.js

Module 'react-native/Libraries/DeprecatedPropTypes/DeprecatedStyleSheetPropType' does not exist in the current Haste module map

Second Approach
1) npm install -g react-viro-cli

2) react-viro init NewArProject

3) cd NewArProject

4) ./setup-ide.sh android

5) In App.js assign API Key.

When I run react-native run-android I get the error in my terminal

FAILURE: Build failed with an exception.

What went wrong:
  Task 'installDebug' not found in project ':app'. Some candidates are: 'installArDebug', 'installGvrDebug', 'installOvrDebug'.

I go into my android directory and do
./gradlew app:installArDebug

But I get an error

Execution failed for task ':app:generateArDebugBuildConfig'.

Please help. Thanks

答: Use react-native run-android --variant=gvrDebug instead.


问:
Unity 2018.3 HDRP - Change material color programatically?
I am using the new HDRP/LitTesselation shader.

I would like to change the Base Color + Opacity at runtime:

I added this code to the game object's script:

```<code>void start()
{
        Color color = new Color(100, 50, 100, 150);

        //Fetch the Renderer from the GameObject
        Renderer rend = GetComponent<Renderer>();

        //Set the main Color of the Material to green
        rend.material.shader = Shader.Find("_Color");
        rend.material.SetColor("_Color", color);
}
</code>```

But it generates an Hidden/InternalShaderError error in the shader.  Can anyone point me in the right direction?

答:
This is for HDRP/Lit:

```<code>private Material _mat;

void Start()
{
    Renderer nRend = GetComponent<Renderer>();
    _mat = nRend.material;
}

void Update()
{
    Color nNew = //do whatever you want here
    _mat.SetColor("_BaseColor", nNew);
}
</code>```

I once read that "sharedMaterial" should be used instead of "material".
However, I think that was just a typo. "sharedMaterial" would affect ALL HDRP/Lit materials, I think.

Body:
I am using the new HDRP/LitTesselation shader.

I would like to change the Base Color + Opacity at runtime:

I added this code to the game object's script:

void start()
{
        Color color = new Color(100, 50, 100, 150);

        //Fetch the Renderer from the GameObject
        Renderer rend = GetComponent<Renderer>();

        //Set the main Color of the Material to green
        rend.material.shader = Shader.Find("_Color");
        rend.material.SetColor("_Color", color);
}

But it generates an Hidden/InternalShaderError error in the shader.  Can anyone point me in the right direction?

Body:
This is for HDRP/Lit:

private Material _mat;

void Start()
{
    Renderer nRend = GetComponent<Renderer>();
    _mat = nRend.material;
}

void Update()
{
    Color nNew = //do whatever you want here
    _mat.SetColor("_BaseColor", nNew);
}

I once read that "sharedMaterial" should be used instead of "material".
However, I think that was just a typo. "sharedMaterial" would affect ALL HDRP/Lit materials, I think.


问:
Can multiple web applications service one domain?
I maintain a fairly large ASP.NET MVC website that's running on the .NET Framework 4.7 and hosted by a dedicated IIS server that I administer. This lives at example.com.

I need to add a bunch of new functionality, and I'd like to do this using ASP.NET Core, so that I can be going with the newer technology to learn it and reduce my obsolescence exposure.

BUT I would like this to be invisible to the users of the existing site. Specifically, I want the new functionality to be accessible at example.com/new-stuff, so that it works the same as the example.com/current-stuff that they're used to, in terms of navigation and url structure.

Can I set up IIS or the app routes so that everything works as before, but a request for example.com/{some-pattern} is serviced by my new and different web app, while requests that don't match the pattern are serviced by the old app? Or is there some other way of accomplishing my requirement?

答: I wouldn't go with routing or redirection rules. I will set iis virtual folders, so no url pattern will change.</p>