问:
How to trace T-SQL function calls
I'm trying to debug a rather complicated formula evaluator written in T-SQL UDFs (don't ask) that recursively (but indirectly through an intermediate function) calls itself, blah, blah.

And, of course, we have a bug.

Now, using PRINT statements (that can then be read from ADO.NET by implementing a handler for the InfoMessage event), I can simulate a trace for stored procedures.

Doing the same for UDF results in a compile time message:

```<code>Invalid use of side-effecting or time-dependent operator in 'PRINT' within a function.
</code>```

I get the message (PRINT does some stuff like resetting @@ROWCOUNT which definitly is a no-no in UDFs, but how can I trace through the calls? I want to have this trace printed out, so I can study it without getting distracted by stepping through the calls in the debugger...

EDIT: I have tried to use the SQL Profiler (this was a first time one for me), but I can't figure out what to trace for: Although I can get the trace to output the queries sent to the database, they are opaque in the sense that I can't drill down to the Expression-UDFs called: I can trace the actual Stored Procedure invoked, but the UDFs called by this procedure are not listed. Am I missing something? I guess not...

EDIT #2: Allthough the (auto-)accepted answer does trace the function calls - very helpful, thanks - it does not help in finding out what parameters were passed to the function. This, of course, is essential in debugging recursive functions. I will post if I find any sollution at all...

答:
I use SQL SPY which does what you are looking for and more.

SQL SPY

SQL SPY Feature Documentation

SQL SPY's Incoming SQL Sniffer shows the incoming SQL code of each connection (Includes DDL and DML statement tracking)

This feature is designed for MS SQL Server 2005\2008, but will work with MS SQL Server 2000 in limited scope. It has the ability to record and report on Incoming SQL. How to use the features: See

Disclosure: I am part of the SQL SPY team.

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

Title: How to trace T-SQL function calls

Body:
I'm trying to debug a rather complicated formula evaluator written in T-SQL UDFs (don't ask) that recursively (but indirectly through an intermediate function) calls itself, blah, blah.

And, of course, we have a bug.

Now, using PRINT statements (that can then be read from ADO.NET by implementing a handler for the InfoMessage event), I can simulate a trace for stored procedures.

Doing the same for UDF results in a compile time message:

Invalid use of side-effecting or time-dependent operator in 'PRINT' within a function.

I get the message (PRINT does some stuff like resetting @@ROWCOUNT which definitly is a no-no in UDFs, but how can I trace through the calls? I want to have this trace printed out, so I can study it without getting distracted by stepping through the calls in the debugger...

EDIT: I have tried to use the SQL Profiler (this was a first time one for me), but I can't figure out what to trace for: Although I can get the trace to output the queries sent to the database, they are opaque in the sense that I can't drill down to the Expression-UDFs called: I can trace the actual Stored Procedure invoked, but the UDFs called by this procedure are not listed. Am I missing something? I guess not...

EDIT #2: Allthough the (auto-)accepted answer does trace the function calls - very helpful, thanks - it does not help in finding out what parameters were passed to the function. This, of course, is essential in debugging recursive functions. I will post if I find any sollution at all...

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: NTulip


来源: stackexchange

问:
Which OpenGL version is most stable and currently used?
I've been thinking of making an additional wrapper for my project to use OpenGL rather then Allegro. I was not sure which OpenGL version to go for since I know that some computers cannot run recent versions such as v4.4. Also, I need a version which compiles no problem in Linux, Windows, Mac.</p>

答:
OpenGL is not a library you usually compile and ship yourself (unless you're a Linux distributor and are packaging X.Org/Mesa). Your program just dynamically links against libGL.so (Linux/BSD), opengl32.dll (Windows, on 64 Bit systems, it's also calles opengl32.dll, but it's in fact a 64 Bit DLL) or the OpenGL Framework (MacOS X). This gives your program access to the system's OpenGL installation. The version/profile you want to use has no influence on the library you link!

Then after your program has been initialized you can test, which OpenGL version is available. If you want to use OpenGL-3 or 4 you'll have to jump a few additional hoops in Windows to make full use of it, but normally some kind of wrapper helps you with context creation anyway, boiling it down to only a few lines.

Then in the program you can implement multiple code paths for the various versions. Usually lower OpenGL verion codepaths share a large subset with higher version codepaths. I recommend writing new code in the highest version available, then adding additional code paths (oftenly just substitutions which can be done by C preprocessor macros or similar) for lower versions until you reach the lowest common denominator of features you really need.

ContentLicense: CC BY-SA 3.0


问:
Returning a week number for any given date and starting from a custom date
well, I'm trying to create a function that return week number, but not like date part that return it for the normal year (01-jannuary - 31 december) i want to retutn it using a custom year (01 september- 31 august of the next year )
also I have some rules like:

first of september is alwayse in week number 1.
-sunday is the last day of the week.

if sunday is the first day of september, then the first week ends until the next sunday.

I expect to get results using code like

```<code>select week_number('01/09/2019')
</code>```

Results : 1

```<code>select week_number('04/09/2017')
</code>```

Results : 2

答:
Try the following:

Number of the week in the month:

```<code>declare @date datetime = '01/09/2017'

select (DATEPART(week,@Date)- DATEPART(week,DATEADD(m, DATEDIFF(m, 0, @Date), 0)))
</code>```

Number of the week in the year:

```<code>declare @date datetime = '01/09/2017'

SELECT DATEPART(wk,@Date)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
well, I'm trying to create a function that return week number, but not like date part that return it for the normal year (01-jannuary - 31 december) i want to retutn it using a custom year (01 september- 31 august of the next year )
also I have some rules like:

first of september is alwayse in week number 1.
-sunday is the last day of the week.

if sunday is the first day of september, then the first week ends until the next sunday.

I expect to get results using code like

select week_number('01/09/2019')

Results : 1

select week_number('04/09/2017')

Results : 2

Body:
Try the following:

Number of the week in the month:

declare @date datetime = '01/09/2017'

select (DATEPART(week,@Date)- DATEPART(week,DATEADD(m, DATEDIFF(m, 0, @Date), 0)))

Number of the week in the year:

declare @date datetime = '01/09/2017'

SELECT DATEPART(wk,@Date)


问:
Can alloca() memory be reallocated?
Memory allocated by malloc can be reallocated with realloc. Is there a similar function for alloca? Reallocating stack memory could be useful when you don't want memory to be allocated on the heap, and you need to allocate variable stack memory multiple times, for example in a library function, where you need dynamic memory, but don't want to allocate on the heap, because the user of the library might use a custom heap allocation strategy. It would look like this:

```<code>int main(void) {
    float * some_mem = alloca(40 * sizeof(float));
    // do something with this memory...

    // now we need a different amount of memory, but some_mem still occupies a lot of the stack, so just reallocate it.

    // is something like this possible?
    some_mem = realloca(some_mem, 50 * sizeof(float));
}
</code>```

The important thing is that this all happens on the stack. Q: is there a way to reallocate dynamic stack memory?

答:
No: that wouldn't work with a stack as commonly implemented. A variable on the stack occupies a fixed range of addresses. The next variable comes immediately after it, so there's no room to grow. Consider a function like this:

void f(int x) {
    int i;
    float *a = alloca(40 * sizeof(float));
    int k;
    …
}
```
<p>The stack after the function prologue looks something like this:</p>
<pre class="lang-none prettyprint-override"><code>----------------+-----+-----+-----+-----+-------------------+-----+---------------------
...             | ret | x   | i   | a   | a[]               | k   | ...
----------------+-----+-----+-----+-----+-------------------+-----+---------------------
^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
previous frames                       f's frame                    free space at the top
</code>```

There's no room to grow a.

I'm showing a highly simplified example: in the real world, variables end up in registers, variables can be reordered even if they do end up on the stack, etc. But only one variable can be the last one on the stack with room to grow.

So if realloca existed, it could only be applied to the variable that's at the top of the stack. (Or else it would have to move everything else that's on top of it, but that would require updating all existing pointers to those, which is not possible in general.) This would be a very limited mechanism, so support for this feature would have a very small benefit. Supporting it would have a significant cost, because compilers are normally free to put things on the stack in the order they want: this feature would require a new mechanism to let the compiler know that one specific variable must go to the top.

It's possible that some C implementation somewhere has realloca, but it's unlikely given the cost/benefit ratio.

Of course realloca can easily be implemented if alloca does not use a stack allocation strategy. But allocating on the stack is the whole point of alloca. If you want resizable objects, you need a memory management structure with a heap interface, and that's what malloc is for.

As a practical matter, there are several possible approaches to dynamic memory management in a library.

The most common approach is to call malloc, realloc and free when you need them. That's what they're for.

In some environments, it's useful to support custom allocators. You can give the user of the library the option to pass pointers to alternative implementations of malloc, realloc and free. It's useful when you want to write a portable library that needs to be used by code that is itself fully portable. Most of the time, though, users who want to use custom allocators can do it by linking their own malloc and friends. And even that is rarely useful.

If you need code that can work in an environment without dynamic allocation (such as safety-critical environments), then you should not use alloca either. alloca is worse than malloc because it causes unpredictable stack usage and can lead to a stack overflow which won't be detected at all, or which will only be detected by a program crash. If you need a variable (or large) amount of temporary memory in a function, have the user pass a suitably-sized buffer to you.

/** [documentation of the function] …
 * working_buffer must point to an array of floats of 3*n elements.
 */
void f(size_t n, float *working_buffer);
```
<p>Better, if you have the code size budget, pass the array size and verify it.</p>
<pre class="lang-c prettyprint-override"><code>/** [documentation of the function] …
 * working_buffer must point to an array of floats of 3*n elements.
 */
int f(size_t n, float *working_buffer, size_t working_buffer_length)
{
    if (working_buffer_length < 3 * n) return -EINVAL;
    …
}
</code>```

Title: Can alloca() memory be reallocated?

Body:
Memory allocated by malloc can be reallocated with realloc. Is there a similar function for alloca? Reallocating stack memory could be useful when you don't want memory to be allocated on the heap, and you need to allocate variable stack memory multiple times, for example in a library function, where you need dynamic memory, but don't want to allocate on the heap, because the user of the library might use a custom heap allocation strategy. It would look like this:

int main(void) {
    float * some_mem = alloca(40 * sizeof(float));
    // do something with this memory...

    // now we need a different amount of memory, but some_mem still occupies a lot of the stack, so just reallocate it.

    // is something like this possible?
    some_mem = realloca(some_mem, 50 * sizeof(float));
}

The important thing is that this all happens on the stack. Q: is there a way to reallocate dynamic stack memory?

Body:
No: that wouldn't work with a stack as commonly implemented. A variable on the stack occupies a fixed range of addresses. The next variable comes immediately after it, so there's no room to grow. Consider a function like this:

void f(int x) {
    int i;
    float *a = alloca(40 * sizeof(float));
    int k;
    …
}

The stack after the function prologue looks something like this:

----------------+-----+-----+-----+-----+-------------------+-----+---------------------
...             | ret | x   | i   | a   | a[]               | k   | ...
----------------+-----+-----+-----+-----+-------------------+-----+---------------------
^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
previous frames                       f's frame                    free space at the top

There's no room to grow a.

I'm showing a highly simplified example: in the real world, variables end up in registers, variables can be reordered even if they do end up on the stack, etc. But only one variable can be the last one on the stack with room to grow.

So if realloca existed, it could only be applied to the variable that's at the top of the stack. (Or else it would have to move everything else that's on top of it, but that would require updating all existing pointers to those, which is not possible in general.) This would be a very limited mechanism, so support for this feature would have a very small benefit. Supporting it would have a significant cost, because compilers are normally free to put things on the stack in the order they want: this feature would require a new mechanism to let the compiler know that one specific variable must go to the top.

It's possible that some C implementation somewhere has realloca, but it's unlikely given the cost/benefit ratio.

Of course realloca can easily be implemented if alloca does not use a stack allocation strategy. But allocating on the stack is the whole point of alloca. If you want resizable objects, you need a memory management structure with a heap interface, and that's what malloc is for.

As a practical matter, there are several possible approaches to dynamic memory management in a library.

The most common approach is to call malloc, realloc and free when you need them. That's what they're for.

In some environments, it's useful to support custom allocators. You can give the user of the library the option to pass pointers to alternative implementations of malloc, realloc and free. It's useful when you want to write a portable library that needs to be used by code that is itself fully portable. Most of the time, though, users who want to use custom allocators can do it by linking their own malloc and friends. And even that is rarely useful.

If you need code that can work in an environment without dynamic allocation (such as safety-critical environments), then you should not use alloca either. alloca is worse than malloc because it causes unpredictable stack usage and can lead to a stack overflow which won't be detected at all, or which will only be detected by a program crash. If you need a variable (or large) amount of temporary memory in a function, have the user pass a suitably-sized buffer to you.

/** [documentation of the function] …
 * working_buffer must point to an array of floats of 3*n elements.
 */
void f(size_t n, float *working_buffer);

Better, if you have the code size budget, pass the array size and verify it.

/** [documentation of the function] …
 * working_buffer must point to an array of floats of 3*n elements.
 */
int f(size_t n, float *working_buffer, size_t working_buffer_length)
{
    if (working_buffer_length < 3 * n) return -EINVAL;
    …
}


问:
am getting undefined while trying execute following code
TypeError: Cannot read property 'bind' of undefined

getting this error, please help me.

Am trying to check and uncheck the checkbox when onchange event occures

please find the code here
https://codesandbox.io/s/competent-mendeleev-cd881

答:
Typo in ToDoItems.js - props.handlehange

You need to assign this to a variable because of different context in map
function

Pass item.id in handleChange() function to keep track of your todo item.

Here is updated solution.


问:
facebook iframe app authentication flow question
I'm not quite sure if I'm doing the auth correctly, so I'm asking here to verify my process.

Check if user is authenticated, if not proceed to next step.

Redirect the user to: https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL

On the redirect, I take the $_REQUEST['code'] and I re-issue it to https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE to get access token.

I get the access token, save it to my session, user is now authenticated and I redirect them back to my application's landing page.

Everything works fine but it seems it's just my app has all these too many redirects happening. Other apps seem to just take you straight to their app without going through step 1 (those that already added the app).

I'm wondering if others are using the "offline_access" permission and using this as a way to bypass getting the "code" to get the "access_token" routine.

答: Correct. With offline_access, you can save the access_token indefinitely and avoid having to go through that flow again. If you try to use it and get an OAuthException, you should discard of the saved access token. This is how many applications skip those authentication steps for account verification. One major down side to requesting offline_access is that it may look bad to a user.


问:
TypeError: ApplicationServiceMock.application$.pipe is not a function
I'm trying to unittest a Angular 7 component which has this in the constructor

```<code>constructor(private store: ApplicationService) {
        this.store.application$.pipe(first()).subscribe(r => { this.application = r; });
    }
</code>```

Now when I try to test I get the error

```<code>TypeError: ApplicationServiceMock.application$.pipe is not a function
</code>```

This is how I try to test

```<code>const ApplicationServiceMock= mock(ApplicationService);
</code>```

.....

```<code>when(ApplicationServiceMock.application$.pipe()).thenResolve(Observable.of(Applications.ApplicationServiceDummy));
</code>```

.....

```<code>providers: [
                    { provide: ApplicationService, useFactory: () => ApplicationServiceMock}
                ],
</code>```

I also tryed to use jasmine.spy, but even this is not working and throwing the exact same error. What am I doing wrong or missing here?

答:
I don't know what mock does. But I would assume it only creates an empty wrapper for your ApplicationService. You need to tell your spy or mock, that is does have a property called application$ which returns any observable.

So you would need something like this:

```<code>const applicationServiceMock = {
  application$: () => EMPTY
}

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AppComponent],
            providers: [{provide: ApplicationService, useValue: applicationServiceMock}],
            schemas: [NO_ERRORS_SCHEMA]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
    });

    it('should be created', () => {
      fixture.detectChanges();
      expect(component).toBeTruthy();
    });
});
</code>```

Since you are accessing the observable inside the component's constructor you need to define the expected Observable either with EMPTY like I did or with of(YOUR_TEST_VALUE_HERE) inside the mock-property beforehand because the constructor gets called before you can intervene inside the  it block.

If you like to use spyOn you would need to move the subscription code from the component's constructor to the ngOnInit lifecycle hook. Then you can alter the stub and spyOn before you call the first fixture.detectChanges() inside your test.

Body:
I'm trying to unittest a Angular 7 component which has this in the constructor

constructor(private store: ApplicationService) {
        this.store.application$.pipe(first()).subscribe(r => { this.application = r; });
    }

Now when I try to test I get the error

TypeError: ApplicationServiceMock.application$.pipe is not a function

This is how I try to test

const ApplicationServiceMock= mock(ApplicationService);

.....

when(ApplicationServiceMock.application$.pipe()).thenResolve(Observable.of(Applications.ApplicationServiceDummy));

.....

providers: [
                    { provide: ApplicationService, useFactory: () => ApplicationServiceMock}
                ],

I also tryed to use jasmine.spy, but even this is not working and throwing the exact same error. What am I doing wrong or missing here?

Body:
I don't know what mock does. But I would assume it only creates an empty wrapper for your ApplicationService. You need to tell your spy or mock, that is does have a property called application$ which returns any observable.

So you would need something like this:

const applicationServiceMock = {
  application$: () => EMPTY
}

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AppComponent],
            providers: [{provide: ApplicationService, useValue: applicationServiceMock}],
            schemas: [NO_ERRORS_SCHEMA]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
    });

    it('should be created', () => {
      fixture.detectChanges();
      expect(component).toBeTruthy();
    });
});

Since you are accessing the observable inside the component's constructor you need to define the expected Observable either with EMPTY like I did or with of(YOUR_TEST_VALUE_HERE) inside the mock-property beforehand because the constructor gets called before you can intervene inside the  it block.

If you like to use spyOn you would need to move the subscription code from the component's constructor to the ngOnInit lifecycle hook. Then you can alter the stub and spyOn before you call the first fixture.detectChanges() inside your test.


问:
Trouble running startup scripts for containers
I am trying to start three docker containers using docker-compose; a postgresql database, a rest api and a frontend web app.

Previously I had the rest api and the database working perfectly (ran migrations and started the server) but when I wanted to send requests to it from my web app I had trouble connecting to the docker network. All the discussion on the internet was centered around connecting a web app in a container to an api in another container and I didn't find any promising method to connect to it (besides enabling port forwarding in the kernel and exposing myself to the network?) so I just decided to package the web app in a container as well.

My directory structure:

```<code>ProjectName
|-> projectapi
|-> |-> api.docker
|-> |-> api_start.sh
|-> projectapp
|-> |-> front.docker
|-> |-> front_start.sh
|-> docker-compose.yml
</code>```

The problem is running these startup scripts in the right context (tbh I only need to run a npm start and a python manage.py runserver).

I can't think of anything I haven't tried, but most of my efforts have been centered around mucking around with paths because for the longest time the issue was not finding the file which I think I have fixed.

This is the docker-compose file, I have tried having all sorts of command entries in here to run the desired startup script. I have also used entrypoint.

```<code>version: '3.7'

services:
  db:
    container_name: projectdb
    image: postgres:9.6-alpine
    restart: always
    volumes:
      - projectdb:/var/lib/postgresql/data/
    environment:
      POSTGRES_DB: projectdb
      POSTGRES_PASSWORD: root
    ports:
      - "8001:5432"

  api:
    container_name: projectapi
    build:
      context: projectapi/
      dockerfile: api.docker
    ports:
      - "8000:8000"
    expose:
      - "8000"
    depends_on:
      - db
    restart: always
    environment:
      POSTGRES_DB: 'projectdb'
      POSTGRES_USER: 'postgres'
      POSTGRES_PASSWORD: 'root'
      POSTGRES_HOST: 'db'

  front:
    container_name: projectapp
    build:
      context: projectapp/
      dockerfile: front.docker
    ports:
      - "3000:3000"
    restart:
      always

volumes:
  projectdb:
</code>```

Then there are the Dockerfiles:

front

```<code>FROM node:8
RUN mkdir /projectapp
COPY $HOSTDIR/package*.json /projectapp/
RUN npm install /projectapp
COPY $HOSTDIR/* /projectapp/
ENTRYPOINT ["npm", "start", "/projectapp"]
</code>```

back

```<code>FROM python:3.6-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONBUFFERED 1

RUN mkdir /projectapi
COPY $HOSTDIR/requirements.txt /projectapi/
RUN pip install -r /projectapi/requirements.txt
COPY $HOSTDIR/* /projectapi/
CMD ["python", "manage.py", "migrate"]
</code>```

That last line could be runserver as well. These are just some examples of the permutations I've gone through but at this point I feel the problem is some conceptual misunderstanding, I've read the docs.

The error messages are all different permutations of not finding the startup script. I think there was a point where I managed to run a startup script and the error became it couldn't find manage.py, at which point I started to look into how to write the script better than just: python manage.py runserver but didn't get very far.

答:
Try using a WORKDIR. Your current run path doesn't have manage.py  -

I tried changing it momentarily -

```<code>WORKDIR /projectapi
COPY requirements.txt ./
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver"]
</code>```

Body:
I am trying to start three docker containers using docker-compose; a postgresql database, a rest api and a frontend web app.

Previously I had the rest api and the database working perfectly (ran migrations and started the server) but when I wanted to send requests to it from my web app I had trouble connecting to the docker network. All the discussion on the internet was centered around connecting a web app in a container to an api in another container and I didn't find any promising method to connect to it (besides enabling port forwarding in the kernel and exposing myself to the network?) so I just decided to package the web app in a container as well.

My directory structure:

ProjectName
|-> projectapi
|-> |-> api.docker
|-> |-> api_start.sh
|-> projectapp
|-> |-> front.docker
|-> |-> front_start.sh
|-> docker-compose.yml

The problem is running these startup scripts in the right context (tbh I only need to run a npm start and a python manage.py runserver).

I can't think of anything I haven't tried, but most of my efforts have been centered around mucking around with paths because for the longest time the issue was not finding the file which I think I have fixed.

This is the docker-compose file, I have tried having all sorts of command entries in here to run the desired startup script. I have also used entrypoint.

version: '3.7'

services:
  db:
    container_name: projectdb
    image: postgres:9.6-alpine
    restart: always
    volumes:
      - projectdb:/var/lib/postgresql/data/
    environment:
      POSTGRES_DB: projectdb
      POSTGRES_PASSWORD: root
    ports:
      - "8001:5432"

  api:
    container_name: projectapi
    build:
      context: projectapi/
      dockerfile: api.docker
    ports:
      - "8000:8000"
    expose:
      - "8000"
    depends_on:
      - db
    restart: always
    environment:
      POSTGRES_DB: 'projectdb'
      POSTGRES_USER: 'postgres'
      POSTGRES_PASSWORD: 'root'
      POSTGRES_HOST: 'db'

  front:
    container_name: projectapp
    build:
      context: projectapp/
      dockerfile: front.docker
    ports:
      - "3000:3000"
    restart:
      always

volumes:
  projectdb:

Then there are the Dockerfiles:

front

FROM node:8
RUN mkdir /projectapp
COPY $HOSTDIR/package*.json /projectapp/
RUN npm install /projectapp
COPY $HOSTDIR/* /projectapp/
ENTRYPOINT ["npm", "start", "/projectapp"]

back

FROM python:3.6-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONBUFFERED 1

RUN mkdir /projectapi
COPY $HOSTDIR/requirements.txt /projectapi/
RUN pip install -r /projectapi/requirements.txt
COPY $HOSTDIR/* /projectapi/
CMD ["python", "manage.py", "migrate"]

That last line could be runserver as well. These are just some examples of the permutations I've gone through but at this point I feel the problem is some conceptual misunderstanding, I've read the docs.

The error messages are all different permutations of not finding the startup script. I think there was a point where I managed to run a startup script and the error became it couldn't find manage.py, at which point I started to look into how to write the script better than just: python manage.py runserver but didn't get very far.

Body:
Try using a WORKDIR. Your current run path doesn't have manage.py  -

I tried changing it momentarily -

WORKDIR /projectapi
COPY requirements.txt ./
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver"]


问:
How to use variable range in Google Sheets?
Currently I have such formula:
COUNTIFS(B3:B36,"16",E3:E36,"01")

Would it be possible to turn these ranges B3:B36 and E3:E36 into variables, like B'start_cell_value':B'stop_cell_value'.

The whole thing would look like:

```<code> =COUNTIFS(B'start_cell_value':B'stop_cell_value',"16",E'start_cell_value':E'stop_cell_value',"01")
</code>```

start_cell_value and stop_cell_value are just some numbers stored in a separate cell. This would help, since changing numbers in those cells only would also change everything in the formula and that's exactly what I want.

I have tried to combine a numeric value from other cells with a letter to make a valid cell name but it doesn't seem to work or it just throws a reference error.

Any ideas would be appreciated.

答:
If you have the start_cell_value in cell A1 and the stop_cell_value in A2 then try this formula:

=COUNTIFS(INDIRECT("B"&A1&":B"&A2),"16",INDIRECT("E"&A1&":E"&A2),"01")

Body:
Currently I have such formula:
COUNTIFS(B3:B36,"16",E3:E36,"01")

Would it be possible to turn these ranges B3:B36 and E3:E36 into variables, like B'start_cell_value':B'stop_cell_value'.

The whole thing would look like:

 =COUNTIFS(B'start_cell_value':B'stop_cell_value',"16",E'start_cell_value':E'stop_cell_value',"01")

start_cell_value and stop_cell_value are just some numbers stored in a separate cell. This would help, since changing numbers in those cells only would also change everything in the formula and that's exactly what I want.

I have tried to combine a numeric value from other cells with a letter to make a valid cell name but it doesn't seem to work or it just throws a reference error.

Any ideas would be appreciated.


问:
How to fill periods in columns?
There is a dataframe. The period column contains lists. These lists contain time spans.

```<code>#load data
df = pd.DataFrame(data, columns=['task_id', 'target_start_date', 'target_end_date'])

df['target_start_date'] = pd.to_datetime(df.target_start_date)
df['target_end_date'] = pd.to_datetime(df.target_end_date)
df['period'] = np.nan

#create period column
z = dict()
freq = 'M'

for i in range(0, len(df)):
    l = pd.period_range(df.target_start_date[i], df.target_end_date[i], freq=freq)
    l = l.to_native_types()
    z[i] = l

df.period = z.values()
</code>```

Output

```<code>    task_id  target_start_date  target_end_date     period

0   35851   2019-04-01 07:00:00 2019-04-01 07:00:00 [2019-04]
1   35852   2020-02-26 11:30:00 2020-02-26 11:30:00 [2020-02]
2   35854   2019-05-17 07:00:00 2019-06-01 17:30:00 [2019-05, 2019-06]
3   35855   2019-03-20 11:30:00 2019-04-07 15:00:00 [2019-03, 2019-04]
4   35856   2019-04-06 08:00:00 2019-04-26 19:00:00 [2019-04]
</code>```

enter image description here

Then I add columns which are called time slices.

```<code>#create slices
date_min = df.target_start_date.min()
date_max = df.target_end_date.max()
period = pd.period_range(date_min, date_max, freq=freq)

#add columns
for i in period:
    df[str(i)] = np.nan
</code>```

result

enter image description here

How can I fill Nan values for True, if this value is in the list in the period column?

enter image description here

答:
My approach was to iterate over rows and column names and compare values:

```<code>import numpy as np
import pandas as pd

# handle assignment error
pd.options.mode.chained_assignment = None

# setup test data
data = {'time': [['2019-04'], ['2019-01'], ['2019-03'], ['2019-06', '2019-05']]}
data = pd.DataFrame(data=data)

# create periods
date_min = data.time.min()[0]
date_max = data.time.max()[0]
period = pd.period_range(date_min, date_max, freq='M')

for i in period:
    data[str(i)] = np.nan

# compare and fill data
for index, row in data.iterrows():
    for column in data:
        if data[column].name in row['time']:
            data[column][index] = 'True'
</code>```

Output:

```<code>                 time 2019-01  2019-02 2019-03 2019-04 2019-05 2019-06
0           [2019-04]     NaN      NaN     NaN    True     NaN     NaN
1           [2019-01]    True      NaN     NaN     NaN     NaN     NaN
2           [2019-03]     NaN      NaN    True     NaN     NaN     NaN
3  [2019-06, 2019-05]     NaN      NaN     NaN     NaN    True    True
</code>```

Title: How to fill periods in columns?

Body:
There is a dataframe. The period column contains lists. These lists contain time spans.

#load data
df = pd.DataFrame(data, columns=['task_id', 'target_start_date', 'target_end_date'])

df['target_start_date'] = pd.to_datetime(df.target_start_date)
df['target_end_date'] = pd.to_datetime(df.target_end_date)
df['period'] = np.nan

#create period column
z = dict()
freq = 'M'

for i in range(0, len(df)):
    l = pd.period_range(df.target_start_date[i], df.target_end_date[i], freq=freq)
    l = l.to_native_types()
    z[i] = l

df.period = z.values()

Output

    task_id  target_start_date  target_end_date     period

0   35851   2019-04-01 07:00:00 2019-04-01 07:00:00 [2019-04]
1   35852   2020-02-26 11:30:00 2020-02-26 11:30:00 [2020-02]
2   35854   2019-05-17 07:00:00 2019-06-01 17:30:00 [2019-05, 2019-06]
3   35855   2019-03-20 11:30:00 2019-04-07 15:00:00 [2019-03, 2019-04]
4   35856   2019-04-06 08:00:00 2019-04-26 19:00:00 [2019-04]

enter image description here

Then I add columns which are called time slices.

#create slices
date_min = df.target_start_date.min()
date_max = df.target_end_date.max()
period = pd.period_range(date_min, date_max, freq=freq)

#add columns
for i in period:
    df[str(i)] = np.nan

result

enter image description here

How can I fill Nan values for True, if this value is in the list in the period column?

enter image description here

Body:
My approach was to iterate over rows and column names and compare values:

import numpy as np
import pandas as pd

# handle assignment error
pd.options.mode.chained_assignment = None

# setup test data
data = {'time': [['2019-04'], ['2019-01'], ['2019-03'], ['2019-06', '2019-05']]}
data = pd.DataFrame(data=data)

# create periods
date_min = data.time.min()[0]
date_max = data.time.max()[0]
period = pd.period_range(date_min, date_max, freq='M')

for i in period:
    data[str(i)] = np.nan

# compare and fill data
for index, row in data.iterrows():
    for column in data:
        if data[column].name in row['time']:
            data[column][index] = 'True'

Output:

                 time 2019-01  2019-02 2019-03 2019-04 2019-05 2019-06
0           [2019-04]     NaN      NaN     NaN    True     NaN     NaN
1           [2019-01]    True      NaN     NaN     NaN     NaN     NaN
2           [2019-03]     NaN      NaN    True     NaN     NaN     NaN
3  [2019-06, 2019-05]     NaN      NaN     NaN     NaN    True    True


问:
How to combine specific values of two variables into a new variable (?)
I am trying to merge / combine specific values of two variables into a new variable.

The two variables to be combined:

AL.INCOME -> (dichotomous, whereas 1 indicates that an individual is in the 1st to 4th income decile (= poor) and 2 indicates that an individual is in the 7th or 10th income decile (= rich), other income deciles = NA)

AL.SKILL -> (dichotomous, whereas 1 indicates that an individual is low skilled, 2 indicates that an individual is high skilled, and else = NA)

Out of these I want to combine another dichotomous variable where 1 denotes all individuals that are poor and AT THE SAME TIME less skilled, and 2 denotes all individuals that are rich and AT THE SAME TIME high skilled, whereas all other individuals that don't fulfill both criteria are classified as NA.
The name of this new variable shall be AL.INCOME.SKILL.

Both variables refer to the same subjects (693 observations, which is the subsample "Albania" out of the ESS6 2012).

I am sorry in advance if this is a very basic question that I'm asking here and I am not using the correct terminology for certain expressions. I'm quite new to R and programming in general.

I have already tried to combine the variables with recode (from library car) and by building a data frame (that consists only of the two variables AL.INCOME & AL.SKILL)

```<code>## This is how I created AL.INCOME (dichotomous):
AlbanienVar$AL.INCOME <- recode(AlbanienVar$hinctntaAL, "1:4=1;7:10=2;else=NA")

## This is how I created AL.SKILL (dichotomous):
AlbanienVar$AL.SKILL <- recode(AlbanienVar$isco08AL, "7000:9629=1;1000:2659=2;else=NA")

##The data frame I already computed:
Trial1 <- as.data.frame(AL.INCOME, AL.SKILL)
</code>```

As a remark: AL.SKILL contains NAs, whereas AL.INCOME does not. I hope this is not an obstacle.

答:
Does this look like a solution to your problem?</p>

```<code>library(tidyverse)

df <- tibble(AL.INCOME = c(1, 2, 2), AL.SKILL = c(1, 2, NA))

df %>%
  rowwise() %>%
  mutate(new_cat = ifelse(sum(AL.INCOME, AL.SKILL) %in% c(2, 4), AL.INCOME, NA))
#> Source: local data frame [3 x 3]
#> Groups: <by row>
#>
#> # A tibble: 3 x 3
#>   AL.INCOME AL.SKILL new_cat
#>       <dbl>    <dbl>   <dbl>
#> 1         1        1       1
#> 2         2        2       2
#> 3         2       NA      NA
</code>```

Body:
I am trying to merge / combine specific values of two variables into a new variable.

The two variables to be combined:

AL.INCOME -> (dichotomous, whereas 1 indicates that an individual is in the 1st to 4th income decile (= poor) and 2 indicates that an individual is in the 7th or 10th income decile (= rich), other income deciles = NA)

AL.SKILL -> (dichotomous, whereas 1 indicates that an individual is low skilled, 2 indicates that an individual is high skilled, and else = NA)

Out of these I want to combine another dichotomous variable where 1 denotes all individuals that are poor and AT THE SAME TIME less skilled, and 2 denotes all individuals that are rich and AT THE SAME TIME high skilled, whereas all other individuals that don't fulfill both criteria are classified as NA.
The name of this new variable shall be AL.INCOME.SKILL.

Both variables refer to the same subjects (693 observations, which is the subsample "Albania" out of the ESS6 2012).

I am sorry in advance if this is a very basic question that I'm asking here and I am not using the correct terminology for certain expressions. I'm quite new to R and programming in general.

I have already tried to combine the variables with recode (from library car) and by building a data frame (that consists only of the two variables AL.INCOME & AL.SKILL)

## This is how I created AL.INCOME (dichotomous):
AlbanienVar$AL.INCOME <- recode(AlbanienVar$hinctntaAL, "1:4=1;7:10=2;else=NA")

## This is how I created AL.SKILL (dichotomous):
AlbanienVar$AL.SKILL <- recode(AlbanienVar$isco08AL, "7000:9629=1;1000:2659=2;else=NA")

##The data frame I already computed:
Trial1 <- as.data.frame(AL.INCOME, AL.SKILL)

As a remark: AL.SKILL contains NAs, whereas AL.INCOME does not. I hope this is not an obstacle.

Body:
Does this look like a solution to your problem?

library(tidyverse)

df <- tibble(AL.INCOME = c(1, 2, 2), AL.SKILL = c(1, 2, NA))

df %>%
  rowwise() %>%
  mutate(new_cat = ifelse(sum(AL.INCOME, AL.SKILL) %in% c(2, 4), AL.INCOME, NA))
#> Source: local data frame [3 x 3]
#> Groups: <by row>
#>
#> # A tibble: 3 x 3
#>   AL.INCOME AL.SKILL new_cat
#>       <dbl>    <dbl>   <dbl>
#> 1         1        1       1
#> 2         2        2       2
#> 3         2       NA      NA


问:
Can this form be filled and submitted using python's responses module?
I am writing a data scraping script. It's purpose is to collect data on available broadband deals from BT's website. I cannot figure out why my simple requests code doesn't fill in the form and follow through to the next page.

Please help me figure out how to enter data into this form and save the output html for data scraping.

I have identified the relevant tags in the form that I am interested in. I am trying to populate the UPRN field and continue to the next page

Link to website: https://www.dslchecker.bt.com/#

My python code:
'''python

```<code>import requests
url = "https://www.dslchecker.bt.com/#"
payload = {'UPRN':'10033360983'}
r = requests.post(url, data = payload)
print(r.text)
</code>```

'''

Form from the website:

'''html

```<code><form method="post" action="adsl/ADSLChecker.UPRNoutput"><input type="hidden" name="URL"> <input value="a%20service%20provider" type="hidden" name="SP_NAME">
      <span class="subheading">UPRN:</span><br><input maxlength="13" size="14" name="UPRN" autocomplete="off" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAAXNSR0IArs4c6QAAAPhJREFUOBHlU70KgzAQPlMhEvoQTg6OPoOjT+JWOnRqkUKHgqWP4OQbOPokTk6OTkVULNSLVc62oJmbIdzd95NcuGjX2/3YVI/Ts+t0WLE2ut5xsQ0O+90F6UxFjAI8qNcEGONia08e6MNONYwCS7EQAizLmtGUDEzTBNd1fxsYhjEBnHPQNG3KKTYV34F8ec/zwHEciOMYyrIE3/ehKAqIoggo9inGXKmFXwbyBkmSQJqmUNe15IRhCG3byphitm1/eUzDM4qR0TTNjEixGdAnSi3keS5vSk2UDKqqgizLqB4YzvassiKhGtZ/jDMtLOnHz7TE+yf8BaDZXA509yeBAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%; cursor: auto;"> <input value="56" type="hidden" name="VERSION"> <input value="E" type="hidden" name="MS"> <input value="no" type="hidden" name="CAP"> <input value="Y" type="hidden" name="AEA">   <input class="form_button" value="submit" type="submit"> </form>
</code>```

'''

Please follow this link :https://www.dslchecker.bt.com/# and enter 10033346575 in the UPRN field to see the desired output

My output when ran in a jupyter notebook:

'''html

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0063)http://dslcheckerait.vade.bt.com:61065/adsl/adslchecker.welcome -->
<HTML><HEAD>
<STYLE>
.body {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #004d5f; FONT-SIZE: 11px; FONT-WEIGHT: normal; TEXT-DECORATION: none
}
.bodybold {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #333333; FONT-SIZE: 11px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.errormessage {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #000000; FONT-SIZE: 11px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.formDescription {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #666666; FONT-SIZE: 9px; FONT-WEIGHT: normal; TEXT-DECORATION: none
}
.form_button {BORDER-BOTTOM: #666666 1px solid; BORDER-LEFT: #666666 1px solid; BACKGROUND-COLOR: #6400AA; FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #ffffff; FONT-SIZE: 10px; BORDER-TOP: #666666 1px solid; FONT-WEIGHT: bold; BORDER-RIGHT: #666666 1px solid; TEXT-DECORATION: none
}
.heading {FONT-VARIANT: normal; FONT-FAMILY: Arial, Helvetica, sans-serif; COLOR: #004d5f; FONT-SIZE: 14px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.heading3 {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #333333; FONT-SIZE: 10px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.heading4 {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #91b1b8; FONT-SIZE: 10px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.subheading {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Helvetica, sans-serif; COLOR: color: #333333; FONT-SIZE: 14px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
A:active {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: underline
}
A:hover {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: underline
}
A:link {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
A:visited {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: underline
}
BODY {PADDING-BOTTOM: 0px; BACKGROUND-COLOR: #ffffff; MARGIN: 10px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 0px
}

</STYLE>

<TITLE>BT Broadband</TITLE>
<META content="text/html; charset=utf-8" http-equiv=Content-Type><LINK
rel=stylesheet type=text/css
href="adslchecker_font.html">
<META content=text/css http-equiv=Content-Style-Type><META http-equiv="X-UA-Compatible" content="IE=5">
<SCRIPT>
<!--
function setFocus() {
    document.forms[0].elements[2].focus();
}
//-->
</SCRIPT>

<META name=GENERATOR content="MSHTML 8.00.7601.18751"></HEAD>
<BODY onload=setFocus()>
<TABLE width=500 align=center>
  <TBODY>
  <TR>
    <TD>
      <SCRIPT language=JavaScript>  var isNS = (navigator.appName == "Netscape") ? 1 : 0;var EnableRightClick = 0;if(isNS) document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);function mischandler(){if(EnableRightClick==1){ return true;}else {return false; }}function mousehandler(e){  if(EnableRightClick==1){ return true; }  var myevent = (isNS) ? e : event;  var eventbutton = (isNS) ? myevent.which : myevent.button;  if((eventbutton==2)||(eventbutton==3)) return false;}function keyhandler(e) {var myevent = (isNS) ? e : window.event;if (myevent.keyCode==96)EnableRightClick = 1;return;}document.oncontextmenu = mischandler;document.onkeypress = keyhandler;document.onmousedown = mousehandlerdocument.onmouseup = mousehandler;</SCRIPT>

      <TABLE border=0 cellSpacing=0 cellPadding=0 width="100%"><!-- Start Header -->
        <TBODY>
        <TR><BR><BR>
          <!--<TD height=20 vAlign=top align=left><IMG border=0 alt="BT Wholesale"
            src="dsl_images/g_main_logo.gif" width=129
height=20></TD></TR>
        <TR>
          <TD class=body height=14 vAlign=top align=left><IMG alt=""
            src="dsl_images/spacer.gif" width=450 height=14></TD></TR>
        <TR>//-->
          <TD class=body vAlign=top align=left fontStyle="italic">
            <TABLE border=0 cellSpacing=0 cellPadding=0 width=450><!-- Start Page Title -->
              <TBODY>
              <TR>
                <TD height=45 vAlign=top width=600 align=left><FONT
                  style="FONT-FAMILY: Calibri Light" color=#6400AA size=6.5><B> BT BROADBAND
                  AVAILABILITY
              CHECKER</B></FONT></TD></TR><!-- End Page Title --></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE><SPAN
      class=body><!--RESPONSE-START-->
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Welcome to the Broadband Availability checker. This
      will provide a provisional check of your ability to receive reliable
      Broadband services.</font></SPAN></P>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Please enter your telephone number.</font></SPAN></P>
      <FORM method=post action=adsl/adslchecker.TelephoneNumberOutput><INPUT
      type=hidden name=URL> <INPUT value=a%20service%20provider type=hidden
      name=SP_NAME> <SPAN class=subheading>TELEPHONE:</SPAN><BR><INPUT
      maxLength=14 size=14 name=TelNo> <INPUT value=56 type=hidden name=VERSION>
      <INPUT value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP>
      <INPUT value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>
      <P><SPAN class=body>Or</SPAN></P>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Please enter your access line id.</font></SPAN></P>
      <FORM method=post action=adsl/adslchecker.AccessLineIDOutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      <SPAN class=subheading>ACCESS LINE ID:</SPAN><BR><INPUT maxLength=13
      size=14 name=ALID> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>
          <P><SPAN class=body>Or</SPAN></P>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Please enter your UPRN.</font></SPAN></P>
      <FORM method=post action=adsl/ADSLChecker.UPRNoutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      <SPAN class=subheading>UPRN:</SPAN><BR><INPUT maxLength=13
      size=14 name=UPRN> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">If you do not have a telephone number or access line
      id, please select the</font>
<TABLE>
  <TR>
   <FORM method=post action=adsl/adslchecker.address>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
          <TD><A href=# onclick="document.forms[3].submit()">Address Checker</A></TD>
   </FORM>
          <FONT>
          <TH><P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">or the</font></SPAN></P></TH>
          </FONT>
   <FORM method=post action=adsl/adslchecker.postcode>
          <TD><A href=# onclick="document.forms[4].submit()">Postcode Checker</A></TD>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>
          <FONT>
          <TH><P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">or the</font></SPAN></P></TH>
          </FONT>
   <FORM method=post action=adsl/adslchecker.bbeuidform>
          <TD><A href=# onclick="document.forms[5].submit()">BBEU Checker</A></TD>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>
  </TR>
</TABLE>
<P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">By submitting a query into this checker you accept <A
      href="https://www.btwholesale.com/pages/static/terms-of-use.htm" target="_blank">Terms of Use</A> for this checker.</font>
<!--RESPONSE-END--></SPAN></P></SPAN></TD></TR></TBODY></TABLE></BODY></HTML>
</code>```

'''

答:
You are posting the the wrong url. I used pandas to pull the table, so you'll need to do a little clean up work, but try:

```<code>import requests
import pandas as pd

url = 'https://www.dslchecker.bt.com/adsl/ADSLChecker.UPRNoutput'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}

UPRN = 10033346575

payload = {
'URL': '',
'SP_NAME': 'a%20service%20provider',
'UPRN': str(UPRN),
'VERSION': '56',
'MS': 'E',
'CAP': 'no',
'AEA': 'Y'}

response = requests.post(url, headers=headers, params=payload)

tables = pd.read_html(response.text)
df = tables[-1]
</code>```

Output:

```<code>print(df.to_string())
          Featured Products  Downstream Line Rate(Mbps)                              Upstream Line Rate(Mbps)                           Downstream Handback Threshold(Mbps)  WBC FTTC Availability Date WBC SOGEA Availability Date Unnamed: 8_level_0
         Unnamed: 0_level_1                        High                         Low                      High                       Low                  Unnamed: 5_level_1          Unnamed: 6_level_1          Unnamed: 7_level_1 Unnamed: 8_level_1
0      VDSL Range A (Clean)                           3                         1.2                       1.2                       0.8                                 0.8                   Available                   Available                NaN
1   VDSL Range B (Impacted)                         2.8                         1.2                       1.2                       0.5                                 0.8                   Available                   Available                NaN
2         Featured Products  Downstream Line Rate(Mbps)  Downstream Line Rate(Mbps)  Upstream Line Rate(Mbps)  Upstream Line Rate(Mbps)              Downstream Range(Mbps)  WBC FTTP Availability Date                         NaN                NaN
3            FTTP on Demand                         330                         330                        30                        30                                  --                   Available                          --                NaN
4             ADSL Products  Downstream Line Rate(Mbps)  Downstream Line Rate(Mbps)  Upstream Line Rate(Mbps)  Upstream Line Rate(Mbps)              Downstream Range(Mbps)           Availability Date                         NaN                NaN
5               WBC ADSL 2+                     Up to 1                     Up to 1                        --                        --                            1 to 3.5                   Available                          --                NaN
6                  ADSL Max                     Up to 1                     Up to 1                        --                        --                         0.75 to 2.5                   Available                          --                NaN
7            WBC Fixed Rate                         0.5                         0.5                        --                        --                                  --                   Available                          --                NaN
8                Fixed Rate                         0.5                         0.5                        --                        --                                  --                   Available                          --                NaN
9           Observed Speeds                        VDSL                        VDSL                       NaN                       NaN                                 NaN                         NaN                         NaN                NaN
10          Other Offerings                         NaN                         NaN                       NaN                       NaN                                 NaN           Availability Date                         NaN                NaN
11           VDSL Multicast                          --                          --                        --                        --                                  --                   Available                          --                NaN
12           ADSL Multicast                          --                          --                        --                        --                                  --                   Available                          --                NaN
</code>```

Body:
I am writing a data scraping script. It's purpose is to collect data on available broadband deals from BT's website. I cannot figure out why my simple requests code doesn't fill in the form and follow through to the next page.

Please help me figure out how to enter data into this form and save the output html for data scraping.

I have identified the relevant tags in the form that I am interested in. I am trying to populate the UPRN field and continue to the next page

Link to website: https://www.dslchecker.bt.com/#

My python code:
'''python

import requests
url = "https://www.dslchecker.bt.com/#"
payload = {'UPRN':'10033360983'}
r = requests.post(url, data = payload)
print(r.text)

'''

Form from the website:

'''html

<form method="post" action="adsl/ADSLChecker.UPRNoutput"><input type="hidden" name="URL"> <input value="a%20service%20provider" type="hidden" name="SP_NAME">
      UPRN:
<input maxlength="13" size="14" name="UPRN" autocomplete="off" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAAXNSR0IArs4c6QAAAPhJREFUOBHlU70KgzAQPlMhEvoQTg6OPoOjT+JWOnRqkUKHgqWP4OQbOPokTk6OTkVULNSLVc62oJmbIdzd95NcuGjX2/3YVI/Ts+t0WLE2ut5xsQ0O+90F6UxFjAI8qNcEGONia08e6MNONYwCS7EQAizLmtGUDEzTBNd1fxsYhjEBnHPQNG3KKTYV34F8ec/zwHEciOMYyrIE3/ehKAqIoggo9inGXKmFXwbyBkmSQJqmUNe15IRhCG3byphitm1/eUzDM4qR0TTNjEixGdAnSi3keS5vSk2UDKqqgizLqB4YzvassiKhGtZ/jDMtLOnHz7TE+yf8BaDZXA509yeBAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%; cursor: auto;"> <input value="56" type="hidden" name="VERSION"> <input value="E" type="hidden" name="MS"> <input value="no" type="hidden" name="CAP"> <input value="Y" type="hidden" name="AEA">   <input class="form_button" value="submit" type="submit"> </form>

'''

Please follow this link :https://www.dslchecker.bt.com/# and enter 10033346575 in the UPRN field to see the desired output

My output when ran in a jupyter notebook:

'''html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<TITLE>BT Broadband</TITLE>
<META content="text/html; charset=utf-8" http-equiv=Content-Type><LINK
rel=stylesheet type=text/css
href="adslchecker_font.html">
<META content=text/css http-equiv=Content-Style-Type><META http-equiv="X-UA-Compatible" content="IE=5">

<META name=GENERATOR content="MSHTML 8.00.7601.18751">

                 BT BROADBAND
                  AVAILABILITY
              CHECKER

Welcome to the Broadband Availability checker. This
      will provide a provisional check of your ability to receive reliable
      Broadband services.

Please enter your telephone number.

      <FORM method=post action=adsl/adslchecker.TelephoneNumberOutput><INPUT
      type=hidden name=URL> <INPUT value=a%20service%20provider type=hidden
      name=SP_NAME> TELEPHONE:
<INPUT
      maxLength=14 size=14 name=TelNo> <INPUT value=56 type=hidden name=VERSION>
      <INPUT value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP>
      <INPUT value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>

Or

Please enter your access line id.

      <FORM method=post action=adsl/adslchecker.AccessLineIDOutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      ACCESS LINE ID:
<INPUT maxLength=13
      size=14 name=ALID> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>

Or

Please enter your UPRN.

      <FORM method=post action=adsl/ADSLChecker.UPRNoutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      UPRN:
<INPUT maxLength=13
      size=14 name=UPRN> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>

If you do not have a telephone number or access line
      id, please select the

   <FORM method=post action=adsl/adslchecker.address>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
          Address Checker
   </FORM>

or the

   <FORM method=post action=adsl/adslchecker.postcode>
          Postcode Checker
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>

or the

   <FORM method=post action=adsl/adslchecker.bbeuidform>
          BBEU Checker
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>

By submitting a query into this checker you accept Terms of Use for this checker.

'''

Body:
You are posting the the wrong url. I used pandas to pull the table, so you'll need to do a little clean up work, but try:

import requests
import pandas as pd

url = 'https://www.dslchecker.bt.com/adsl/ADSLChecker.UPRNoutput'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}

UPRN = 10033346575

payload = {
'URL': '',
'SP_NAME': 'a%20service%20provider',
'UPRN': str(UPRN),
'VERSION': '56',
'MS': 'E',
'CAP': 'no',
'AEA': 'Y'}

response = requests.post(url, headers=headers, params=payload)

tables = pd.read_html(response.text)
df = tables[-1]

Output:

print(df.to_string())
          Featured Products  Downstream Line Rate(Mbps)                              Upstream Line Rate(Mbps)                           Downstream Handback Threshold(Mbps)  WBC FTTC Availability Date WBC SOGEA Availability Date Unnamed: 8_level_0
         Unnamed: 0_level_1                        High                         Low                      High                       Low                  Unnamed: 5_level_1          Unnamed: 6_level_1          Unnamed: 7_level_1 Unnamed: 8_level_1
0      VDSL Range A (Clean)                           3                         1.2                       1.2                       0.8                                 0.8                   Available                   Available                NaN
1   VDSL Range B (Impacted)                         2.8                         1.2                       1.2                       0.5                                 0.8                   Available                   Available                NaN
2         Featured Products  Downstream Line Rate(Mbps)  Downstream Line Rate(Mbps)  Upstream Line Rate(Mbps)  Upstream Line Rate(Mbps)              Downstream Range(Mbps)  WBC FTTP Availability Date                         NaN                NaN
3            FTTP on Demand                         330                         330                        30                        30                                  --                   Available                          --                NaN
4             ADSL Products  Downstream Line Rate(Mbps)  Downstream Line Rate(Mbps)  Upstream Line Rate(Mbps)  Upstream Line Rate(Mbps)              Downstream Range(Mbps)           Availability Date                         NaN                NaN
5               WBC ADSL 2+                     Up to 1                     Up to 1                        --                        --                            1 to 3.5                   Available                          --                NaN
6                  ADSL Max                     Up to 1                     Up to 1                        --                        --                         0.75 to 2.5                   Available                          --                NaN
7            WBC Fixed Rate                         0.5                         0.5                        --                        --                                  --                   Available                          --                NaN
8                Fixed Rate                         0.5                         0.5                        --                        --                                  --                   Available                          --                NaN
9           Observed Speeds                        VDSL                        VDSL                       NaN                       NaN                                 NaN                         NaN                         NaN                NaN
10          Other Offerings                         NaN                         NaN                       NaN                       NaN                                 NaN           Availability Date                         NaN                NaN
11           VDSL Multicast                          --                          --                        --                        --                                  --                   Available                          --                NaN
12           ADSL Multicast                          --                          --                        --                        --                                  --                   Available                          --                NaN


问:
Tracking multiple clicks on the same element
Looking for a way to track if an element has been clicked multiple times (for example, a user clicks "Submit" button several times to place an order).

We are doing some work redeveloping a website and in our UX research we found that people don't download PDFs from the site because the link behind the button is broken. We noticed that people tend to click the button several times before giving up, yet some still manage to download the PDF.

In order to show our changes to code have improved site performance and user experiences, we want to show that these "multiple clicks" have decreased.

Since the site uses Google Analytics, I have tried to create a variable in GTM that counts clicks on the same click element (which doesn't work):

```<code>function() {
var the_div = {{Click Element}};
var clickCount = 0;
return clickCount;
}
</code>```

I expect the output to be a count of the times I've clicked on the Click Element (1, 2, 3, etc....)

答:
Try like this.

Define a varable for count. and on each click increment it.

var i = 1;
$('#elem').on('click',function(){
  console.log(i);
  i++;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elem">click here</div></code>```

Body:
Looking for a way to track if an element has been clicked multiple times (for example, a user clicks "Submit" button several times to place an order).

We are doing some work redeveloping a website and in our UX research we found that people don't download PDFs from the site because the link behind the button is broken. We noticed that people tend to click the button several times before giving up, yet some still manage to download the PDF.

In order to show our changes to code have improved site performance and user experiences, we want to show that these "multiple clicks" have decreased.

Since the site uses Google Analytics, I have tried to create a variable in GTM that counts clicks on the same click element (which doesn't work):

function() {
var the_div = {{Click Element}};
var clickCount = 0;
return clickCount;
}

I expect the output to be a count of the times I've clicked on the Click Element (1, 2, 3, etc....)

Body:
Try like this.

Define a varable for count. and on each click increment it.

var i = 1;
$('#elem').on('click',function(){
  console.log(i);
  i++;
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elem">click here</div>


问:
Summing by multiple columns in a list
I am creating a html table to display values in a List<> the list has three columns: the name of the indicator, the year and month in which it was selected and the count of the number of times it has been filtered on.

the code and html I am using is shown below:

```<code><table class="users">
    <tr>
        <th></th>
        @foreach (var monthYear in Model.KeyIndicatorUseCount.Select(m => m.MonthYear).Distinct())
        {
            <th>@monthYear</th>
        }
    </tr>
    @foreach (var keyIndicator in Model.KeyIndicatorUseCount.Select(m => m.Name).Distinct())
    {
        <tr>
            <td>@keyIndicator</td>
            @foreach (var monthYear in Model.KeyIndicatorUseCount.Select(m => m.MonthYear).Distinct())
            {
                <td>@Model.KeyIndicatorUseCount.Sum(m => m.Count)</td>
            }
        </tr>
    }
</table>
</code>```

Currently the table is being populated with the sum of the values for the first month-year column.

The calculation needs to be the sum of the number of views for each key indicator with that month-year.

For reference here is a screenshot of what is currently being produced:

How do I go about performing the calculation to get a sum which corresponds to each month-year for the key indicator name in the first column?

答:
```<code> @foreach (var keyIndicator in item.OrderBy(f => f.Name).GroupBy(f => f.Name))
 {
     <tr>
         <td>@keyIndicator.Key</td>
         @foreach (var monthYear in keyIndicator.OrderBy(f => f.MonthYear).GroupBy(f => f.MonthYear))
         {
              <td>@(keyIndicator.Sum(f => f.Count))</td>
         }
         <td>
             @(keyIndicator.Sum(f => f.Count)) /* if you want to sum count of every month of year */
         </td>
     </tr>
}
</code>```

Title: Summing by multiple columns in a list

Body:
I am creating a html table to display values in a List<> the list has three columns: the name of the indicator, the year and month in which it was selected and the count of the number of times it has been filtered on.

the code and html I am using is shown below:

        @foreach (var monthYear in Model.KeyIndicatorUseCount.Select(m => m.MonthYear).Distinct())
        {
            @monthYear
        }

    @foreach (var keyIndicator in Model.KeyIndicatorUseCount.Select(m => m.Name).Distinct())
    {

            @keyIndicator
            @foreach (var monthYear in Model.KeyIndicatorUseCount.Select(m => m.MonthYear).Distinct())
            {
                @Model.KeyIndicatorUseCount.Sum(m => m.Count)
            }

    }

Currently the table is being populated with the sum of the values for the first month-year column.

The calculation needs to be the sum of the number of views for each key indicator with that month-year.

For reference here is a screenshot of what is currently being produced:

How do I go about performing the calculation to get a sum which corresponds to each month-year for the key indicator name in the first column?


问:
Ansible change all dict key values only by filters
I have an ansible dict like

```<code>ports:
  webui: 7200
  webadmin: 7209
  core_api: 7201
  stock_api: 7204
  import_export: 7207
</code>```

And i want to transform all keys in it, like

```<code>ports:
  staging-webui: 7200
  staging-webadmin: 7209
  staging-core_api: 7201
  staging-stock_api: 7204
  staging-import_export: 7207
</code>```

I do that in 'vars' section, so i can't use 'set_fact' with 'with_items' to iterate over dict. Is it possible to it only by filters?

I found working answer,

```<code>env: staging # comes from outside

regex_env: "\"key\": \"{{ env }}-\\1\""
app_upstreams: "{{ ports | dict2items | map('to_json') | map('regex_replace', '\"key\":\\s\"(.*)\"', lookup('vars', 'regex_env')) | map('from_json') }}"
</code>```

but it looks really ugly, is there more good-looking solution?

答:
You can achieve this using jinja2 template module and create a yml file with all the variables.

playbook -->

```<code>---
- hosts: localhost
  vars:
    ports:
      webui: 7200
      webadmin: 7209
      core_api: 7201
      stock_api: 7204
      import_export: 7207
  tasks:
    - name: debug module
      debug:
        var: "{{ item }}"
      with_items:
        - ports

    - name: template
      template:
        src: templates/template.yml
        dest: templates/dest.yml
</code>```

jinja2 template -->

```<code>ports:
{% for key, value in ports.iteritems() %}
  staging-{{ key }}: {{ value }}
{% endfor %}
</code>```

output -->

```<code>ports:
  staging-core_api: 7201
  staging-import_export: 7207
  staging-stock_api: 7204
  staging-webui: 7200
  staging-webadmin: 7209
</code>```

Body:
I have an ansible dict like

ports:
  webui: 7200
  webadmin: 7209
  core_api: 7201
  stock_api: 7204
  import_export: 7207

And i want to transform all keys in it, like

ports:
  staging-webui: 7200
  staging-webadmin: 7209
  staging-core_api: 7201
  staging-stock_api: 7204
  staging-import_export: 7207

I do that in 'vars' section, so i can't use 'set_fact' with 'with_items' to iterate over dict. Is it possible to it only by filters?

I found working answer,

env: staging # comes from outside

regex_env: "\"key\": \"{{ env }}-\\1\""
app_upstreams: "{{ ports | dict2items | map('to_json') | map('regex_replace', '\"key\":\\s\"(.*)\"', lookup('vars', 'regex_env')) | map('from_json') }}"

but it looks really ugly, is there more good-looking solution?

Body:
You can achieve this using jinja2 template module and create a yml file with all the variables.

playbook -->

---
- hosts: localhost
  vars:
    ports:
      webui: 7200
      webadmin: 7209
      core_api: 7201
      stock_api: 7204
      import_export: 7207
  tasks:
    - name: debug module
      debug:
        var: "{{ item }}"
      with_items:
        - ports

    - name: template
      template:
        src: templates/template.yml
        dest: templates/dest.yml

jinja2 template -->

ports:
{% for key, value in ports.iteritems() %}
  staging-{{ key }}: {{ value }}
{% endfor %}

output -->

ports:
  staging-core_api: 7201
  staging-import_export: 7207
  staging-stock_api: 7204
  staging-webui: 7200
  staging-webadmin: 7209


问:
Writing a abstract function turns integer into string

Possible Duplicate:

  Easiest way to convert int to string in C++

```<code>class MyInteger
{
   MyInteger() : m_val(0) { }
   MyInteger()( int _val ) : m_val( _val ) {}
  ~MyInteger() {}
};

MyInteger myInteger(10);
std::string s = (std::string)myInteger
</code>```

How can I write C++ function to get "10" in s??
I am new to C++.

Thanks you very much.

答:
you could have a method

```<code>#include <sstream>
#include <string>
//...

std::string MyInteger::toString()
{
    std::stringstream stream;
    stream << m_val;
    return stream.str();
}
</code>```

or to fit your style:

```<code>class MyInteger
{
public:
    MyInteger() : m_val(0) { }
    MyInteger()( int _val ) : m_val( _val ) {}
   ~MyInteger() {}

   std::string toString()
   {
        std::stringstream stream;
        stream << m_val;
        return stream.str();
   }

private:
   int m_val;
};
</code>```

Body:
Possible Duplicate:

  Easiest way to convert int to string in C++

class MyInteger
{
   MyInteger() : m_val(0) { }
   MyInteger()( int _val ) : m_val( _val ) {}
  ~MyInteger() {}
};

MyInteger myInteger(10);
std::string s = (std::string)myInteger

How can I write C++ function to get "10" in s??
I am new to C++.

Thanks you very much.

Body:
you could have a method

#include <sstream>
#include <string>
//...

std::string MyInteger::toString()
{
    std::stringstream stream;
    stream << m_val;
    return stream.str();
}

or to fit your style:

class MyInteger
{
public:
    MyInteger() : m_val(0) { }
    MyInteger()( int _val ) : m_val( _val ) {}
   ~MyInteger() {}

   std::string toString()
   {
        std::stringstream stream;
        stream << m_val;
        return stream.str();
   }

private:
   int m_val;
};


问:
MVCGrid.NET - How to reload the grid?
I am using MVCGrid.NET http://mvcgrid.net/

And I created a Non-Fluent grid http://mvcgrid.net/gettingstarted see Non-Fluent Example

```<code>GridDefinition<YourModelItem> def = new GridDefinition<YourModelItem>();

GridColumn<YourModelItem> column = new GridColumn<YourModelItem>();
column.ColumnName = "UniqueColumnName";
column.HeaderText = "Any Header";
column.ValueExpression = (i, c) => i.YourProperty;
def.AddColumn(column);

def.RetrieveData = (options) =>
{
    return new QueryResult<YourModelItem>()
        {
            Items = new List<YourModelItem>(),
            TotalRecords = 0
        };
};

MVCGridDefinitionTable.Add("NonFluentUsageExample", def);
</code>```

Now I have my grid appear when you submit a form, but when I submit the form again, I am expecting new data, but the grid does not reload or refresh or anything. It does't even reset when I refresh the page, I have to do a full reload of the page to reset it, which is lame, does anyone know how to refresh or reload the grid when I want to show new data?

I have even tried this: http://mvcgrid.net/demo/NoQueryOnPageLoad

But it did not reload or refresh.

PLEASE HELP!

答:
It reloads, try this,

```<code> //model class
    public class YourModelItem
    {
        public int Id { get; set; }
        public string YourProperty { get; set; }
    }

    //controller
    public class HomeController : Controller
    {
        private static List<YourModelItem> _modelItems = new List<YourModelItem>();

        public ActionResult Index()
        {
            GridDefinition<YourModelItem> def = new GridDefinition<YourModelItem>();

            GridColumn<YourModelItem> column = new GridColumn<YourModelItem>();
            column.ColumnName = "UniqueColumnName";
            column.HeaderText = "Any Header";
            column.ValueExpression = (i, c) => i.YourProperty;
            def.AddColumn(column);

            def.RetrieveData = (options) => new QueryResult<YourModelItem>()
            {
                Items = _modelItems,
                TotalRecords = 0
            };

            MVCGridDefinitionTable.Add("NonFluentUsageExample", def);

            return View();
        }

        [HttpPost]
        public JsonResult Add(YourModelItem item)
        {
            _modelItems.Add(item);

            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }
</code>```

index.cshtml

```<code>@{
    ViewBag.Title = "Home Page";
}

@using MVCGrid.Web

<div class="jumbotron">
    <div id="form1">
        <div class="form-group">
            <label for="Id">ID</label>
            <input type="number" class="form-control" id="Id" aria-describedby="Id" placeholder="Enter Id">
        </div>
        <div class="form-group">
            <label for="YourProperty">YourProperty</label>
            <input type="text" class="form-control" id="YourProperty" placeholder="Enter Your Property">
        </div>

        <button id="addItem">Submit</button>
    </div>

    <br />

    @Html.MVCGrid("NonFluentUsageExample")
</div>

@section scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            $("#addItem").click(function () {
                var formData = { Id: $('#Id').val(), YourProperty: $('#YourProperty').val() };

                $.ajax({
                    type: "POST",
                    url: "/Home/add",
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(data) {
                        if (data) {
                            MVCGrid.reloadGrid('NonFluentUsageExample');
                        }
                    }
                });
            });
        });
    </script>
}
</code>```

_layout.cshtml -> body

```<code><body>
    <div class="container body-content">
        @RenderBody()
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    <script src="~/MVCGridHandler.axd/script.js"></script>

    @RenderSection("scripts", required: false)
</body>
</code>```

It adds item and reloads after "Submit".
Just have installed MVCGrid in new asp.net mvc - Install-Package MVCGrid.Net
Put these lines as above

Title: MVCGrid.NET - How to reload the grid?

Body:
I am using MVCGrid.NET http://mvcgrid.net/

And I created a Non-Fluent grid http://mvcgrid.net/gettingstarted see Non-Fluent Example

GridDefinition<YourModelItem> def = new GridDefinition<YourModelItem>();

GridColumn<YourModelItem> column = new GridColumn<YourModelItem>();
column.ColumnName = "UniqueColumnName";
column.HeaderText = "Any Header";
column.ValueExpression = (i, c) => i.YourProperty;
def.AddColumn(column);

def.RetrieveData = (options) =>
{
    return new QueryResult<YourModelItem>()
        {
            Items = new List<YourModelItem>(),
            TotalRecords = 0
        };
};

MVCGridDefinitionTable.Add("NonFluentUsageExample", def);

Now I have my grid appear when you submit a form, but when I submit the form again, I am expecting new data, but the grid does not reload or refresh or anything. It does't even reset when I refresh the page, I have to do a full reload of the page to reset it, which is lame, does anyone know how to refresh or reload the grid when I want to show new data?

I have even tried this: http://mvcgrid.net/demo/NoQueryOnPageLoad

But it did not reload or refresh.

PLEASE HELP!

Body:
It reloads, try this,

 //model class
    public class YourModelItem
    {
        public int Id { get; set; }
        public string YourProperty { get; set; }
    }

    //controller
    public class HomeController : Controller
    {
        private static List<YourModelItem> _modelItems = new List<YourModelItem>();

        public ActionResult Index()
        {
            GridDefinition<YourModelItem> def = new GridDefinition<YourModelItem>();

            GridColumn<YourModelItem> column = new GridColumn<YourModelItem>();
            column.ColumnName = "UniqueColumnName";
            column.HeaderText = "Any Header";
            column.ValueExpression = (i, c) => i.YourProperty;
            def.AddColumn(column);

            def.RetrieveData = (options) => new QueryResult<YourModelItem>()
            {
                Items = _modelItems,
                TotalRecords = 0
            };

            MVCGridDefinitionTable.Add("NonFluentUsageExample", def);

            return View();
        }

        [HttpPost]
        public JsonResult Add(YourModelItem item)
        {
            _modelItems.Add(item);

            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }

index.cshtml

@{
    ViewBag.Title = "Home Page";
}

@using MVCGrid.Web

<div class="jumbotron">
    <div id="form1">
        <div class="form-group">
            <label for="Id">ID</label>
            <input type="number" class="form-control" id="Id" aria-describedby="Id" placeholder="Enter Id">
        </div>
        <div class="form-group">
            <label for="YourProperty">YourProperty</label>
            <input type="text" class="form-control" id="YourProperty" placeholder="Enter Your Property">
        </div>

        <button id="addItem">Submit</button>
    </div>

    <br />

    @Html.MVCGrid("NonFluentUsageExample")
</div>

@section scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            $("#addItem").click(function () {
                var formData = { Id: $('#Id').val(), YourProperty: $('#YourProperty').val() };

                $.ajax({
                    type: "POST",
                    url: "/Home/add",
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(data) {
                        if (data) {
                            MVCGrid.reloadGrid('NonFluentUsageExample');
                        }
                    }
                });
            });
        });
    </script>
}

_layout.cshtml -> body

<body>
    <div class="container body-content">
        @RenderBody()
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    <script src="~/MVCGridHandler.axd/script.js"></script>

    @RenderSection("scripts", required: false)
</body>

It adds item and reloads after "Submit".
Just have installed MVCGrid in new asp.net mvc - Install-Package MVCGrid.Net
Put these lines as above


问:
Xamarin.Forms Refresh ContentPage in TabbedPage
I'm new to app development and I created an app with a TabbedPage as MainPage. This TabbedPage has 3 children (ContentPages).
Now when I'm switching between the tabs, the tabbed page doesn't refresh.
For example in one ContentPage it's possible to enter some data, and the other ContentPage should show these data now.
So my question is how can I refresh (new instance or something like this) the ContentPage when I click on it's tab.

Thank you

答:
In this particular case I would have one view model that is assigned as the binding context of the tabbed page, and then it should just work.

If you are not into using view models, which is recommended, you may try with messaging center https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center to communicate among the pages.

Finally you can always use some sort of events to communicate among classes, just in this case it really wouldn't be recommended to do that.