问:
Manipulating values not matching HH:MM:SS format - python
I have a dataframe that looks like the following:

    arrival     departure
0   23:55:00    23:57:00
1   23:57:00    23:59:00
2   23:59:00    24:01:00
3   24:01:00    24:03:00
4   24:03:00    24:05:00
```

<p>I am working with data that cover a whole day and part of the day after. Data are (most of the time) in the <code>HH:MM:SS</code> format. However some time values are higher than 23:59:59 and go up to 27:00:00.</p>

<p>I would like to get the time difference between <code>departure</code> and <code>arrival</code> columns.</p>

<p>I tried using <code>datetime</code> to do that but I guess something went wrong:</p>

<pre class="lang-py prettyprint-override"><code>FMT = '%H:%M:%S'

delta = datetime.strptime(df['departure'], FMT) - datetime.strptime(df['arrival'], FMT)
</code>```

Which raises the following error:

ValueError: time data '24:01:00' does not match format '%H:%M:%S'
```

Is there a way to get the time difference between these two columns even though their format do not always match the HH:MM:SS format?

答:
You could use timedelta from datetime

```<code>import datetime

delta1 = datetime.timedelta(hours=23, minutes=59, seconds=0)
delta2 = datetime.timedelta(hours=24, minutes=01, seconds=0)
timedelta = delta2 - delta1
>>> timedelta # or timedelta.to_seconds()
datetime.timedelta(seconds=120)
</code>```

Give you the delta in seconds. Full example:

```<code>import datetime

arrival = "24:01:00"
departure = "24:03:00"

def get_time_from_string(t):
    return dict(
        zip(["hours", "minutes", "seconds"], list(map(lambda x: int(x), t.split(":"))),)
    )

delta1 = datetime.timedelta(**get_time_from_string(arrival))
delta2 = datetime.timedelta(**get_time_from_string(departure))

delta = delta2 - delta1
print(delta.total_seconds())
</code>```

Body:
I have a dataframe that looks like the following:

    arrival     departure
0   23:55:00    23:57:00
1   23:57:00    23:59:00
2   23:59:00    24:01:00
3   24:01:00    24:03:00
4   24:03:00    24:05:00

I am working with data that cover a whole day and part of the day after. Data are (most of the time) in the HH:MM:SS format. However some time values are higher than 23:59:59 and go up to 27:00:00.

I would like to get the time difference between departure and arrival columns.

I tried using datetime to do that but I guess something went wrong:

FMT = '%H:%M:%S'

delta = datetime.strptime(df['departure'], FMT) - datetime.strptime(df['arrival'], FMT)

Which raises the following error:

ValueError: time data '24:01:00' does not match format '%H:%M:%S'

Is there a way to get the time difference between these two columns even though their format do not always match the HH:MM:SS format?

Body:
You could use timedelta from datetime

import datetime

delta1 = datetime.timedelta(hours=23, minutes=59, seconds=0)
delta2 = datetime.timedelta(hours=24, minutes=01, seconds=0)
timedelta = delta2 - delta1
>>> timedelta # or timedelta.to_seconds()
datetime.timedelta(seconds=120)

Give you the delta in seconds. Full example:

import datetime

arrival = "24:01:00"
departure = "24:03:00"

def get_time_from_string(t):
    return dict(
        zip(["hours", "minutes", "seconds"], list(map(lambda x: int(x), t.split(":"))),)
    )

delta1 = datetime.timedelta(**get_time_from_string(arrival))
delta2 = datetime.timedelta(**get_time_from_string(departure))

delta = delta2 - delta1
print(delta.total_seconds())


来源: stackexchange

问:
Dynamically render information from two arrays
I have this data:

```<code>"PensionPlanSummary": [
        {
            "Type": "DefinedContributionPension",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 425.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],

        },
        {
            "Type": "Welfare",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 252.0
                },
                {
                    "Year": 2017,
                    "Value": 389.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ]

        }
    ]
</code>```

I want to render data in this table:

Focus only on Participants. As you can see the data is not populated correct because it is populating by row and for example it should skip 2016 and 2017 for DefinedContributionPension and to fill 2018.
This table is result of this code:

```<code>{element.Participants.reverse().map((el, ind) => {
                              return uniqueYears.map((e, i) => {
                                // console.log(el.Year);
                                if (el.Year == e) {
                                  console.log(el.Year);
                                  return (
                                    <td key={ind}>
                                      ${numeral(el.Value).format("0,0")}
                                    </td>
                                  );
                                } else {
                                  return <td key={ind}> - </td>;
                                }
                              });
                            })}
</code>```

uniqueYears =[2016,2017,2018]
element is the single object (I have another map above). So as you can see I am mapping 1 time the participants and 1 time unique years and finding the 1 record that is true for the condition of equality of the element year. As you can see it is not putting the dash - and it is not populating table correct. I tried looping in other way - first to loop over the uniqueYears array and then to element.Participants but again it not worked as expected. Any ideas how to make it?
P.S.: Table should look like this way:

But lets focus only on participants as in example.

答:
I have tried coming up with a very dirty solution in as little as time as possible, but it seems to be working for me

pensionPlans and uniqueYears are arrays that you have mentioned. My code is below

```<code>pensionPlans.map(e => {
    if(e.Type === "DefinedContributionPension"){
uniqueYears.map(year => {
    e.Participants.map(item => {
    if(item.Year === year){
     console.log('found')
    } else {
    console.log("not found")
    }
    })
})
  }
})
</code>```

Also, I notice that you have used == instead of === while checking for if (el.Year == e). Although correct, this might have some implications later as it doesn't check the type.

You can see my answer running in console here https://jsfiddle.net/z65mp0s8/

ContentLicense: CC BY-SA 4.0

Body:
I have this data:

"PensionPlanSummary": [
        {
            "Type": "DefinedContributionPension",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 425.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 629282.0
                }
            ],

        },
        {
            "Type": "Welfare",
            "Participants": [
                {
                    "Year": 2018,
                    "Value": 252.0
                },
                {
                    "Year": 2017,
                    "Value": 389.0
                }
            ],
            "TotalAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ],
            "NetAssets": [
                {
                    "Year": 2018,
                    "Value": 0.0
                },
                {
                    "Year": 2017,
                    "Value": 0.0
                }
            ]

        }
    ]

I want to render data in this table:

Focus only on Participants. As you can see the data is not populated correct because it is populating by row and for example it should skip 2016 and 2017 for DefinedContributionPension and to fill 2018.
This table is result of this code:

{element.Participants.reverse().map((el, ind) => {
                              return uniqueYears.map((e, i) => {
                                // console.log(el.Year);
                                if (el.Year == e) {
                                  console.log(el.Year);
                                  return (

                                      ${numeral(el.Value).format("0,0")}

                                  );
                                } else {
                                  return  - 	;
                                }
                              });
                            })}

uniqueYears =[2016,2017,2018]
element is the single object (I have another map above). So as you can see I am mapping 1 time the participants and 1 time unique years and finding the 1 record that is true for the condition of equality of the element year. As you can see it is not putting the dash - and it is not populating table correct. I tried looping in other way - first to loop over the uniqueYears array and then to element.Participants but again it not worked as expected. Any ideas how to make it?
P.S.: Table should look like this way:

But lets focus only on participants as in example.

Body:
I have tried coming up with a very dirty solution in as little as time as possible, but it seems to be working for me

pensionPlans and uniqueYears are arrays that you have mentioned. My code is below

pensionPlans.map(e => {
    if(e.Type === "DefinedContributionPension"){
uniqueYears.map(year => {
    e.Participants.map(item => {
    if(item.Year === year){
     console.log('found')
    } else {
    console.log("not found")
    }
    })
})
  }
})

Also, I notice that you have used == instead of === while checking for if (el.Year == e). Although correct, this might have some implications later as it doesn't check the type.

You can see my answer running in console here https://jsfiddle.net/z65mp0s8/


问:
Convert Character date/time with am and pm to date/time format
I am attempting to convert a character date time to a date/time format using strptime. The data is in MDY_HM (1/29/20 3:43pm).

My code currently looks like this:

```<code>comp_report_tz$Start_Date_Time <- strptime(comp_report_tz$Start_Date_Time, format = "%m/%d/%y %H:%M %p")
</code>```

The output for each observation simply shows: "< POSIXlt >"

I don't receive any errors when executing.

答:
Make the following changes:

use %I for the hour

use %p for the am/pm.

ensure that the format pattern is in the precise pattern of the data -- it's not in the question

you likely want POSIXct, not POSIXlt

thus we use this format

```<code>as.POSIXct("1/29/20 3:43pm", format = "%m/%d/%y %I:%M%p")
## [1] "2020-01-29 15:43:00 EST"
</code>```

Body:
I am attempting to convert a character date time to a date/time format using strptime. The data is in MDY_HM (1/29/20 3:43pm).

My code currently looks like this:

comp_report_tz$Start_Date_Time <- strptime(comp_report_tz$Start_Date_Time, format = "%m/%d/%y %H:%M %p")

The output for each observation simply shows: "< POSIXlt >"

I don't receive any errors when executing.

Body:
Make the following changes:

use %I for the hour

use %p for the am/pm.

ensure that the format pattern is in the precise pattern of the data -- it's not in the question

you likely want POSIXct, not POSIXlt

thus we use this format

as.POSIXct("1/29/20 3:43pm", format = "%m/%d/%y %I:%M%p")
## [1] "2020-01-29 15:43:00 EST"


问:
Changing font colour in Textboxes in IE which are disabled
I noticed that you can change the colour of text in textboxes which are disabled in Firefox applying a simple class but could not get a way to do it in IE 6/7. Does anyone out there have a elegant solution to achieve this.</p>

答:
I noticed that you can change the colour of text in textboxes which are disabled in Firefox

I think what the question is trying to say is that this:

```<code><textarea disabled="disabled" style="color: red;">Hello</textarea>
</code>```

Results in grey text in IE, vs. red in Fox. FWIW, Opera also gives grey, whilst the WebKit browsers give red.

This is a pure CSS issue to do with how much form fields are rendered according to the OS's widget set and how much according to the CSS rules. This has always been an area of great cross-browser difference. Scripting is not relevant, much though SO would like “use jQuery” to be the answer to every question.

The usual workaround is to use ‘readonly’ instead of ‘disabled’, then use styling (eg. based off ‘class="disabled"’) to reproduce whatever shaded disabled effect you want. ‘readonly’ controls are not turned into OS-level-disabled widgets, giving you more latitude to style them.

ContentLicense: CC BY-SA 2.5

Body:
I noticed that you can change the colour of text in textboxes which are disabled in Firefox

I think what the question is trying to say is that this:

<textarea disabled="disabled" style="color: red;">Hello</textarea>

Results in grey text in IE, vs. red in Fox. FWIW, Opera also gives grey, whilst the WebKit browsers give red.

This is a pure CSS issue to do with how much form fields are rendered according to the OS's widget set and how much according to the CSS rules. This has always been an area of great cross-browser difference. Scripting is not relevant, much though SO would like “use jQuery” to be the answer to every question.

The usual workaround is to use ‘readonly’ instead of ‘disabled’, then use styling (eg. based off ‘class="disabled"’) to reproduce whatever shaded disabled effect you want. ‘readonly’ controls are not turned into OS-level-disabled widgets, giving you more latitude to style them.

OwnerDisplayName: bobince


问:
Why does this error pop if if i try to tun my node.js webserver (6.0.0)
I have got this error when i try to run my node 6.0.0 web server.

https://i.stack.imgur.com/v1H9v.png

答: Turns out I forgot to initialize a package file.</p>


问:
Error while angular unit testing with Jasmine and Karma
I have already imported the angular material in my spec.ts but I am getting the below error when trying to run the test that is ng test of this particular component:

Error: Template parse errors:

'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

[ERROR ->]

                      ][dataSource]="parts" matSort  class="mat-elevation-z8">

                "): ng:///DynamicTestModule/PartViewComponent.html@6:23
                The pipe 'uuidAbbrev' could not be found ("eader-cell *matHeaderCellDef mat-sort-header>Uuid
                       {{[ERROR ->]row.uuid|uuidAbbrev}}

                "): ng:///DynamicTestModule/PartViewComponent.html@10:44
                Can't bind to 'matHeaderRowDef' since it isn't a known property of 'tr'. ("

                    ]matHeaderRowDef="displayedProps">

                    [ERROR ->]

                    ]*matRowDef="let row; columns: displayedProps;">

                "): ng:///DynamicTestModule/PartViewComponent.html@24:35
                Property binding matRowDefColumns not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("

                    [ERROR ->]

                http://localhost:9876/_karma_webpack_/vendor.js:36418:17)
                    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (http://localhost:9876/_karma_webpack_/vendor.js:54593:19)
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (http://localhost:9876/_karma_webpack_/vendor.js:60159:37)
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (http://localhost:9876/_karma_webpack_/vendor.js:60146:23)
                    at http://localhost:9876/_karma_webpack_/vendor.js:60089:62
                    at Set.forEach ()
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (http://localhost:9876/_karma_webpack_/vendor.js:60089:19)
                    at http://localhost:9876/_karma_webpack_/vendor.js:60007:19
                    at Object.then (http://localhost:9876/_karma_webpack_/vendor.js:36409:77)
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndAllComponents (http://localhost:9876/_karma_webpack_/vendor.js:60005:26)
            ```

答:
A couple of things:

To avoid importing modules from Angular Material directly you need to create a separated Angular module. This is a good practice, and you should stick to it :)

Second,
You need to import the Angular Material module you just create in your TestBed:

```<code>  beforeEach(async(() => {
            TestBed.configureTestingModule({
              imports: [MaterialModule],
              declarations: [PartViewComponent],
              providers: [PartService]
            })
            .compileComponents();
          }));
</code>```

Example of my MaterialModule:

```<code>import { NgModule } from '@angular/core';
import {
  MatAutocompleteModule,
  MatButtonModule,
  MatButtonToggleModule,
  MatCardModule,
  MatCheckboxModule,
  MatChipsModule,
  MatDatepickerModule,
  MatDialogModule,
  MatExpansionModule,
  MatFormFieldModule,
  MatGridListModule,
  MatIconModule,
  MatInputModule,
  MatListModule,
  MatMenuModule,
  MatNativeDateModule,
  MatRadioModule,
  MatRippleModule,
  MatSelectModule,
  MatSidenavModule,
  MatSlideToggleModule,
  MatSnackBarModule,
  MatStepperModule,
  MatTableModule,
  MatTabsModule,
  MatToolbarModule,
  MatTooltipModule
} from '@angular/material';

@NgModule({
  imports: [
    MatSidenavModule,
    MatToolbarModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MatDialogModule,
    MatSelectModule,
    MatInputModule,
    MatFormFieldModule,
    MatAutocompleteModule,
    MatInputModule,
    MatTableModule,
    MatSlideToggleModule,
    MatRadioModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatSnackBarModule,
    MatTooltipModule,
    MatTabsModule,
    MatRippleModule,
    MatGridListModule,
    MatStepperModule,
    MatCheckboxModule,
    MatMenuModule,
    MatChipsModule,
    MatExpansionModule
  ],
  exports: [
    MatSidenavModule,
    MatToolbarModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MatDialogModule,
    MatSelectModule,
    MatInputModule,
    MatFormFieldModule,
    MatAutocompleteModule,
    MatTableModule,
    MatSlideToggleModule,
    MatRadioModule,
    MatDatepickerModule,
    MatSnackBarModule,
    MatTooltipModule,
    MatTabsModule,
    MatRippleModule,
    MatGridListModule,
    MatStepperModule,
    MatMenuModule,
    MatCheckboxModule,
    MatChipsModule,
    MatExpansionModule
  ],
  declarations: []
})
export class MaterialModule {}
</code>```

Last but not least, probably you'll get another error related to pipe uuidAbbrev, make sure to add it to your declarations array in the TestBed.configureTestingModule

Body:
A couple of things:

To avoid importing modules from Angular Material directly you need to create a separated Angular module. This is a good practice, and you should stick to it :)

Second,
You need to import the Angular Material module you just create in your TestBed:

  beforeEach(async(() => {
            TestBed.configureTestingModule({
              imports: [MaterialModule],
              declarations: [PartViewComponent],
              providers: [PartService]
            })
            .compileComponents();
          }));

Example of my MaterialModule:

import { NgModule } from '@angular/core';
import {
  MatAutocompleteModule,
  MatButtonModule,
  MatButtonToggleModule,
  MatCardModule,
  MatCheckboxModule,
  MatChipsModule,
  MatDatepickerModule,
  MatDialogModule,
  MatExpansionModule,
  MatFormFieldModule,
  MatGridListModule,
  MatIconModule,
  MatInputModule,
  MatListModule,
  MatMenuModule,
  MatNativeDateModule,
  MatRadioModule,
  MatRippleModule,
  MatSelectModule,
  MatSidenavModule,
  MatSlideToggleModule,
  MatSnackBarModule,
  MatStepperModule,
  MatTableModule,
  MatTabsModule,
  MatToolbarModule,
  MatTooltipModule
} from '@angular/material';

@NgModule({
  imports: [
    MatSidenavModule,
    MatToolbarModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MatDialogModule,
    MatSelectModule,
    MatInputModule,
    MatFormFieldModule,
    MatAutocompleteModule,
    MatInputModule,
    MatTableModule,
    MatSlideToggleModule,
    MatRadioModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatSnackBarModule,
    MatTooltipModule,
    MatTabsModule,
    MatRippleModule,
    MatGridListModule,
    MatStepperModule,
    MatCheckboxModule,
    MatMenuModule,
    MatChipsModule,
    MatExpansionModule
  ],
  exports: [
    MatSidenavModule,
    MatToolbarModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MatDialogModule,
    MatSelectModule,
    MatInputModule,
    MatFormFieldModule,
    MatAutocompleteModule,
    MatTableModule,
    MatSlideToggleModule,
    MatRadioModule,
    MatDatepickerModule,
    MatSnackBarModule,
    MatTooltipModule,
    MatTabsModule,
    MatRippleModule,
    MatGridListModule,
    MatStepperModule,
    MatMenuModule,
    MatCheckboxModule,
    MatChipsModule,
    MatExpansionModule
  ],
  declarations: []
})
export class MaterialModule {}

Last but not least, probably you'll get another error related to pipe uuidAbbrev, make sure to add it to your declarations array in the TestBed.configureTestingModule


问:
How can I give Linear gradient to my entire flutter app?
Here's the code,
The problem is that there is a gap of black colour around the rounded corners due to theme data being black. I can't fill it with gradient present in the above container. image has been attached. any solution?

```<code> class _TrackListState extends State<TrackList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: Container(
                height: double.infinity,
                //child: Text('hello'),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                      colors: [Color(0xFF04DCB6), Color(0xFF6DE079)]),
                ),
                child: Column(
                  children: <Widget>[],
                ),
              ),
            ),
            Expanded(
              flex: 3,
              child: Container(
                //padding: EdgeInsets.symmetric(horizontal: 20),
                foregroundDecoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

The image where I am having the problem

答:
I tested it on DartPad. Give it a try. Using stack, you can fill the background and draw on top of it.</p>

```<code>      @override
      Widget build(BuildContext context) {
        return Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                gradient:
                    LinearGradient(colors: [Color(0xFF04DCB6), Color(0xFF6DE079)]),
              ),
            ),
            Positioned.fill(
              top: 80,
              child: Container(
                foregroundDecoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
              ),
            ),
          ],
        );
      }
</code>```

Body:
Here's the code,
The problem is that there is a gap of black colour around the rounded corners due to theme data being black. I can't fill it with gradient present in the above container. image has been attached. any solution?

 class _TrackListState extends State<TrackList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: Container(
                height: double.infinity,
                //child: Text('hello'),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                      colors: [Color(0xFF04DCB6), Color(0xFF6DE079)]),
                ),
                child: Column(
                  children: <Widget>[],
                ),
              ),
            ),
            Expanded(
              flex: 3,
              child: Container(
                //padding: EdgeInsets.symmetric(horizontal: 20),
                foregroundDecoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

The image where I am having the problem

Body:
I tested it on DartPad. Give it a try. Using stack, you can fill the background and draw on top of it.

      @override
      Widget build(BuildContext context) {
        return Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                gradient:
                    LinearGradient(colors: [Color(0xFF04DCB6), Color(0xFF6DE079)]),
              ),
            ),
            Positioned.fill(
              top: 80,
              child: Container(
                foregroundDecoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
              ),
            ),
          ],
        );
      }


问:
How to handle realign of components in runtime after screen resize delphi
I searched a lot in google to get a clearer info on how I could solve my current issue, but I got scalability of components as the best answer, that's... not yet my issue.

So, long story short: I want to realign components on my form after the user resizes the window, the form is populated dinamically from a SQL query, this is the constructor code:

```<code>procedure TForm2.MakeWindow;
var
  dummyMaskedit, dummyEdit: TEdit;
  dummyMemo: TMemo;
  dummyCombobox: TComboBox;
  dummyLabel: TLabel;
  dummyLBox: TListBox;
  dummybutton: TButton;
  i, f: integer;
  buffer, workarea: double;
begin
  FDQDB.Close;
  FDQDB.Open('SELECT * FROM Defs WHERE active = 1');

  i := 0;
  f := 1;
  buffer := Layout1.Width;
  workarea := Layout1.Width;
  SetLength(aMasks, 0);
  while not FDQDB.Eof do
  begin
    case AnsiIndexStr(FDQDB.FieldByName('comptype').AsString,
      ['tedit', 'tcombobox', 'tmaskedit', 'tlistbox']) of
      0: // TEdit
        begin
          dummyEdit := TEdit.Create(self);
          dummyEdit.Parent := Form2.Layout1;
          dummyEdit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyEdit.Width >= 0 then
          begin
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end;
          dummyEdit.Name := 'field' + IntToStr(f);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyEdit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyEdit.Position.Y - 17;
            Position.X := dummyEdit.Position.X;
          end;
        end;

      1: // TComboBox
        begin
          dummyCombobox := TComboBox.Create(self);
          dummyCombobox.Parent := Form2.Layout1;
          dummyCombobox.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyCombobox.Width >= 0 then
          begin
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end;
          dummyCombobox.Name := 'field' + IntToStr(f);
          dummyCombobox.Items.Delimiter := '|';
          dummyCombobox.Items.StrictDelimiter := true;
          dummyCombobox.Items.DelimitedText :=
            AnsiUpperCase(FDQDB.FieldByName('combovalue').AsString);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyCombobox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyCombobox.Position.Y - 17;
            Position.X := dummyCombobox.Position.X;
          end;
        end;

      2: // TMaskEdit
        begin
          dummyMaskedit := TEdit.Create(self);
          dummyMaskedit.Parent := Form2.Layout1;
          dummyMaskedit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyMaskedit.Width >= 0 then
          begin
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end;
          dummyMaskedit.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyMaskedit.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyMaskedit.OnExit := MaskTextExit;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyMaskedit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyMaskedit.Position.Y - 17;
            Position.X := dummyMaskedit.Position.X;
          end;
        end;

      3: // TListBox
        begin
          dummyLBox := TListBox.Create(self);
          dummyLBox.Parent := Form2.Layout1;
          dummyLBox.Width := FDQDB.FieldByName('size').AsInteger;
          inc(i);
          buffer := workarea;
          if buffer - dummyLBox.Width >= 0 then
          begin
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end;
          dummyLBox.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyLBox.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyLBox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyLBox.Position.Y - 17;
            Position.X := dummyLBox.Position.X;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '+';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y;
            Name := 'ba' + dummyLBox.Name;
            OnClick := ButtonsAddClick;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '-';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y + 28;
            Name := 'br' + dummyLBox.Name;
            OnClick := ButtonsRemClick;
          end;
        end;
    end;
    FDQDB.Next;
  end;
  FDQDB.Close;
end;
</code>```

That works nice and pretty on the windowed state of the application, this code is applied to the onCreate event of the form:

```<code>procedure TForm2.FormCreate(Sender: TObject);
begin
  FDCDB.Params.Database := ExtractFilePath(ParamStr(0)) + 'window.db';
  MakeWindow;
end;
</code>```

The first form, main form of the application, is the one that summons the new form that has the components built in runtime:

```<code>procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  Application.CreateForm(TForm2, Form2);
  Form2.Layout1.parent := Self.Layout1.Parent;
  Form2.Layout1.Width := Self.Layout1.Width;
end;
</code>```

The second form has a TLayout, just like the first form. Then, when I create the form I bring the TLayout of the second form to the first. So far so good, it works when the application is launched in windowed mode.
But when I put form1 in fullscreen mode, then click the Button that creates the form2, the components stays on the same position as in windowed mode. I've tried changing the workarea variable to these:

```<code>Screen.width, //components behave as the application were in fullscreen the whole time
Screen.WorkAreaWidth, //same as screen.width
(Layout1.Parent as TLayout).Width, //invalid typecast
(Layout1.GetParentComponent as TLayout).Width //invalid typecast
</code>```

None of them worked.
I wanna be able to adjust the position of the components on the screen based on its visual width, so if the user resizes the window before creating the new form, the components gets aligned properly.
Anyone knows a solution for that? Thanks in advance

答:
The form has ClientWidth and ClientHeight properties which work well in OnResize to dynamically size a control based on the area available. The OnResize fires before the form is made visible. For example to have a Memo1 with a 100 border around it:</p>

```<code>procedure TForm1.FormResize(Sender: TObject);
begin
  memo1.Position.X := 100;  // Only needs to be done once but here so all code is in one spot
  memo1.Position.Y := 100;
  memo1.Width := form1.ClientWidth - 200;
  memo1.Height := form1.ClientHeight - 200;
end;
</code>```

Body:
I searched a lot in google to get a clearer info on how I could solve my current issue, but I got scalability of components as the best answer, that's... not yet my issue.

So, long story short: I want to realign components on my form after the user resizes the window, the form is populated dinamically from a SQL query, this is the constructor code:

procedure TForm2.MakeWindow;
var
  dummyMaskedit, dummyEdit: TEdit;
  dummyMemo: TMemo;
  dummyCombobox: TComboBox;
  dummyLabel: TLabel;
  dummyLBox: TListBox;
  dummybutton: TButton;
  i, f: integer;
  buffer, workarea: double;
begin
  FDQDB.Close;
  FDQDB.Open('SELECT * FROM Defs WHERE active = 1');

  i := 0;
  f := 1;
  buffer := Layout1.Width;
  workarea := Layout1.Width;
  SetLength(aMasks, 0);
  while not FDQDB.Eof do
  begin
    case AnsiIndexStr(FDQDB.FieldByName('comptype').AsString,
      ['tedit', 'tcombobox', 'tmaskedit', 'tlistbox']) of
      0: // TEdit
        begin
          dummyEdit := TEdit.Create(self);
          dummyEdit.Parent := Form2.Layout1;
          dummyEdit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyEdit.Width >= 0 then
          begin
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end;
          dummyEdit.Name := 'field' + IntToStr(f);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyEdit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyEdit.Position.Y - 17;
            Position.X := dummyEdit.Position.X;
          end;
        end;

      1: // TComboBox
        begin
          dummyCombobox := TComboBox.Create(self);
          dummyCombobox.Parent := Form2.Layout1;
          dummyCombobox.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyCombobox.Width >= 0 then
          begin
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end;
          dummyCombobox.Name := 'field' + IntToStr(f);
          dummyCombobox.Items.Delimiter := '|';
          dummyCombobox.Items.StrictDelimiter := true;
          dummyCombobox.Items.DelimitedText :=
            AnsiUpperCase(FDQDB.FieldByName('combovalue').AsString);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyCombobox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyCombobox.Position.Y - 17;
            Position.X := dummyCombobox.Position.X;
          end;
        end;

      2: // TMaskEdit
        begin
          dummyMaskedit := TEdit.Create(self);
          dummyMaskedit.Parent := Form2.Layout1;
          dummyMaskedit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyMaskedit.Width >= 0 then
          begin
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end;
          dummyMaskedit.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyMaskedit.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyMaskedit.OnExit := MaskTextExit;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyMaskedit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyMaskedit.Position.Y - 17;
            Position.X := dummyMaskedit.Position.X;
          end;
        end;

      3: // TListBox
        begin
          dummyLBox := TListBox.Create(self);
          dummyLBox.Parent := Form2.Layout1;
          dummyLBox.Width := FDQDB.FieldByName('size').AsInteger;
          inc(i);
          buffer := workarea;
          if buffer - dummyLBox.Width >= 0 then
          begin
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end;
          dummyLBox.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyLBox.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyLBox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyLBox.Position.Y - 17;
            Position.X := dummyLBox.Position.X;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '+';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y;
            Name := 'ba' + dummyLBox.Name;
            OnClick := ButtonsAddClick;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '-';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y + 28;
            Name := 'br' + dummyLBox.Name;
            OnClick := ButtonsRemClick;
          end;
        end;
    end;
    FDQDB.Next;
  end;
  FDQDB.Close;
end;

That works nice and pretty on the windowed state of the application, this code is applied to the onCreate event of the form:

procedure TForm2.FormCreate(Sender: TObject);
begin
  FDCDB.Params.Database := ExtractFilePath(ParamStr(0)) + 'window.db';
  MakeWindow;
end;

The first form, main form of the application, is the one that summons the new form that has the components built in runtime:

procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  Application.CreateForm(TForm2, Form2);
  Form2.Layout1.parent := Self.Layout1.Parent;
  Form2.Layout1.Width := Self.Layout1.Width;
end;

The second form has a TLayout, just like the first form. Then, when I create the form I bring the TLayout of the second form to the first. So far so good, it works when the application is launched in windowed mode.
But when I put form1 in fullscreen mode, then click the Button that creates the form2, the components stays on the same position as in windowed mode. I've tried changing the workarea variable to these:

Screen.width, //components behave as the application were in fullscreen the whole time
Screen.WorkAreaWidth, //same as screen.width
(Layout1.Parent as TLayout).Width, //invalid typecast
(Layout1.GetParentComponent as TLayout).Width //invalid typecast

None of them worked.
I wanna be able to adjust the position of the components on the screen based on its visual width, so if the user resizes the window before creating the new form, the components gets aligned properly.
Anyone knows a solution for that? Thanks in advance

Body:
The form has ClientWidth and ClientHeight properties which work well in OnResize to dynamically size a control based on the area available. The OnResize fires before the form is made visible. For example to have a Memo1 with a 100 border around it:

procedure TForm1.FormResize(Sender: TObject);
begin
  memo1.Position.X := 100;  // Only needs to be done once but here so all code is in one spot
  memo1.Position.Y := 100;
  memo1.Width := form1.ClientWidth - 200;
  memo1.Height := form1.ClientHeight - 200;
end;


问:
Plotting colorbar in Python 3
I am trying to color the errorbar points based on the color from an array. But getting an error. My code is shown below:

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable, coolwarm as cmap
from matplotlib.colors import Normalize

fig = plt.figure(1)
sp = fig.add_subplot(1, 1, 1)
sp.set_xlabel(r'$x$')
sp.set_ylabel(r'$y$')

x = np.random.rand(10)
y = np.random.rand(10)
M = np.logspace(9, 10, 10)
norm = Normalize(vmin=8, vmax=11,clip=False)  # controls the min and max of the colorbar
smap = ScalarMappable(cmap=cmap, norm=norm)
for xi, yi, Mi in zip(x, y, M):
    c = cmap(norm(np.log10(Mi)))  # make sure to color by log of mass, not mass
    sp.errorbar(
        xi,
        yi,
        yerr=[[.1], [.1]],
        xerr=[[.1], [.1]],
        ecolor=c,
        marker='o',
        mec=c,
        mfc=c
    )

cb = plt.colorbar(smap)
cb.set_label(r'$\log_{10}M$')
</code>```

I am getting the following error:
TypeError: You must first set_array for mappable

答:
For matplotlib < 3.1, you need to set an array - which can be empty

```<code>sm = ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
fig.colorbar(sm)
</code>```

For matplotlib >= 3.1, this is not necessary any more.

```<code>sm = ScalarMappable(cmap=cmap, norm=norm)
fig.colorbar(sm)
</code>```

Title: Plotting colorbar in Python 3

Body:
I am trying to color the errorbar points based on the color from an array. But getting an error. My code is shown below:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable, coolwarm as cmap
from matplotlib.colors import Normalize

fig = plt.figure(1)
sp = fig.add_subplot(1, 1, 1)
sp.set_xlabel(r'$x$')
sp.set_ylabel(r'$y$')

x = np.random.rand(10)
y = np.random.rand(10)
M = np.logspace(9, 10, 10)
norm = Normalize(vmin=8, vmax=11,clip=False)  # controls the min and max of the colorbar
smap = ScalarMappable(cmap=cmap, norm=norm)
for xi, yi, Mi in zip(x, y, M):
    c = cmap(norm(np.log10(Mi)))  # make sure to color by log of mass, not mass
    sp.errorbar(
        xi,
        yi,
        yerr=[[.1], [.1]],
        xerr=[[.1], [.1]],
        ecolor=c,
        marker='o',
        mec=c,
        mfc=c
    )

cb = plt.colorbar(smap)
cb.set_label(r'$\log_{10}M$')

I am getting the following error:
TypeError: You must first set_array for mappable

Body:
For matplotlib < 3.1, you need to set an array - which can be empty

sm = ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
fig.colorbar(sm)

For matplotlib >= 3.1, this is not necessary any more.

sm = ScalarMappable(cmap=cmap, norm=norm)
fig.colorbar(sm)


问:
Dynamics 365 V9.0 detail(child) entity target doesnt contain parent entity reference when creating using entity.RelatedEntities
I'm work on Dynamics 365 online V9. I have encounted a problem when creating a new entity with related entity.

I have custom entities new_quote and new_quotedetail, with 1-N Relationship. I have a plugin on entity new_quotedetail on preCreate event that will check if the target contains the key "new_quoteid", otherwise il will block the creation.
the problem is that I want to create new_quote with its all details in the same time, so I use entity.RelatedEntities to create them. but it look like the child detail entity target doesn't contain the new_quoteid, is it normal?

I have tried to register the plugin in post-create event but still have the problem

Thanks
Song

答:
You will not be able to do this at one go.
Reason been your child entity has plugin on create which checks and restrict creation unless you have primary entity created.
I will suggest separate logic in 2 calls I.e first create parent entity and after create of parent then fire plugin to create child entity.</p>


问:
Send and receive data through jQuery ajax and update database in Entity Framework in ASP.NET MVC
When I select dropdownlist I want to retrieve data from database according to dropdownlist ID.

The whole row is retrieved through an ajax call and I only want PurchasePrice and RemainingQuantity to display through label in view.

Second is: I want to update tbl_addproduct when user give some date from input text I created a function in jQuery but don't know how to update table row through PID.

Like previously I used in ASP.NET

```<code>update tbl_AddProduct
set Date = @date
where PID = @pid
</code>```

I have two model classes:

```<code>public class addproduct
{
    public int PID { get; set; }
    public int VID { get; set; }
    public string ProductName { get; set; }
    public decimal ProductQuantity { get; set; }
    public decimal PurchasePrice { get; set; }
    public decimal SellingPrice { get; set; }
    public decimal RemainingQuantity { get; set; }
    public DateTime Date { get; set; }
    public int SID { get; set; }
    public Boolean Paid { get; set; }
}
</code>```

Second view model. through this performing cascading dropdownlist

```<code>public class vendorproductVM
{
    public addproduct addpro { get; set; }
    public int VID { get; set; }
    public int PID { get; set; }
}
</code>```

Index view:

```<code>        <div class="row">
            <div class="col-sm-6">
                @Html.Label("Vendor Name")
                @if (ViewBag.vendorlist != null)
                {
                    @Html.DropDownListFor(m => m.VID, ViewBag.vendorlist as SelectList, "Select", new { @class = "  form-control" })
                }

            </div>
            <div class="col-sm-6">
                @Html.Label("Product Name")
                @Html.DropDownListFor(m => m.PID, new SelectList(" "), "--Select--", new { @class = "form-control" })

            </div>
        </div>
        <div class="row">

            <div class="col-sm-4">
                @Html.Label("Remaining Quantity")
                @Html.LabelFor(m => m.addpro.RemainingQuantity)
            </div>

            <div class="col-sm-4">
                @Html.Label("Purchase Price")
                @Html.LabelFor(m => m.addpro.PurchasePrice )
            </div>

            <div class="col-sm-4">
                @Html.Label("Date")
                <input type="text" id="txt_date" />
            </div>
        </div>
        <div>
            <div class="col-sm-4" style="align-content: center">
                <input type="button" id="btn_save" value="Save" CssClass="btn btn-success" />
                <input type="button" id="btn_cancel" value="Cancel" CssClass="btn btn-danger" />
            </div>
        </div>
<script>
$(function () {
     $("#VID").change(function () {

        var vid = $("#VID").val();
        $("#PID").empty();
        $.ajax({
            type: "post",
            url: "/ProductInventory/getproductlist",
            //datatype: "Json",
            data: { VID: vid, },
            success: function (products) {
                debugger
                $.each(products, function (index, row) {
                    $("#PID").append("<option value='" + row.PID + "'>" + row.ProductName + "</option>");
                });
                //$("productlist").append();
            },
            failure: function () {
                alert("something goes wrong")
            }
        })
    });

    $(function () {
    $("#btn_save").click(function () {
        $.ajax({
            type: "Post",
            url: "/ProductInventory/updatedate",
            data: {
                date: $("#txt_date").val(),
            },
            success: function (da) {
                alert("updated date successfully");
            },
            failure: function (da) {
                alert("error");
            },
        })
   })
})

$("#PID").change(function () {
        var pid = $("#PID").val();

        $.ajax({
            type: "post",
            url: "/ProductInventory/getremaining",
            data: { PID: pid },
            success: (function (data) {
                debugger
                $.each(data, function (index, value) {
                // I want to show remaining amount and purchase price in label
                // and I tried below code this
                $("#lblremquantity").html(parseInt(value.RemainingQuantity))
                    //$("#RemaingQuantity").append("<label value='" + value.PID + "'>" +
                    value.RemaingQuantity + "</label>");
                });
            })
        })
    });
})
</script>
</code>```

My controller:

```<code>public class ProductInventoryController : Controller
{
    private db_shopEntities db = new db_shopEntities();

    // GET: ProductInventory
    public ActionResult Index()
    {
        ViewBag.vendorlist = new SelectList(getvendorlist(), "VID", "VendorName");
        return View();
    }

    public List<tbl_AddVendor> getvendorlist()
    {
       List<tbl_AddVendor> vendors = db.tbl_AddVendor.ToList();
       return vendors;
    }

    public JsonResult getproductlist(int VID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<tbl_AddProduct> products = db.tbl_AddProduct.Where(x => x.VID == VID).ToList();
        var pro = products;
        // ViewBag.productlist = new SelectList(products, "VID", "VendorName");
        return Json(products, JsonRequestBehavior.AllowGet);
    }

    public JsonResult getremainingquantity(int PID)
    {
        db.Configuration.ProxyCreationEnabled = false;

        List<tbl_AddProduct> remquantity = db.tbl_AddProduct.Where(x => x.PID == PID).ToList();
        return Json(remquantity, JsonRequestBehavior.AllowGet);
    }

    public JsonResult updatedate(string date)
    {
        DateTime sdate = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
        db.Configuration.ProxyCreationEnabled = false;

        // I want to update tbl_addproduct.. update date column when submit
        return Json(success, JsonRequestBehavior.AllowGet);
    }
}
</code>```

答:
if this a new project maybe you try blazor ? </p>

<p>also you can use jquery but this is not a modern approach </p>

```<code>$.ajax({
    //type: 'post',
    url: 'http://///////',
    data: { 'filter': JSON.stringify(filter) },
    success: function (data) {
        callback(data);
    },
    error: function (ex, textStatus, errorThrown) {
        SetAlert('Помилка доступу до сервера ' + textStatus + '  ' + errorThrown, 'danger', false);

    }
});
</code>```

Body:
When I select dropdownlist I want to retrieve data from database according to dropdownlist ID.

The whole row is retrieved through an ajax call and I only want PurchasePrice and RemainingQuantity to display through label in view.

Second is: I want to update tbl_addproduct when user give some date from input text I created a function in jQuery but don't know how to update table row through PID.

Like previously I used in ASP.NET

update tbl_AddProduct
set Date = @date
where PID = @pid

I have two model classes:

public class addproduct
{
    public int PID { get; set; }
    public int VID { get; set; }
    public string ProductName { get; set; }
    public decimal ProductQuantity { get; set; }
    public decimal PurchasePrice { get; set; }
    public decimal SellingPrice { get; set; }
    public decimal RemainingQuantity { get; set; }
    public DateTime Date { get; set; }
    public int SID { get; set; }
    public Boolean Paid { get; set; }
}

Second view model. through this performing cascading dropdownlist

public class vendorproductVM
{
    public addproduct addpro { get; set; }
    public int VID { get; set; }
    public int PID { get; set; }
}

Index view:

                @Html.Label("Vendor Name")
                @if (ViewBag.vendorlist != null)
                {
                    @Html.DropDownListFor(m => m.VID, ViewBag.vendorlist as SelectList, "Select", new { @class = "  form-control" })
                }

                @Html.Label("Product Name")
                @Html.DropDownListFor(m => m.PID, new SelectList(" "), "--Select--", new { @class = "form-control" })

                @Html.Label("Remaining Quantity")
                @Html.LabelFor(m => m.addpro.RemainingQuantity)

                @Html.Label("Purchase Price")
                @Html.LabelFor(m => m.addpro.PurchasePrice )

                @Html.Label("Date")
                <input type="text" id="txt_date" />

                <input type="button" id="btn_save" value="Save" CssClass="btn btn-success" />
                <input type="button" id="btn_cancel" value="Cancel" CssClass="btn btn-danger" />

My controller:

public class ProductInventoryController : Controller
{
    private db_shopEntities db = new db_shopEntities();

    // GET: ProductInventory
    public ActionResult Index()
    {
        ViewBag.vendorlist = new SelectList(getvendorlist(), "VID", "VendorName");
        return View();
    }

    public List<tbl_AddVendor> getvendorlist()
    {
       List<tbl_AddVendor> vendors = db.tbl_AddVendor.ToList();
       return vendors;
    }

    public JsonResult getproductlist(int VID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<tbl_AddProduct> products = db.tbl_AddProduct.Where(x => x.VID == VID).ToList();
        var pro = products;
        // ViewBag.productlist = new SelectList(products, "VID", "VendorName");
        return Json(products, JsonRequestBehavior.AllowGet);
    }

    public JsonResult getremainingquantity(int PID)
    {
        db.Configuration.ProxyCreationEnabled = false;

        List<tbl_AddProduct> remquantity = db.tbl_AddProduct.Where(x => x.PID == PID).ToList();
        return Json(remquantity, JsonRequestBehavior.AllowGet);
    }

    public JsonResult updatedate(string date)
    {
        DateTime sdate = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
        db.Configuration.ProxyCreationEnabled = false;

        // I want to update tbl_addproduct.. update date column when submit
        return Json(success, JsonRequestBehavior.AllowGet);
    }
}

Body:
if this a new project maybe you try blazor ?

also you can use jquery but this is not a modern approach

$.ajax({
    //type: 'post',
    url: 'http://///////',
    data: { 'filter': JSON.stringify(filter) },
    success: function (data) {
        callback(data);
    },
    error: function (ex, textStatus, errorThrown) {
        SetAlert('Помилка доступу до сервера ' + textStatus + '  ' + errorThrown, 'danger', false);

    }
});


问:
Dismissible Height not matching child height
I am new to Flutter, but I really enjoy the language and hope to find some answers to my probably very dumb issue :)

I have a ToDo List App and it contains a ListView with dismissible tiles.
I added a divier to seperate tiles, but after adding a dividor the height of the Dismissible does not match its child anymore.

As you can see without dividors the dismissible height matches the one of its child:

As you can see with the dividors the dismissible height does not match the one of its child. Or atleast that is what I think (keep in mind my non exisiting knowledge of this language). The dismissible height seems greater than the one of the child.

This is how I build the dismissibles:

```<code>return Dismissible(
          key: Key(item.getId()),
          direction: DismissDirection.endToStart,
          background: Container(
            alignment: AlignmentDirectional.centerEnd,
            color: Colors.red,
            child: Padding(
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 20.0, 0.0),
              child: Icon(
                Icons.delete,
                color: Colors.white,
              ),
            ),
          ),
          onDismissed: (direction) {
            toDoRemove(index);
          },
          child: Column(children: <Widget>[
            ListTile(
              leading: Theme(
                  data: ThemeData(unselectedWidgetColor: Colors.white24),
                  child: Checkbox(
                      checkColor: Colors.white,
                      activeColor: Colors.blue,
                      value: item.isDone(),
                      onChanged: (bool newValue) {
                        toDoToggle(index, newValue);
                      })),
              title: Text(item.getTitle()),
            ),
            Divider(
              color: Colors.white24,
              thickness: 0.0,
            ),
          ]));
</code>```

As can be seen in the code the child of the Dismissible is a Column which contains two children:

List Tile

Divider

I would appreciate any Help. Thank you :)

答:
Okay so I messed up. Instead of wrapping the divider inside the dismissible it would be smarter to have the divider in a column with the dismissible. This way the divider is not contained in the dismissible anymore.

Updated Code:

```<code> return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[
        Dismissible(
          ...
          child: // No Column anymore
            ListTile(
              leading: Theme(
                  data: ThemeData(unselectedWidgetColor: Colors.white24),
                  child: Checkbox(
                      checkColor: Colors.white,
                      activeColor: Colors.blue,
                      value: item.isDone(),
                      onChanged: (bool newValue) {
                        toDoToggle(index, newValue);
                      })),
              title: Text(item.getTitle()),
            ),
          ),
        Container(decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.white24, width: 0.4))))
      ]);
</code>```

And also appearently Dividers always have some paddings thus I used a Container with decoration to mimic a divider.

Here is the result:

And now it works as expected.

Body:
I am new to Flutter, but I really enjoy the language and hope to find some answers to my probably very dumb issue :)

I have a ToDo List App and it contains a ListView with dismissible tiles.
I added a divier to seperate tiles, but after adding a dividor the height of the Dismissible does not match its child anymore.

As you can see without dividors the dismissible height matches the one of its child:

As you can see with the dividors the dismissible height does not match the one of its child. Or atleast that is what I think (keep in mind my non exisiting knowledge of this language). The dismissible height seems greater than the one of the child.

This is how I build the dismissibles:

return Dismissible(
          key: Key(item.getId()),
          direction: DismissDirection.endToStart,
          background: Container(
            alignment: AlignmentDirectional.centerEnd,
            color: Colors.red,
            child: Padding(
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 20.0, 0.0),
              child: Icon(
                Icons.delete,
                color: Colors.white,
              ),
            ),
          ),
          onDismissed: (direction) {
            toDoRemove(index);
          },
          child: Column(children: <Widget>[
            ListTile(
              leading: Theme(
                  data: ThemeData(unselectedWidgetColor: Colors.white24),
                  child: Checkbox(
                      checkColor: Colors.white,
                      activeColor: Colors.blue,
                      value: item.isDone(),
                      onChanged: (bool newValue) {
                        toDoToggle(index, newValue);
                      })),
              title: Text(item.getTitle()),
            ),
            Divider(
              color: Colors.white24,
              thickness: 0.0,
            ),
          ]));

As can be seen in the code the child of the Dismissible is a Column which contains two children:

List Tile

Divider

I would appreciate any Help. Thank you :)

Body:
Okay so I messed up. Instead of wrapping the divider inside the dismissible it would be smarter to have the divider in a column with the dismissible. This way the divider is not contained in the dismissible anymore.

Updated Code:

 return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[
        Dismissible(
          ...
          child: // No Column anymore
            ListTile(
              leading: Theme(
                  data: ThemeData(unselectedWidgetColor: Colors.white24),
                  child: Checkbox(
                      checkColor: Colors.white,
                      activeColor: Colors.blue,
                      value: item.isDone(),
                      onChanged: (bool newValue) {
                        toDoToggle(index, newValue);
                      })),
              title: Text(item.getTitle()),
            ),
          ),
        Container(decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.white24, width: 0.4))))
      ]);

And also appearently Dividers always have some paddings thus I used a Container with decoration to mimic a divider.

Here is the result:

And now it works as expected.


问:
Can I use stat to show human readable size of file?
I'm trying to use stat command to display a list of files in the current directory, sorted by largest  to smallest.
my script is

```<code>filelist=$(ls -p | grep -v/)
filesize=$(stat -c "%s : %n" $filelist | sort -nr)
</code>```

It works however it displays the size in bytes. Is there a way to show it in a human readable format using stat? or do i have to try something else. thank you for the help.

答:
As far as I know, the stat program cannot display human readable sizes by itself. But you can always pipe it to another program that does it, such as numfmt:

stat -c %s /path/to/file | numfmt --to=iec
```

<p>Applied to your example, it would be:</p>

<pre class="lang-sh prettyprint-override"><code>filelist=$(ls -p | grep -v/)
filesize=$(
    stat -c "%s %n" $filelist | sort -nr -k1 | while read filesize filename; do
        printf '%s : %s\n' "$(numfmt --to=iec <<< $filesize)" "$filename"
    done
)
</code>```

Please note I added the -k1 option when calling sort because I assume you want to sort using the size, not the name.

numfmt has the advantage that you can choose how to want to display the human readable size. I suggested --to=iec because this is the most common for file sizes, but you may want to use other conversions. Please refer to the numfmt man page.

As a last note, I would advise you against storing files directly out of the $() capture because it will not work when a filename contains a space character. You could use find to list the files and get the size at the same time, e.g.:

find . -mindepth 1 -maxdepth 1 -not -type d -printf '%s %f\n' |
    sort -nr -k1 |
    while read filesize filename
do
    printf '%s : %s\n' "$(numfmt --to=iec <<< $filesize)" "$filename"
done
```

Body:
I'm trying to use stat command to display a list of files in the current directory, sorted by largest  to smallest.
my script is

filelist=$(ls -p | grep -v/)
filesize=$(stat -c "%s : %n" $filelist | sort -nr)

It works however it displays the size in bytes. Is there a way to show it in a human readable format using stat? or do i have to try something else. thank you for the help.

Body:
As far as I know, the stat program cannot display human readable sizes by itself. But you can always pipe it to another program that does it, such as numfmt:

stat -c %s /path/to/file | numfmt --to=iec

Applied to your example, it would be:

filelist=$(ls -p | grep -v/)
filesize=$(
    stat -c "%s %n" $filelist | sort -nr -k1 | while read filesize filename; do
        printf '%s : %s\n' "$(numfmt --to=iec <<< $filesize)" "$filename"
    done
)

Please note I added the -k1 option when calling sort because I assume you want to sort using the size, not the name.

numfmt has the advantage that you can choose how to want to display the human readable size. I suggested --to=iec because this is the most common for file sizes, but you may want to use other conversions. Please refer to the numfmt man page.

As a last note, I would advise you against storing files directly out of the $() capture because it will not work when a filename contains a space character. You could use find to list the files and get the size at the same time, e.g.:

find . -mindepth 1 -maxdepth 1 -not -type d -printf '%s %f\n' |
    sort -nr -k1 |
    while read filesize filename
do
    printf '%s : %s\n' "$(numfmt --to=iec <<< $filesize)" "$filename"
done


问:
Reading files from disk in Python in Parallel
I am in the process of migrating from MATLAB to Python, mainly because of the vast number of interesting Machine Learning packages available in Python. But one of the issues which have been the source of confusion for me, is parallel processing. In particular, I want to read thousand of text files from disk in a for loop and I want to do it in parallel. In MATLAB, using parfor instead of for will do the trick, but so far I haven't been able to figure out how to do this in python.
Here is an example of what I want to do. I want to read N text files, shape them into a N1xN2 array, and save each one into a a NxN1xN2 numpy array. And this array will be what I return from a function. Assuming the file names are file0001.dat, file0002.dat, etc., the code I like to parallelise is as follows:

```<code>import numpy as np
N=10000
N1=200
N2=100
result = np.empty([N, N1, N2])
for counter in range(N):
    t_str="%.4d" % counter
    filename = 'file_'+t_str+'.dat'
    temp_array = np.loadtxt(filename)
    temp_array.shape=[N1,N2]
    result[counter,:,:]=temp_array
</code>```

I run the codes on a cluster, so I can use many processors for the job. Hence, any comment on which of the parallelisation methods is more suitable for my task (if there are more than one) is most welcome.

NOTE: I am aware of this post, but in that post, there are only out1, out2, out3 variables to worry about, and they have been used explicitly as arguments of a function to be parallelised. But here, I have many 2D arrays that should be read from file and saved into a 3D array. So, the answer to that question is not general enough for my case (or that is how I understood it).

答:
It can be done using joblib library as follows:

```<code>def par_func(N1, N2, counter):
    import numpy as np
    t_str="%.4d" % counter
    filename = 'file_'+t_str+'.dat'
    temp_array = np.loadtxt(filename)
    temp_array.shape=[N1,N2]
    # temp_array = np.random.randn(N1, N2)  # use this line to test
    return temp_array

if __name__ == '__main__':
    import numpy as np

    N=1000
    N1=200
    N2=100

    from joblib import Parallel, delayed
    num_jobs = 2
    output_list = Parallel(n_jobs=num_jobs)(delayed(par_func)
                                            (N1, N2, counter)
                                            for counter in range(N))

    output_array = np.array(output_list)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am in the process of migrating from MATLAB to Python, mainly because of the vast number of interesting Machine Learning packages available in Python. But one of the issues which have been the source of confusion for me, is parallel processing. In particular, I want to read thousand of text files from disk in a for loop and I want to do it in parallel. In MATLAB, using parfor instead of for will do the trick, but so far I haven't been able to figure out how to do this in python.
Here is an example of what I want to do. I want to read N text files, shape them into a N1xN2 array, and save each one into a a NxN1xN2 numpy array. And this array will be what I return from a function. Assuming the file names are file0001.dat, file0002.dat, etc., the code I like to parallelise is as follows:

import numpy as np
N=10000
N1=200
N2=100
result = np.empty([N, N1, N2])
for counter in range(N):
    t_str="%.4d" % counter
    filename = 'file_'+t_str+'.dat'
    temp_array = np.loadtxt(filename)
    temp_array.shape=[N1,N2]
    result[counter,:,:]=temp_array

I run the codes on a cluster, so I can use many processors for the job. Hence, any comment on which of the parallelisation methods is more suitable for my task (if there are more than one) is most welcome.

NOTE: I am aware of this post, but in that post, there are only out1, out2, out3 variables to worry about, and they have been used explicitly as arguments of a function to be parallelised. But here, I have many 2D arrays that should be read from file and saved into a 3D array. So, the answer to that question is not general enough for my case (or that is how I understood it).

Body:
It can be done using joblib library as follows:

def par_func(N1, N2, counter):
    import numpy as np
    t_str="%.4d" % counter
    filename = 'file_'+t_str+'.dat'
    temp_array = np.loadtxt(filename)
    temp_array.shape=[N1,N2]
    # temp_array = np.random.randn(N1, N2)  # use this line to test
    return temp_array

if __name__ == '__main__':
    import numpy as np

    N=1000
    N1=200
    N2=100

    from joblib import Parallel, delayed
    num_jobs = 2
    output_list = Parallel(n_jobs=num_jobs)(delayed(par_func)
                                            (N1, N2, counter)
                                            for counter in range(N))

    output_array = np.array(output_list)


问:
How to improve performance of rendering?
I have service that adds each time response data to array: group: [].

Where response is object:

```<code>{"items": [{"id": 1}, {"id": 2}, {"id": 3}]}
</code>```

Problem is that it is rendered so long in template and renders each time when changes comes to array group:

```<code><div class="SearchResultGroup" *ngFor="let layer of group">
   <div class="SearchResultGroup" *ngFor="let l of layer.items"></div>
</div>
</code>```

How to improve performance of rendering?

答:
You can take control of when change detection occurs by using ChangeDetectionStrategy.OnPush in your component.

```<code>@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent  {
  constructor(private changeDetector: ChangeDetectorRef) { }

  someMethod(): void {
    // do lots of heavy stuff

    // now trigger change detection

    this.changeDetector.detectChanges();
  }
}
</code>```

Adding changeDetection: ChangeDetectionStrategy.OnPush to the decorator indicates that you will tell Angular when to run change detection.

this.changeDetector.detectChanges() tells Angular that you are now ready for it to run change detection.

This strategy means that you can silently update your model and trigger change detection in one go.

Body:
I have service that adds each time response data to array: group: [].

Where response is object:

{"items": [{"id": 1}, {"id": 2}, {"id": 3}]}

Problem is that it is rendered so long in template and renders each time when changes comes to array group:

How to improve performance of rendering?

Body:
You can take control of when change detection occurs by using ChangeDetectionStrategy.OnPush in your component.

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent  {
  constructor(private changeDetector: ChangeDetectorRef) { }

  someMethod(): void {
    // do lots of heavy stuff

    // now trigger change detection

    this.changeDetector.detectChanges();
  }
}

Adding changeDetection: ChangeDetectionStrategy.OnPush to the decorator indicates that you will tell Angular when to run change detection.

this.changeDetector.detectChanges() tells Angular that you are now ready for it to run change detection.

This strategy means that you can silently update your model and trigger change detection in one go.


问:
why is the address of a c++ function always True?
well why would,

```<code>#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}
</code>```

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

答:
There's no overload of operator<< for function pointers (except stream manipulators), but there is one for bool, so the function pointer is converted to that type before display.

The addresses aren't equal, but they're both non-null, and hence they both covert to true.

Body:
well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?


问:
How to get currently visible index in RN flat list
I have a horizontal flat list where each item is width:300
All I am trying to do is to get index of currently visible item.

```<code><FlatList
            onScroll={(e) => this.handleScroll(e)}
            horizontal={true}
            data={this.state.data}
            renderItem...
</code>```

Tried this:

```<code>handleScroll(event) {
    let index = Math.ceil(
      event.nativeEvent.contentOffset.x / 300
    );
</code>```

And something like this:

```<code>handleScroll(event) {
  let contentOffset = event.nativeEvent.contentOffset;
  let index = Math.floor(contentOffset.x / 300);
</code>```

but nothing is accurate I always get one index up or one index down.

What am I doing wrong and how to get correct current index in flat list?

For example I get to list item that is 8th in a list but I get index 9 or 10.

答:
In your case, I guess, you might ignore the padding or margin of items. The contentOffsetX or contentOffsetY should be firstViewableItemIndex * (itemWidth + item padding or margin).

As other answers, onViewableItemsChanged would be a better choice to meet your requirement. I wrote an article about how to use it and how it is implemented.
https://suelan.github.io/2020/01/21/onViewableItemsChanged/

Body:
I have a horizontal flat list where each item is width:300
All I am trying to do is to get index of currently visible item.

<FlatList
            onScroll={(e) => this.handleScroll(e)}
            horizontal={true}
            data={this.state.data}
            renderItem...

Tried this:

handleScroll(event) {
    let index = Math.ceil(
      event.nativeEvent.contentOffset.x / 300
    );

And something like this:

handleScroll(event) {
  let contentOffset = event.nativeEvent.contentOffset;
  let index = Math.floor(contentOffset.x / 300);

but nothing is accurate I always get one index up or one index down.

What am I doing wrong and how to get correct current index in flat list?

For example I get to list item that is 8th in a list but I get index 9 or 10.


问:
Problem with sqlite3 and linking in makefile
I have a project in which I use sqlite3 library in order to create a database. The files are as follows:

```<code>| sqlite3
    | shell.c
    | sqlite3.c
    | sqlite3.h
    | sqlite3ext.h
| database.hpp
| database.cpp
| main.cpp
| makefile
</code>```

And in database.hpp file I do #include "sqlite3/sqlite3.h".

Here is the make file that I wrote for this project:

```<code>FLAGS = -g

LIBS = -lsqlite3

CC = g++
executable = a.out

all: $(executable)

$(executable): database.o main.cpp
    $(CC) $(FLAGS) $(LIBS) database.o main.cpp -o $(executable)

database.o: database.cpp
    $(CC) $(FLAGS) $(LIBS) -c database.cpp -o database.o

.PHONY : clean

clean:
    rm $(executable) *.o
</code>```

The problem is that this makefile works just fine in my linux manjaro computer but when I run it in another computer that uses ubuntu, the make sends me errors like undefined refrence or sometimes in another machin with ubuntu it sends me can't find -lsqlite3.

What am I doing wrong here?

Thank you in advanced for your answer

答:
You're using the system SQLite libraries instead of the ones you shipped.
The simplest solution is to define a new rule for sqlite3.o and depend on it in your executable:

```<code>CFLAGS = -g
CXXFLAGS += $(CFLAGS)
LDFLAGS = -g
# SQLite needs these libraries.
LIBS = -lpthread -ldl
# see https://sqlite.org/howtocompile.html. I added one option to show how it's done
SQLITE3_OPTIONS = -DSQLITE_ENABLE_JSON1

executable = a.out

all: $(executable)

$(executable): database.o sqlite3.o main.o
    $(CXX) $(LDFLAGS) $(LIBS) $^ -o $@

# No rule is necessary for main.o or database.o, these are covered by
# Make's built-in rules

sqlite3.o: sqlite3/sqlite3.c sqlite3/sqlite3.h
    $(CC) $(CFLAGS) -Isqlite3 $(SQLITE3_OPTIONS) -c -o $@ $<

.PHONY : clean

clean:
    rm $(executable) *.o
</code>```

Body:
I have a project in which I use sqlite3 library in order to create a database. The files are as follows:

| sqlite3
    | shell.c
    | sqlite3.c
    | sqlite3.h
    | sqlite3ext.h
| database.hpp
| database.cpp
| main.cpp
| makefile

And in database.hpp file I do #include "sqlite3/sqlite3.h".

Here is the make file that I wrote for this project:

FLAGS = -g

LIBS = -lsqlite3

CC = g++
executable = a.out

all: $(executable)

$(executable): database.o main.cpp
    $(CC) $(FLAGS) $(LIBS) database.o main.cpp -o $(executable)

database.o: database.cpp
    $(CC) $(FLAGS) $(LIBS) -c database.cpp -o database.o

.PHONY : clean

clean:
    rm $(executable) *.o

The problem is that this makefile works just fine in my linux manjaro computer but when I run it in another computer that uses ubuntu, the make sends me errors like undefined refrence or sometimes in another machin with ubuntu it sends me can't find -lsqlite3.

What am I doing wrong here?

Thank you in advanced for your answer

Body:
You're using the system SQLite libraries instead of the ones you shipped.
The simplest solution is to define a new rule for sqlite3.o and depend on it in your executable:

CFLAGS = -g
CXXFLAGS += $(CFLAGS)
LDFLAGS = -g
# SQLite needs these libraries.
LIBS = -lpthread -ldl
# see https://sqlite.org/howtocompile.html. I added one option to show how it's done
SQLITE3_OPTIONS = -DSQLITE_ENABLE_JSON1

executable = a.out

all: $(executable)

$(executable): database.o sqlite3.o main.o
    $(CXX) $(LDFLAGS) $(LIBS) $^ -o $@

# No rule is necessary for main.o or database.o, these are covered by
# Make's built-in rules

sqlite3.o: sqlite3/sqlite3.c sqlite3/sqlite3.h
    $(CC) $(CFLAGS) -Isqlite3 $(SQLITE3_OPTIONS) -c -o $@ $<

.PHONY : clean

clean:
    rm $(executable) *.o


问:
Dividing within a column based on values of other columns in SQL Server
Having some trouble solving this.

```<code>store key  promotion key  sales year  average weekly sales          *Desired Output Column*
1               1           2007             100                        1 (100 / by itself)
1               1           2008             120                        1 (120 / by itself)
1               2           2008             240                        2 (240 / 120)
1               3           2007              50                        0.5 (50 / 100)
1               4           2007              70                        0.7 (70 / 100)
1               5           2007              80                        0.8 (80 / 100)
1               3           2008              180                       1.5 (180 / 120)
2               1           2009              150                       1 (150 / by itself)
2               2           2009              200                       1.3 (200 / 150)
2               3           2007              300                       Null (no baseline value in 2007)
</code>```

Each store key and sales year has a baseline value indicated by promotion key 1. All other promotion keys reflect entries I want divided into the baseline value for the same store key and sales year.

So in the above example, I want all entries with store key 1 and year 2007 divided by the baseline value for that year and store (i.e., promotion key 1 for the same store key of 1 and sales year of 2007). Similarly, all entries with store key 1 and year 2008 divided by the baseline value for that year (promotion key 1 for store 1 and sales year 2008). Likewise for store 2, I want store key 2 and year 2009 for promotion key 2 divided by the baseline value (promotion key 1, store key 2, and year 2009). As there is no baseline value (promotion key 1) for store key 2 in 2007, that entry will produce a null.

答:
This is a very similar idea to Gordon's, but I used FIRST_VALUE:

```<code>WITH YourTable AS(
    SELECT V.StoreKey,
           V.PromotionKey,
           V.SalesYear,
           V.AvgSales
    FROM (VALUES(1,1,2007,100),
                (1,1,2008,120),
                (1,2,2008,240),
                (1,3,2007,50),
                (1,4,2007,70),
                (1,5,2007,80),
                (1,3,2008,180),
                (2,1,2009,150),
                (2,2,2009,200),
                (2,3,2007,300))V(StoreKey,PromotionKey,SalesYear,AvgSales))
SELECT YT.StoreKey,
       YT.PromotionKey,
       YT.SalesYear,
       YT.AvgSales,
       (YT.AvgSales * 1.) / FIRST_VALUE(CASE YT.PromotionKey WHEN 1 THEN YT.AvgSales END) OVER (PARTITION BY YT.StoreKey, YT.SalesYear ORDER BY YT.PromotionKey) AS DesiredColumn
FROM YourTable YT
ORDER BY YT.StoreKey,
         YT.PromotionKey,
         YT.SalesYear;
</code>```

Body:
Having some trouble solving this.

store key  promotion key  sales year  average weekly sales          *Desired Output Column*
1               1           2007             100                        1 (100 / by itself)
1               1           2008             120                        1 (120 / by itself)
1               2           2008             240                        2 (240 / 120)
1               3           2007              50                        0.5 (50 / 100)
1               4           2007              70                        0.7 (70 / 100)
1               5           2007              80                        0.8 (80 / 100)
1               3           2008              180                       1.5 (180 / 120)
2               1           2009              150                       1 (150 / by itself)
2               2           2009              200                       1.3 (200 / 150)
2               3           2007              300                       Null (no baseline value in 2007)

Each store key and sales year has a baseline value indicated by promotion key 1. All other promotion keys reflect entries I want divided into the baseline value for the same store key and sales year.

So in the above example, I want all entries with store key 1 and year 2007 divided by the baseline value for that year and store (i.e., promotion key 1 for the same store key of 1 and sales year of 2007). Similarly, all entries with store key 1 and year 2008 divided by the baseline value for that year (promotion key 1 for store 1 and sales year 2008). Likewise for store 2, I want store key 2 and year 2009 for promotion key 2 divided by the baseline value (promotion key 1, store key 2, and year 2009). As there is no baseline value (promotion key 1) for store key 2 in 2007, that entry will produce a null.

Body:
This is a very similar idea to Gordon's, but I used FIRST_VALUE:

WITH YourTable AS(
    SELECT V.StoreKey,
           V.PromotionKey,
           V.SalesYear,
           V.AvgSales
    FROM (VALUES(1,1,2007,100),
                (1,1,2008,120),
                (1,2,2008,240),
                (1,3,2007,50),
                (1,4,2007,70),
                (1,5,2007,80),
                (1,3,2008,180),
                (2,1,2009,150),
                (2,2,2009,200),
                (2,3,2007,300))V(StoreKey,PromotionKey,SalesYear,AvgSales))
SELECT YT.StoreKey,
       YT.PromotionKey,
       YT.SalesYear,
       YT.AvgSales,
       (YT.AvgSales * 1.) / FIRST_VALUE(CASE YT.PromotionKey WHEN 1 THEN YT.AvgSales END) OVER (PARTITION BY YT.StoreKey, YT.SalesYear ORDER BY YT.PromotionKey) AS DesiredColumn
FROM YourTable YT
ORDER BY YT.StoreKey,
         YT.PromotionKey,
         YT.SalesYear;


问:
How does .indexOn works with users and unique keys?
I am confused with index rules in firebase. I have this database and I wanted to extract distance_traveled in battery_and_cables. The thing is, 1 is something like a userID set by the user itself so that will vary.

I used this code in pyrebase to extract the distance_traveled

```<code>db.child("mileage_maintenance").order_by_child("distance_traveled").get()
</code>```

but I get

Index not defined, add ".indexOn": "distance_traveled", for path "/mileage_maintenance", to the rules

This is my database:

Any my rules:

```<code>{
  "rules": {
    ".read": true,
    ".write": true,
    "mileage_maintenance": {
      "battery_and_cables":{
        ".indexOn": ["distance_traveled"]
       }
    },
  }
}
</code>```

Is there any way you can go through the 1 and the push key to acquire the distance_traveled?

答:
Firebase Realtime Database queries work on a flat list of the nodes under the location where you run the query. So in your case, the query considers the direct children of the mileage_maintenance node (which is just the node 1 in the screenshot).

You can have wildcards in your rules, like in your case:

```<code>{
  "rules": {
    ".read": true,
    ".write": true,
    "mileage_maintenance": {
      "$id": {
        "battery_and_cables":{
          ".indexOn": ["distance_traveled"]
         }
      }
    }
  }
}
</code>```

As you can see, I added a $id level here for the 1 node. That now means that you have an index defined on each /mileage_maintenance/$id/battery_and_cables node for the distance_traveled property of each child node under that.

So with this index, you can query a specific /mileage_maintenance/$id/battery_and_cables path for the distance_traveled values. But you can't run a query on just /mileage_maintenance for all distance_traveled values under it.

If you need such a query, you will need to modify/augment your data model to allow it. For example, by introducing a flat list of distance_traveled nodes that you can then query:

```<code>"distance_traveled": {
   "1000000": "1/battery_and_cables/-M01CT...1hMj"
}
</code>```

Or

```<code>"distance_traveled": {
   "1~battery_and_cables~-M01CT...1hMj": 1000000
}
</code>```

Where the ~ in that last model is just a separate for the segments in that key, since / isn't allowed.

Also see:

Firebase Query Double Nested

Firebase query if child of child contains a value

Body:
I am confused with index rules in firebase. I have this database and I wanted to extract distance_traveled in battery_and_cables. The thing is, 1 is something like a userID set by the user itself so that will vary.

I used this code in pyrebase to extract the distance_traveled

db.child("mileage_maintenance").order_by_child("distance_traveled").get()

but I get

Index not defined, add ".indexOn": "distance_traveled", for path "/mileage_maintenance", to the rules

This is my database:

Any my rules:

{
  "rules": {
    ".read": true,
    ".write": true,
    "mileage_maintenance": {
      "battery_and_cables":{
        ".indexOn": ["distance_traveled"]
       }
    },
  }
}

Is there any way you can go through the 1 and the push key to acquire the distance_traveled?

Body:
Firebase Realtime Database queries work on a flat list of the nodes under the location where you run the query. So in your case, the query considers the direct children of the mileage_maintenance node (which is just the node 1 in the screenshot).

You can have wildcards in your rules, like in your case:

{
  "rules": {
    ".read": true,
    ".write": true,
    "mileage_maintenance": {
      "$id": {
        "battery_and_cables":{
          ".indexOn": ["distance_traveled"]
         }
      }
    }
  }
}

As you can see, I added a $id level here for the 1 node. That now means that you have an index defined on each /mileage_maintenance/$id/battery_and_cables node for the distance_traveled property of each child node under that.

So with this index, you can query a specific /mileage_maintenance/$id/battery_and_cables path for the distance_traveled values. But you can't run a query on just /mileage_maintenance for all distance_traveled values under it.

If you need such a query, you will need to modify/augment your data model to allow it. For example, by introducing a flat list of distance_traveled nodes that you can then query:

"distance_traveled": {
   "1000000": "1/battery_and_cables/-M01CT...1hMj"
}

Or

"distance_traveled": {
   "1~battery_and_cables~-M01CT...1hMj": 1000000
}

Where the ~ in that last model is just a separate for the segments in that key, since / isn't allowed.

Also see:

Firebase Query Double Nested

Firebase query if child of child contains a value


问:
Bootstrap Carousel Jumps to top of page when advancing
When I advance the slider manually, the slider jumps to the top of the page. How can I prevent this from happening? Help much appreciated! Here's the code:</p>

```<code><div class="row">
    <div class="span12">
        <script>
            $('.carousel').carousel({
            interval: 4000
            })
        </script>
        <div class="container">
            <div id="myCarousel" class="carousel slide frame">
                <!-- Carousel items -->
                <div class="carousel-inner">
                    <div class="active item"><a href="work.html"><img src="assets/images/slide_psd.jpg" width="1170"  alt="wga"></a></div>
                    <div class="item"><a href="work.html"><img src="assets/images/slide_wga.jpg" width="1170"  alt="wga"></a></div>
                    <div class="item"><a href="work.html"><img src="assets/images/slide_ts.jpg" width="1170"  alt="top secret hair"></a></div>
                    <div class="item"><a href="work.html"><img src="assets/images/slide_baja.jpg" width="1170"  alt="baja"></a></div>
                </div>
                <!-- Carousel nav -->
                <a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
        <a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
            </div>
        </div>
        <!-- end cara container-->
    </div>
    <!-- end span-->
</div>
<!-- end row-->
</code>```

答: I ended up adding a overflow: hidden; to the carousel class which did the trick.</p>

Body:
When I advance the slider manually, the slider jumps to the top of the page. How can I prevent this from happening? Help much appreciated! Here's the code:

                ‹
        ›


问:
How to avoid refreshing of masterpage while navigating in site?
In my website, I have created a masterpage and attached all of my pages to it.
My masterpage structure contains a header and a footer. On the left it has a treeview control, which i have attached to all my pages, and on the right there is a contentplaceholder to show the content of respective pages.

My problem is that when I click any link in the treeview it refreshes the whole masterpage and open the respective page. I wish to avoid this refresh. Means it should show the contents of page on right side contentplaceholder without refreshing the whole page.

I have seen people suggesting to use iframes. But for using iframes I shall have to restructure my website. Is there any other solution than iframes and with minimal changes to the work that I have done?

答:
You will probably want to look at using AJAX to stop this from happening.  You will want to read up on using an UpdatePanel.  Below are some good articles that goes over this:

http://geekswithblogs.net/ranganh/archive/2007/05/11/112405.aspx

http://msdn.microsoft.com/en-us/library/bb399001.aspx

You also have the option of using jQuery to handle your AJAX calls.  While I typically prefer the use of jQuery when using AJAX, I am not sure I would use it in your situation.  If you would like to look at what it offers take a look at these links:

http://api.jquery.com/jQuery.ajax/

http://sixrevisions.com/javascript/the-power-of-jquery-with-ajax/