问:
CSS - border not going over elements that float left
I have this code here:

```<code><div style="border:3px solid #808080;">
    <h1 style="text-transform: uppercase;font-size: 38px;color: #808080;text-align: center;">Lowell</h1>
    <div class="column-1">
         <img src="images/ruler-icon.png">
    </div>
    <div class="column-2">
         <img src="images/bed-icon.png">
    </div>
    <div class="column-3">
         <img src="images/bath-icon.png">
    </div>
</div>
</code>```

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

```<code>.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}
</code>```

答:
I think this is the css you need. Choose the width according to your needs.</p>

```<code>.column-1, .column-2, .column-3
{
    width: 30%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
    display:inline-block;
}
</code>```

Body:
I have this code here:

Lowell

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}

Body:
I think this is the css you need. Choose the width according to your needs.

.column-1, .column-2, .column-3
{
    width: 30%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
    display:inline-block;
}


来源: stackexchange

问:
JavaScript variable empty after call of getJSON()
I'm having this issue with importing data from a JSON file. I use the .getJSON function to get the data which means to work according to the console log, but once I move out of the getJSON sub function the array in data2 disappears. I've narrowed it down to this section here:

```<code>function prepData() {
    data2 = [];

    $.getJSON('http://localhost/data').done(function(json) {
        data2 =json;
        console.log(data2);
    });

    console.log(data2);
    SelectedData = data2;
    return SelectedData;
};
</code>```

What might the issue be here?

答:
The .done is an event so it will happen few milliseconds or seconds later than the other script, it only occurs when the request to http://localhost/data is completed

this will run first:

```<code>$.getJSON('http://localhost/data');
console.log(data2);
SelectedData= data2;
return SelectedData;
</code>```

few seconds later .done event will be fired
then this will run

```<code>data2 =json;
console.log(data2);
</code>```

my suggestion is in the .done function call another function that process the answer, instead of waiting for return value which will return as undefined in your code

ContentLicense: CC BY-SA 3.0

Body:
I'm having this issue with importing data from a JSON file. I use the .getJSON function to get the data which means to work according to the console log, but once I move out of the getJSON sub function the array in data2 disappears. I've narrowed it down to this section here:

function prepData() {
    data2 = [];

    $.getJSON('http://localhost/data').done(function(json) {
        data2 =json;
        console.log(data2);
    });

    console.log(data2);
    SelectedData = data2;
    return SelectedData;
};

What might the issue be here?

Body:
The .done is an event so it will happen few milliseconds or seconds later than the other script, it only occurs when the request to http://localhost/data is completed

this will run first:

$.getJSON('http://localhost/data');
console.log(data2);
SelectedData= data2;
return SelectedData;

few seconds later .done event will be fired
then this will run

data2 =json;
console.log(data2);

my suggestion is in the .done function call another function that process the answer, instead of waiting for return value which will return as undefined in your code


问:
Can one author a library API – one accessible outside Python – using Cython?
I know Cython's purpose is to create Python extensions modules, but can the compiled libraries made with Cython be loaded by non-python programs? If not, why?</p>

答:
There are two mechanisms by which you can make cdef’ed Cython structures available externally:

Use a cdef public declaration – and/or also

Use the api keyword.

Here’s one of the examples of both mechanisms, from the aforelinked pages:

cdef public struct Vehicle:
    int speed
    float power

cdef api void activate(Vehicle *v):
    if v.speed >= 88 and v.power >= 1.21:
        print "Time travel achieved"
```

Each of these methods will instruct the Cython compiler to generate a header (“.h”) file that you can then integrate with your orthogonal C/C++ project.

A cdef public declaration yields a file named modulename.h; using the structures in this file will require you to link with the compiled Cython extension module.

An api declaration (which may be used simultaneously with cdef public, if you so desire) yields a modulename_api.h file; code consuming an api-based header will not need to link to the extension module – but it will need to call the cdef’d function import_modulename() before any of the API code can be used (a tactic the Cython-inclined users of NumPy will find familiar).

In my personal experience, it takes little effort to expose and subsequently employ encythoned structures as an external API in this fashion, provided that the struct layouts dovetail well with the consuming code, and that you’re willing to contend with manually managing the GIL in your C/C++ code in order to make things work.

Body:
There are two mechanisms by which you can make cdef’ed Cython structures available externally:

Use a cdef public declaration – and/or also

Use the api keyword.

Here’s one of the examples of both mechanisms, from the aforelinked pages:

cdef public struct Vehicle:
    int speed
    float power

cdef api void activate(Vehicle *v):
    if v.speed >= 88 and v.power >= 1.21:
        print "Time travel achieved"

Each of these methods will instruct the Cython compiler to generate a header (“.h”) file that you can then integrate with your orthogonal C/C++ project.

A cdef public declaration yields a file named modulename.h; using the structures in this file will require you to link with the compiled Cython extension module.

An api declaration (which may be used simultaneously with cdef public, if you so desire) yields a modulename_api.h file; code consuming an api-based header will not need to link to the extension module – but it will need to call the cdef’d function import_modulename() before any of the API code can be used (a tactic the Cython-inclined users of NumPy will find familiar).

In my personal experience, it takes little effort to expose and subsequently employ encythoned structures as an external API in this fashion, provided that the struct layouts dovetail well with the consuming code, and that you’re willing to contend with manually managing the GIL in your C/C++ code in order to make things work.


问:
What do you use the Android Terminal Emulator for?
Why is there a terminal emulator in the Android App Market?</p>

答:
So you can get direct access to the commandline?

Android is based on Linux, so it's essentially the Linux commandline you'd be accessing here

If you don't know the Linux commandline:

http://linuxcommand.org/learning_the_shell.php

Please note that it'll be a somewhat limited environment - you might need to root your phone to get access to everything, also some commands won't be available, you probably want to install something like Busybox to get a more featureful environment.

Cheers,
Victor

ContentLicense: CC BY-SA 2.5


问:
Matplotlib: how to edit a figure that has been closed
```<code>import matplotlib.pyplot as plt
a = plt.figure(1)
plt.plot([1,2,3,4])
a.show()
</code>```

after closing the canvas I can show the figure stored in variable a at any time using a.show(), but how can I edit this figure?

答:
As with most things matplotlib, you should keep track of your Figure and Axes objects directly. The you can do "anything"

So your example becomes:

```<code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,4])
fig.show()

# <close the figure>
ax.set_xlabel('Post-mortem')
</code>```

Body:
import matplotlib.pyplot as plt
a = plt.figure(1)
plt.plot([1,2,3,4])
a.show()

after closing the canvas I can show the figure stored in variable a at any time using a.show(), but how can I edit this figure?

Body:
As with most things matplotlib, you should keep track of your Figure and Axes objects directly. The you can do "anything"

So your example becomes:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,4])
fig.show()

# <close the figure>
ax.set_xlabel('Post-mortem')


答:
How about something like:</p>

```<code>t(apply(sample[,-1], 1, diff))
</code>```

Title: loop for value differences between consecutive columns

Body:
I have the following dataset: the 10-minute instances are taken from a feed that displays the number of bicycles at a station at a given time.  My goal is to find out the difference in value from one time to the next for each station_id

> dim(sample)
[1]  6 73
> sample
  station_id 2014-08-18 20:00:00 2014-08-18 20:10:00 2014-08-18 20:20:00
1          1                   1                   0                   0
2          2                  18                  18                  19
3          3                   5                   4                   4
4          4                  21                  20                  20
5          5                   9                  10                   8
6          6                   9                   9                   9
  2014-08-18 20:30:00 2014-08-18 20:40:00 2014-08-18 20:50:00 2014-08-18 21:00:00
1                   2                   1                   1                   0
2                  18                  18                  21                  22
3                   4                   4                   4                   4
4                  21                  22                  25                  23
5                   5                   7                   3                   0
6                   9                   9                   9                   9
  2014-08-18 21:10:00 2014-08-18 21:20:00 2014-08-18 21:30:00 2014-08-18 21:40:00
1                   0                   4                   2                   1
2                  21                  22                  22                  21
3                   4                   6                   3                   3
4                  25                  24                  24                  24
5                   0                   0                   0                   0
6                   9                   9                  10                  10
  2014-08-18 21:50:00 2014-08-18 22:00:00 2014-08-18 22:10:00 2014-08-18 22:20:00
1                   3                   2                   3                   2
2                  21                  22                  18                  16
3                   4                   5                   6                   4
4                  25                  22                  21                  21
5                   4                   0                   0                   3
6                  10                  10                  11                  11
  2014-08-18 22:30:00 2014-08-18 22:40:00 2014-08-18 22:50:00 2014-08-18 23:00:00
1                   2                   3                   8                  11
2                  15                  14                  16                  17
3                   4                   4                   4                   4
4                  23                  21                  20                  20
5                   0                   1                   0                   0
6                  11                  12                  12                  12
  2014-08-18 23:10:00 2014-08-18 23:20:00 2014-08-18 23:30:00 2014-08-18 23:40:00
1                  11                  13                  14                  15
2                  17                  15                  10                   3
3                   5                   5                   5                   4
4                  22                  19                  19                  17
5                   1                   0                   2                   3
6                  12                  12                  12                  12
  2014-08-18 23:50:00 2014-08-19 00:00:00 2014-08-19 00:10:00 2014-08-19 00:20:00
1                  16                  16                  17                  19
2                   2                   2                   2                   1
3                   5                   6                   5                   5
4                  18                  19                  19                  20
5                   3                   0                   2                   6
6                  12                  12                  12                  12
  2014-08-19 00:30:00 2014-08-19 00:40:00 2014-08-19 00:50:00 2014-08-19 01:00:00
1                  20                  21                  22                  23
2                   1                   4                   3                   3
3                   3                   3                   3                   3
4                  20                  19                  20                  19
5                   0                   1                   2                   5
6                  12                  12                  12                  12
  2014-08-19 01:10:00 2014-08-19 01:20:00 2014-08-19 01:30:00 2014-08-19 01:40:00
1                  22                  23                  23                  21
2                   3                   4                   4                   4
3                   4                   4                   4                   4
4                  21                  24                  23                  24
5                   0                   3                   2                   1
6                  12                  12                  12                  12
  2014-08-19 01:50:00 2014-08-19 02:00:00 2014-08-19 02:10:00 2014-08-19 02:20:00
1                  22                  23                  22                  22
2                   3                   1                   1                   1
3                   4                   4                   4                   4
4                  24                  22                  21                  22
5                   0                   1                   2                   2
6                  12                  12                  12                  12
  2014-08-19 02:30:00 2014-08-19 02:40:00 2014-08-19 02:50:00 2014-08-19 03:00:00
1                  20                  22                  22                  22
2                   1                   1                   1                   1
3                   4                   4                   4                   4
4                  22                  24                  24                  23
5                   2                   3                   3                   3
6                  12                  12                  12                  12
  2014-08-19 03:10:00 2014-08-19 03:20:00 2014-08-19 03:30:00 2014-08-19 03:40:00
1                  22                  22                  21                  21
2                   1                   1                   1                   1
3                   4                   4                   4                   4
4                  23                  23                  23                  22
5                   4                   3                   3                   3
6                  12                  12                  12                  12
  2014-08-19 03:50:00 2014-08-19 04:00:00 2014-08-19 04:10:00 2014-08-19 04:20:00
1                  21                  21                  21                  21
2                   1                   1                   1                   1
3                   4                   4                   4                   4
4                  22                  22                  23                  23
5                   2                   3                   3                   3
6                  12                  12                  12                  12
  2014-08-19 04:30:00 2014-08-19 04:40:00 2014-08-19 04:50:00 2014-08-19 05:00:00
1                  21                  21                  21                  21
2                   1                   1                   1                   1
3                   4                   4                   4                   4
4                  23                  23                  23                  23
5                   5                   4                   4                   4
6                  12                  12                  12                  12
  2014-08-19 05:10:00 2014-08-19 05:20:00 2014-08-19 05:30:00 2014-08-19 05:40:00
1                  21                  21                  21                  21
2                   1                   1                   1                   1
3                   4                   4                   4                   4
4                  24                  24                  24                  24
5                   4                   4                   4                   4
6                  12                  12                  12                  12
  2014-08-19 05:50:00 2014-08-19 06:00:00 2014-08-19 06:10:00 2014-08-19 06:20:00
1                  21                  21                  21                  22
2                   1                   1                   1                   1
3                   4                   4                   4                   4
4                  24                  24                  24                  24
5                   4                   4                   4                   3
6                  12                  12                  12                  12
  2014-08-19 06:30:00 2014-08-19 06:40:00 2014-08-19 06:50:00 2014-08-19 07:00:00
1                  22                  22                  22                  22
2                   1                   1                   1                   1
3                   5                   5                   5                   5
4                  24                  24                  24                  24
5                   3                   4                   4                   4
6                  12                  12                  12                  12
  2014-08-19 07:10:00 2014-08-19 07:20:00 2014-08-19 07:30:00 2014-08-19 07:40:00
1                  22                  22                  22                  22
2                   6                   5                   5                   5
3                   5                   5                   5                   5
4                  24                  24                  24                  24
5                   4                   4                   4                   4
6                  12                  12                  12                  12
  2014-08-19 07:50:00
1                  22
2                   5
3                   5
4                  24
5                   4
6                  12

The final out put should look something like this (of course,the
actual number of columns will naturally be 73, but it was too much to put into the example).

> reshape2
  station_id 2014-08-18 20:00:00 2014-08-18 20:10:00 2014-08-18 20:20:00
1          1                   1                  -1                   0
2          2                  18                   0                   1
3          3                   5                  -1                   0
4          4                  21                  -1                   0
5          5                   9                   1                  -2
6          6                   9                   0                   0
  2014-08-18 20:30:00 2014-08-18 20:40:00
1                   2                  -1
2                  -1                   0
3                   0                   0
4                   1                   1
5                  -3                   2
6                   0                   0

How would one loop over all of the columns in R?

Here is a small sample of the data

> dput(sample)
structure(list(station_id = 1:6, `2014-08-18 20:00:00` = c(1L,
18L, 5L, 21L, 9L, 9L), `2014-08-18 20:10:00` = c(0L, 18L, 4L,
20L, 10L, 9L), `2014-08-18 20:20:00` = c(0L, 19L, 4L, 20L, 8L,
9L), `2014-08-18 20:30:00` = c(2L, 18L, 4L, 21L, 5L, 9L), `2014-08-18 20:40:00` = c(1L,
18L, 4L, 22L, 7L, 9L), `2014-08-18 20:50:00` = c(1L, 21L, 4L,
25L, 3L, 9L), `2014-08-18 21:00:00` = c(0L, 22L, 4L, 23L, 0L,
9L)), .Names = c("station_id", "2014-08-18 20:00:00", "2014-08-18 20:10:00", "2014-08-18 20:20:00", "2014-08-18 20:30:00", "2014-08-18 20:40:00", "2014-08-18 20:50:00", "2014-08-18 21:00:00"), row.names = c(NA,
6L), class = "data.frame")

Body:
How about something like:

t(apply(sample[,-1], 1, diff))


问:
SpringBoot Junit bean autowire
I try to write junit test to my service.
I use in my project spring-boot 1.5.1. Everything works fine, but when I try to autowire bean (created in AppConfig.class), it gives me NullPointerException. I've tried almost everything.

This is my configuration class:

```<code>@Configuration
public class AppConfig {

@Bean
public DozerBeanMapper mapper(){
    DozerBeanMapper mapper = new DozerBeanMapper();
    mapper.setCustomFieldMapper(new CustomMapper());
    return mapper;
 }
}
</code>```

and my test class:

```<code>@SpringBootTest
public class LottoClientServiceImplTest {
@Mock
SoapServiceBindingStub soapServiceBindingStub;
@Mock
LottoClient lottoClient;
@InjectMocks
LottoClientServiceImpl lottoClientService;
@Autowired
DozerBeanMapper mapper;

@Before
public void setUp() throws Exception {
    initMocks(this);
    when(lottoClient.soapService()).thenReturn(soapServiceBindingStub);
}

@Test
public void getLastResults() throws Exception {

    RespLastWyniki expected = Fake.generateFakeLastWynikiResponse();
    when(lottoClient.soapService().getLastWyniki(anyString())).thenReturn(expected);

    LastResults actual = lottoClientService.getLastResults();
</code>```

Can someone tells me what's wrong ?

Error log:

```<code>java.lang.NullPointerException
at pl.lotto.service.LottoClientServiceImpl.getLastResults(LottoClientServiceImpl.java:26)
at pl.lotto.service.LottoClientServiceImplTest.getLastResults(LottoClientServiceImplTest.java:45)
</code>```

and this is my service:

```<code>@Service
public class LottoClientServiceImpl implements LottoClientServiceInterface {
@Autowired
LottoClient lottoClient;
@Autowired
DozerBeanMapper mapper;
@Override
public LastResults getLastResults() {
    try {
        RespLastWyniki wyniki = lottoClient.soapService().getLastWyniki(new Date().toString());
        LastResults result = mapper.map(wyniki, LastResults.class);
        return result;
    } catch (RemoteException e) {
        throw new GettingDataError();
    }
}
</code>```

答:
Ofcourse your dependency will be null,due to the @InjectMocks you are creating a new instance, outside the visibility of Spring and as such nothing will be auto wired.

Spring Boot has extensive testing support and also for replacing beans with mocks, see the testing section of the Spring Boot reference guide.

To fix it work with the framework instead of around it.

Replace @Mock with @MockBean

Replace @InjectMocks with @Autowired

Remove your setup method

Also apparently you only need a mock for the SOAP stub (so not sure what you need to mock for the LottoClient for).

Something like this should do the trick.

```<code>@SpringBootTest
public class LottoClientServiceImplTest {

    @MockBean
    SoapServiceBindingStub soapServiceBindingStub;

    @Autowired
    LottoClientServiceImpl lottoClientService;

    @Test
    public void getLastResults() throws Exception {

        RespLastWyniki expected = Fake.generateFakeLastWynikiResponse();
        when(soapServiceBindingStub.getLastWyniki(anyString())).thenReturn(expected);

        LastResults actual = lottoClientService.getLastResults();
</code>```

Title: SpringBoot Junit bean autowire

Body:
I try to write junit test to my service.
I use in my project spring-boot 1.5.1. Everything works fine, but when I try to autowire bean (created in AppConfig.class), it gives me NullPointerException. I've tried almost everything.

This is my configuration class:

@Configuration
public class AppConfig {

@Bean
public DozerBeanMapper mapper(){
    DozerBeanMapper mapper = new DozerBeanMapper();
    mapper.setCustomFieldMapper(new CustomMapper());
    return mapper;
 }
}

and my test class:

@SpringBootTest
public class LottoClientServiceImplTest {
@Mock
SoapServiceBindingStub soapServiceBindingStub;
@Mock
LottoClient lottoClient;
@InjectMocks
LottoClientServiceImpl lottoClientService;
@Autowired
DozerBeanMapper mapper;

@Before
public void setUp() throws Exception {
    initMocks(this);
    when(lottoClient.soapService()).thenReturn(soapServiceBindingStub);
}

@Test
public void getLastResults() throws Exception {

    RespLastWyniki expected = Fake.generateFakeLastWynikiResponse();
    when(lottoClient.soapService().getLastWyniki(anyString())).thenReturn(expected);

    LastResults actual = lottoClientService.getLastResults();

Can someone tells me what's wrong ?

Error log:

java.lang.NullPointerException
at pl.lotto.service.LottoClientServiceImpl.getLastResults(LottoClientServiceImpl.java:26)
at pl.lotto.service.LottoClientServiceImplTest.getLastResults(LottoClientServiceImplTest.java:45)

and this is my service:

@Service
public class LottoClientServiceImpl implements LottoClientServiceInterface {
@Autowired
LottoClient lottoClient;
@Autowired
DozerBeanMapper mapper;
@Override
public LastResults getLastResults() {
    try {
        RespLastWyniki wyniki = lottoClient.soapService().getLastWyniki(new Date().toString());
        LastResults result = mapper.map(wyniki, LastResults.class);
        return result;
    } catch (RemoteException e) {
        throw new GettingDataError();
    }
}

Body:
Ofcourse your dependency will be null,due to the @InjectMocks you are creating a new instance, outside the visibility of Spring and as such nothing will be auto wired.

Spring Boot has extensive testing support and also for replacing beans with mocks, see the testing section of the Spring Boot reference guide.

To fix it work with the framework instead of around it.

Replace @Mock with @MockBean

Replace @InjectMocks with @Autowired

Remove your setup method

Also apparently you only need a mock for the SOAP stub (so not sure what you need to mock for the LottoClient for).

Something like this should do the trick.

@SpringBootTest
public class LottoClientServiceImplTest {

    @MockBean
    SoapServiceBindingStub soapServiceBindingStub;

    @Autowired
    LottoClientServiceImpl lottoClientService;

    @Test
    public void getLastResults() throws Exception {

        RespLastWyniki expected = Fake.generateFakeLastWynikiResponse();
        when(soapServiceBindingStub.getLastWyniki(anyString())).thenReturn(expected);

        LastResults actual = lottoClientService.getLastResults();


问:
Execute Code When The URL Has Hash OR HASH Changes After Load?
Any assistance would be greatly appreciated!

Execute code when a hash exists on load:

```<code>if(location.hash) { //code; }
</code>```

Execute code when the hash changes:

```<code>$(window).hashchange(function(){//code;});
</code>```

How do I combine these 2 checks?

This doesn't work:

```<code>if(location.hash || $(window).hashchange(function() { //code; });
</code>```

答:
Define a function for theCode, Pass its reference to hashchange event and on page load check if hash exists execute it directly

```<code>function theCode() { //code; }

if(location.hash){
    theCode();
}

$(window).hashchange(theCode);
</code>```

Body:
Any assistance would be greatly appreciated!

Execute code when a hash exists on load:

if(location.hash) { //code; }

Execute code when the hash changes:

$(window).hashchange(function(){//code;});

How do I combine these 2 checks?

This doesn't work:

if(location.hash || $(window).hashchange(function() { //code; });

Body:
Define a function for theCode, Pass its reference to hashchange event and on page load check if hash exists execute it directly

function theCode() { //code; }

if(location.hash){
    theCode();
}

$(window).hashchange(theCode);


问:
IgnoreReadOnlyRecommended not working from Python when opening Excel workbook
I have an excel workbook I need to open from python in a writable mode. The workbook is set up to have the prompt for a read only recommendation and this cannot be removed.

I am using the following:

```<code>import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
filepath = 'C:\Users\FullFilePath.xlsm'
xl.Workbooks.Open(Filename=filepath, ReadOnly=False, IgnoreReadOnlyRecommended=True)
</code>```

It opens the file, but it's still popping up the dialog asking if I want to open in read only. Is it possible to cancel that dialog?

答:
Use instead:

```<code>xl = win32com.client.DispatchEx('Excel.Application')
</code>```

This works without a dialog box for me.

Body:
I have an excel workbook I need to open from python in a writable mode. The workbook is set up to have the prompt for a read only recommendation and this cannot be removed.

I am using the following:

import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
filepath = 'C:\Users\FullFilePath.xlsm'
xl.Workbooks.Open(Filename=filepath, ReadOnly=False, IgnoreReadOnlyRecommended=True)

It opens the file, but it's still popping up the dialog asking if I want to open in read only. Is it possible to cancel that dialog?

Body:
Use instead:

xl = win32com.client.DispatchEx('Excel.Application')

This works without a dialog box for me.


问:
Reclaim string memory quickly (device with limited RAM)
I am writing a C# app for a device with limited ram. (Mono on iPhone/iPad)

When I assign a large string:

```<code>string xml = "10 meg xml string from REST service";
</code>```

then clear it

```<code>xml = null;
</code>```

Is with the GC free up that memory asap? Is there a way to make sure it's cleaned up. GC has a collect feature, but is this executed right away?

The problem is that I am downloading many large xml files in a loop and even though I am setting the string to null, memory use is growing.

答:
While I'm not a Mono expert, but some simple things to check.  While you noted that you are setting your variable to null, are you actually calling a .Close() or .Dispose() method as appropriate, or including the scope of the variable in question inside of a using block?

Could be a case of a problem where you're sticking around waiting for a finalizer (i.e. if you have a handle on an unmalaged resource like a file handle), or the variable is still stuck in scope for some reason.  This would result in increased memory pressure.

Ideally, handle opening your file one at a time in a method with explicitly clear variable scope in combination with a using block, thus ensuring that the appropriate finalizers, etc. are called even if an exception is thrown.

Hope that helps!

ContentLicense: CC BY-SA 4.0

Body:
I am writing a C# app for a device with limited ram. (Mono on iPhone/iPad)

When I assign a large string:

string xml = "10 meg xml string from REST service";

then clear it

xml = null;

Is with the GC free up that memory asap? Is there a way to make sure it's cleaned up. GC has a collect feature, but is this executed right away?

The problem is that I am downloading many large xml files in a loop and even though I am setting the string to null, memory use is growing.


问:
Quiz displays wrong score
I am trying to build the quiz application with javascipt only but it gives me the wrong score. I first initialised correct variable with 0 and then wanted to increment the correct variable with 1 every time when the correct answer is selected but it shows the wrong score. I tried really hard to find any error but unable to find one. Please someone help me to fix this code and I would also appreciate if someone can specify why it is showing the wrong score.

var questions, question, pos = 0,
  ch1, ch2, ch3, cho, storeval, correct = 0;

questions = [
  ["What is 10 + 4", "12", "14", "16", "B"],
  ["What is 7 x 3", "21", "22", "23", "A"],
  ["What is 20 - 9", "15", "13", "11", "C"],
  ["What is 8/2", "5", "4", "2", "B"]
];

question = document.getElementById('question');

function loadQ() {

  ch1 = questions[pos][1];
  ch2 = questions[pos][2];
  ch3 = questions[pos][3];

  question.innerHTML = questions[pos][0] + "
";
  question.innerHTML += "<input type='radio' name='choices' value='A'>" + ch1 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='B'>" + ch2 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='C'>" + ch3 + "
";
}

function submitAnswer() {
  cho = document.getElementsByName('choices');

  for (var i = 0; i < cho.length; i++) {
    if (cho[i].checked) {
      storeval = cho[i].value;
    }
    if (storeval == questions[pos][4]) {
      correct++;
    }
  }
  pos++;

  if (pos < questions.length) {
    loadQ();
  } else {
    question.innerHTML = "Your Score is " + correct;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Quiz</title>
</head>

<body onload="loadQ()">
  <div id="customize">
    <div id="question"></div>
    <input type="button" onclick="submitAnswer()" value="Submit">
  </div>
</body>

</html></code>```

答:
Instead of the for loop to grab the checked radio replace it with this. Add JQuery to your project it easier.</p>

```<code>function submitAnswer(){

        storeval = $('input[name=choices]:checked').val();

            if(storeval==questions[pos][4]) {
                correct++;
            }

            pos++;

            if (pos < questions.length){
            loadQ();
            } else  {
                question.innerHTML = "Your Score is " + correct ;
            }
    }
</code>```

Title: Quiz displays wrong score

Body:
I am trying to build the quiz application with javascipt only but it gives me the wrong score. I first initialised correct variable with 0 and then wanted to increment the correct variable with 1 every time when the correct answer is selected but it shows the wrong score. I tried really hard to find any error but unable to find one. Please someone help me to fix this code and I would also appreciate if someone can specify why it is showing the wrong score.

var questions, question, pos = 0,
  ch1, ch2, ch3, cho, storeval, correct = 0;

questions = [
  ["What is 10 + 4", "12", "14", "16", "B"],
  ["What is 7 x 3", "21", "22", "23", "A"],
  ["What is 20 - 9", "15", "13", "11", "C"],
  ["What is 8/2", "5", "4", "2", "B"]
];

question = document.getElementById('question');

function loadQ() {

  ch1 = questions[pos][1];
  ch2 = questions[pos][2];
  ch3 = questions[pos][3];

  question.innerHTML = questions[pos][0] + "
";
  question.innerHTML += "<input type='radio' name='choices' value='A'>" + ch1 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='B'>" + ch2 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='C'>" + ch3 + "
";
}

function submitAnswer() {
  cho = document.getElementsByName('choices');

  for (var i = 0; i < cho.length; i++) {
    if (cho[i].checked) {
      storeval = cho[i].value;
    }
    if (storeval == questions[pos][4]) {
      correct++;
    }
  }
  pos++;

  if (pos < questions.length) {
    loadQ();
  } else {
    question.innerHTML = "Your Score is " + correct;
  }
}

<!DOCTYPE html>

  <title>Quiz</title>

    <input type="button" onclick="submitAnswer()" value="Submit">

Body:
Instead of the for loop to grab the checked radio replace it with this. Add JQuery to your project it easier.

function submitAnswer(){

        storeval = $('input[name=choices]:checked').val();

            if(storeval==questions[pos][4]) {
                correct++;
            }

            pos++;

            if (pos < questions.length){
            loadQ();
            } else  {
                question.innerHTML = "Your Score is " + correct ;
            }
    }


问:
How can I clear a specific filter without clearing all filters?
Background:

I am creating an app that stores record of trainings that employees in a company took in table. I want to filter the rows of the table based on training name and/or employee name. I was able to figure out this first part, and I was able to create a button that clears all the filters and reloads the entire table using the clearFilters() function.

Problem:

I want to create two buttons that clear the filter selections one ("All Trainings") for the training name and one ("All Employees") for the employee name. To be more clear, when I click on the "All Trainings" button, I want to clear the filters on the training name, but not on the Employee name. This will become useful once I have a table with multiple fields that I want to filter, and I want to navigate the table without having to reset all fields every time.

I tried searching the functions available on Google App Maker, but there was nothing that seemed to be able to solve my problem. Any suggestions?

答:
Can you simply take 3 steps in your onClick handler?
(1) clear all filter
(2) set the employee name filter
(3) load data</p>


问:
Increasing the font size of only 1 axis value in an R plot
I was wondering how I can increase the font size of ONLY number "6" in my x-axis in the plot below? (Please see my R code below)

Here is my R code:

```<code>plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')

axis(side = 1, at = 1:10, font = 2)
</code>```

答:
Another solution</p>

```<code>plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')
axis(1, 1:10, labels = NA)
mtext(text = "6", side = 1, line = 1, at = 6, cex = 3, font = 2, padj = 0.5)
mtext(text = paste(c(1:5,7:10)), side = 1, line = 1,
                        at = c(1:5,7:10), cex = 1, font = 2, padj = 0.5)
</code>```

Body:
I was wondering how I can increase the font size of ONLY number "6" in my x-axis in the plot below? (Please see my R code below)

Here is my R code:

plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')

axis(side = 1, at = 1:10, font = 2)

Body:
Another solution

plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')
axis(1, 1:10, labels = NA)
mtext(text = "6", side = 1, line = 1, at = 6, cex = 3, font = 2, padj = 0.5)
mtext(text = paste(c(1:5,7:10)), side = 1, line = 1,
                        at = c(1:5,7:10), cex = 1, font = 2, padj = 0.5)


问:
Failing to POST NSData of PDF to server
I have an iPad application in which I need to send a server a PDF file, alongside two POST variables, a user ID and a job ID. I am using the code below to do this:

NSData *pdfData = [NSData dataWithContentsOfFile:currentPDFFileName];

```<code>    NSData *validPDF = [[NSString stringWithString:@"%PDF"] dataUsingEncoding: NSASCIIStringEncoding];
    if (!(pdfData && [[pdfData subdataWithRange:NSMakeRange(0, 4)] isEqualToData:validPDF]))
    {
        NSLog (@"Not valid");
    }

    NSLog (@"%@", currentPDFFileName);
    NSLog (@"%@", [currentPDFFileName lastPathComponent]);

    //create the body
    NSMutableData *body = [NSMutableData data];

    //create the POST vars
    NSString *jobID = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"jobid\"\r\n\r\n%@", job.jobID];
    NSString *userID = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userid\"\r\n\r\n%@", delegate.userID];
    NSString *pdf = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image_file\"; filename=\"%@\"\r\n", [currentPDFFileName lastPathComponent]];

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[jobID dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[userID dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[pdf dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/pdf\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:pdfData];

    NSMutableURLRequest *pdfRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]];
    [pdfRequest setValue:@"multipart/form-data; boundary=----foo" forHTTPHeaderField:@"Content-type"];
    [pdfRequest setHTTPMethod:@"POST"];
    [pdfRequest setHTTPBody:body];
    NSData *pdfDataReply;
    NSURLResponse *pdfResponse;
    NSError *pdfError;
    pdfDataReply = [NSURLConnection sendSynchronousRequest:pdfRequest returningResponse:&pdfResponse error:&pdfError];

    NSString *pdfResult = [[NSString alloc] initWithData:pdfDataReply encoding:NSASCIIStringEncoding];
    NSLog (@"%@", pdfResult);
</code>```

The people on the other end of the connection are saying that they are not receiving the PDF file. I have tried all the usual suspects such as trying to find any nil objects.

Would greatly appreciate if anyone could please lend a hand with this!

Thanks.
Ricky.

答: Turns out there was an issue with the boundaries. I needed to add one at the end, after pdfData was added. Thank you for your help.</p>

Title: Failing to POST NSData of PDF to server

Body:
I have an iPad application in which I need to send a server a PDF file, alongside two POST variables, a user ID and a job ID. I am using the code below to do this:

NSData *pdfData = [NSData dataWithContentsOfFile:currentPDFFileName];

    NSData *validPDF = [[NSString stringWithString:@"%PDF"] dataUsingEncoding: NSASCIIStringEncoding];
    if (!(pdfData && [[pdfData subdataWithRange:NSMakeRange(0, 4)] isEqualToData:validPDF]))
    {
        NSLog (@"Not valid");
    }

    NSLog (@"%@", currentPDFFileName);
    NSLog (@"%@", [currentPDFFileName lastPathComponent]);

    //create the body
    NSMutableData *body = [NSMutableData data];

    //create the POST vars
    NSString *jobID = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"jobid\"\r\n\r\n%@", job.jobID];
    NSString *userID = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userid\"\r\n\r\n%@", delegate.userID];
    NSString *pdf = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image_file\"; filename=\"%@\"\r\n", [currentPDFFileName lastPathComponent]];

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[jobID dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[userID dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[pdf dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/pdf\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:pdfData];

    NSMutableURLRequest *pdfRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]];
    [pdfRequest setValue:@"multipart/form-data; boundary=----foo" forHTTPHeaderField:@"Content-type"];
    [pdfRequest setHTTPMethod:@"POST"];
    [pdfRequest setHTTPBody:body];
    NSData *pdfDataReply;
    NSURLResponse *pdfResponse;
    NSError *pdfError;
    pdfDataReply = [NSURLConnection sendSynchronousRequest:pdfRequest returningResponse:&pdfResponse error:&pdfError];

    NSString *pdfResult = [[NSString alloc] initWithData:pdfDataReply encoding:NSASCIIStringEncoding];
    NSLog (@"%@", pdfResult);

The people on the other end of the connection are saying that they are not receiving the PDF file. I have tried all the usual suspects such as trying to find any nil objects.

Would greatly appreciate if anyone could please lend a hand with this!

Thanks.
Ricky.


问:
Use python struct.error to stop a function?
I'm trying to write a small function for my programm (python) which writes some data into a csv file. The input data is from an other file. Both files are opened!
The code for actual read- and writeprocess is:

```<code>while aux != '':
     data = f.read(4)
     data = unpack('I', data)
     data = list(data)
     writer.writerow(data)
else:
     print('done')
</code>```

This code works fine so far, but sometimes my input data doesn't have left 4 bytes at the end for the last readprocess, so it gives me the error "struct.error: unpack requires a string argument of length 4".

This is totally fine for me, i don't mind some dataloss at the end but this error stops my whole programm.
Is there a way to stop the function and return to the main programm if this error occours? Or just stop the while loop und go on with the "else:" part?

答:
This should do it:

```<code>try:
    data = unpack('I', data)
except struct.error as err:
    print(err)
</code>```

This way you'll know when there is a problem, but program execution will continue.

Do read up on Python error handling for the full story.

Body:
I'm trying to write a small function for my programm (python) which writes some data into a csv file. The input data is from an other file. Both files are opened!
The code for actual read- and writeprocess is:

while aux != '':
     data = f.read(4)
     data = unpack('I', data)
     data = list(data)
     writer.writerow(data)
else:
     print('done')

This code works fine so far, but sometimes my input data doesn't have left 4 bytes at the end for the last readprocess, so it gives me the error "struct.error: unpack requires a string argument of length 4".

This is totally fine for me, i don't mind some dataloss at the end but this error stops my whole programm.
Is there a way to stop the function and return to the main programm if this error occours? Or just stop the while loop und go on with the "else:" part?

Body:
This should do it:

try:
    data = unpack('I', data)
except struct.error as err:
    print(err)

This way you'll know when there is a problem, but program execution will continue.

Do read up on Python error handling for the full story.


问:
How to securely send additional data/parameters via $.ajax for filtering?
How to securely send additional data/parameters via $.ajax for filtering?

I'm trying to send additional data/parameters via $.ajax for additional filtering of a returning json. When sending a single term, my setup looks like this:

javascript:

```<code>$.ajax({
  url: "/source.php",
  dataType: "json",
  data: {
    term: request.term
  },
</code>```

Console:

```<code>GET .../source.php?term=valueA1
</code>```

PHP:

```<code>$term = trim(strip_tags($_GET['term']));
$term = preg_replace('/\s+/', ' ', $term);

$a_json = array();
$a_json_row = array();

$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);

if(preg_match("/[^\040\pL\pN_-]/u", $term)) {
  print $json_invalid;
  exit;
}

if ($data = $mysqli->query("SELECT * FROM accounts WHERE name LIKE '%$term%' OR code LIKE '%$term%'")) {
while($row = mysqli_fetch_array($data)) {
    ...
}
}
</code>```

Now, when adding/sending the additional data/parameters (if available) my setup looks like this:

```<code>$.ajax({
  url: "/source.php",
  dataType: "json",
  data: {
    term: request.term,
    tags: $('#input-newsearch-2').val()
  },
</code>```

.val() of $('#input-newsearch-2') can be:

```<code>$('#input-newsearch-2').val() =
$('#input-newsearch-2').val() = valueA1
$('#input-newsearch-2').val() = valueA1,valueA2
$('#input-newsearch-2').val() = valueA1,valueA2,valueA3
</code>```

... and so on.

Console:

```<code>GET source.php?term=valueA1&tags=
GET source.php?term=valueA2&tags=valueA1
GET source.php?term=valueA3&tags=valueA1%2CvalueA2
GET source.php?term=valueA4&tags=valueA1%2CvalueA2%2CvalueA3
</code>```

Is it possible to send a comma seperated array like this and how should the php look like to use tags for additional filtering (AND WHERE)?

Edit: This is not a dublicate to the referenced answer since I'm sending a possible array as second parameter. Also it doesn't answer hoe then to fetch it in php und how to use it in the query

答:
If you want it to be truly secure, you need to put the data inside the payload instead of in the URL or Query string.

See this relevant question: Send JSON data with jQuery

Body:
How to securely send additional data/parameters via $.ajax for filtering?

I'm trying to send additional data/parameters via $.ajax for additional filtering of a returning json. When sending a single term, my setup looks like this:

javascript:

$.ajax({
  url: "/source.php",
  dataType: "json",
  data: {
    term: request.term
  },

Console:

GET .../source.php?term=valueA1

PHP:

$term = trim(strip_tags($_GET['term']));
$term = preg_replace('/\s+/', ' ', $term);

$a_json = array();
$a_json_row = array();

$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);

if(preg_match("/[^\040\pL\pN_-]/u", $term)) {
  print $json_invalid;
  exit;
}

if ($data = $mysqli->query("SELECT * FROM accounts WHERE name LIKE '%$term%' OR code LIKE '%$term%'")) {
while($row = mysqli_fetch_array($data)) {
    ...
}
}

Now, when adding/sending the additional data/parameters (if available) my setup looks like this:

$.ajax({
  url: "/source.php",
  dataType: "json",
  data: {
    term: request.term,
    tags: $('#input-newsearch-2').val()
  },

.val() of $('#input-newsearch-2') can be:

$('#input-newsearch-2').val() =
$('#input-newsearch-2').val() = valueA1
$('#input-newsearch-2').val() = valueA1,valueA2
$('#input-newsearch-2').val() = valueA1,valueA2,valueA3

... and so on.

Console:

GET source.php?term=valueA1&tags=
GET source.php?term=valueA2&tags=valueA1
GET source.php?term=valueA3&tags=valueA1%2CvalueA2
GET source.php?term=valueA4&tags=valueA1%2CvalueA2%2CvalueA3

Is it possible to send a comma seperated array like this and how should the php look like to use tags for additional filtering (AND WHERE)?

Edit: This is not a dublicate to the referenced answer since I'm sending a possible array as second parameter. Also it doesn't answer hoe then to fetch it in php und how to use it in the query


问:
javascript download image which requires referer
The image I want to download returns 403 when I tried to download with javascript

but I can download image with python code like below. It adds referer to headers and downloads it.

```<code>req = urllib.request.Request(image_url, headers={"Referer": referer_url})
with urllib.request.urlopen(req) as response, open("image.jpg", "wb") as outfile:
    shutil.copyfileobj(response, outfile)
</code>```

Is javascript can download image like that ?

Javascript code I am trying with. Its react-native-fetch-blob libaray

```<code>export const saveToonImageToLocal = (url, imageName) => {
  return RNFetchBlob
    .config({
      path: dirs.DocumentDir + `${imageName}.jpg`,
      appendExt: 'jpg'
    })
    .fetch('GET', url, {})
    .then((res)=>{
      return res.path();
    })
    .catch((e)=>{
      console.log('error occurend during saving images');
    })
};
</code>```

答:
You can load images using javascript ajax calls and passing headers in it:</p>

```<code>  $.ajax({
     type:'GET',
     url:'https://example.com/someimage.png',
     headers: {'Referer': "http://somepage.com"},
     success:function(data){
        $('#someImage').attr('src',data);
     }
  });
</code>```

Body:
The image I want to download returns 403 when I tried to download with javascript

but I can download image with python code like below. It adds referer to headers and downloads it.

req = urllib.request.Request(image_url, headers={"Referer": referer_url})
with urllib.request.urlopen(req) as response, open("image.jpg", "wb") as outfile:
    shutil.copyfileobj(response, outfile)

Is javascript can download image like that ?

Javascript code I am trying with. Its react-native-fetch-blob libaray

export const saveToonImageToLocal = (url, imageName) => {
  return RNFetchBlob
    .config({
      path: dirs.DocumentDir + `${imageName}.jpg`,
      appendExt: 'jpg'
    })
    .fetch('GET', url, {})
    .then((res)=>{
      return res.path();
    })
    .catch((e)=>{
      console.log('error occurend during saving images');
    })
};

Body:
You can load images using javascript ajax calls and passing headers in it:

  $.ajax({
     type:'GET',
     url:'https://example.com/someimage.png',
     headers: {'Referer': "http://somepage.com"},
     success:function(data){
        $('#someImage').attr('src',data);
     }
  });


问:
How to group EXTJS 4.2.1 grid rows by a has many relationship?
I want to know if it is possible to group an extjs grid by a column set in a hasMany element of a store. My example isn't thorough enough to re-create anything, but I'm only looking for a yes, here is an example, or a no. Thanks!

I have an extjs store set up that populates a UI for a library book. There is a hasMany relationship in the bookStore that points to a model representing each time the book was checked out. This hasMany model is bound to a gridpanel in the Book's UI showing a list of checkouts.

I want to group the gridpanel rows by which library member checked out the book (say 3 users checked it out twice each, currently I have 6 rows with memberName and checkoutDate. I want to group those rows by memberName showing three headers each with two rows below them showing checkoutDate).

I can't make it work no matter which configurations I try, even custom groupFields, and different ways of referencing 'child' objects from a store (eg
ExtJS 6 grid group by associated models )

This is roughly what the model's look like just to help clarify my explanation. I know this might not be exactly syntactically correct, but I'm just trying to find out if my goal is possible and what approaches I could take.

```<code>Ext.define('Book.model.BookModel', {
    extend : 'Ext.data.Model',
    alias  : 'model.BookModel',
    fields : [{
        name: 'Title',
        type: 'String'
    }],
    hasMany:[{
        name: 'checkouts',
        model: 'Book.model.Checkouts'
    }]
});

Ext.define('Book.model.Checkouts', {
    extend : 'Ext.data.Model',
    alias  : 'model.Checkouts',
    fields: [{
        name: 'Name',
        type: 'string'
    },{
        name: 'checkoutDate',
        type: 'date'
    }],
    associations : [{
        model: 'Book.store.BookStore',
        type : 'belongsTo',
        name: 'bookStore'
    }]
});

Ext.define('Book.store.BookStore', {
extend: 'Ext.data.Store',
model : 'Book.model.BookModel',
groupField: '????',
//etc.
});
</code>```

Config I've attempted:

--in the store:

```<code>groupField: 'Checkouts.Name',

groupField: 'checkouts.Name',
</code>```

--in the grid config:

```<code>groupers: [{ftype:'grouping'}],
groupers:  [{
                      property: 'Checkouts.name',//and with checkouts.name
                      root: 'data',
                      groupFn: function (val) {
                         return val === val ? val : '';
                    }
           }]
</code>```

答: So far it seems that doing this with grouping is impossible, but there are several other potential grid solutions/plugins that may work, like one of the types of Summary Grid, or Tree Grid. Another option besides two separate stores might be something like what is in the Data Binding examples.</p>

Body:
I want to know if it is possible to group an extjs grid by a column set in a hasMany element of a store. My example isn't thorough enough to re-create anything, but I'm only looking for a yes, here is an example, or a no. Thanks!

I have an extjs store set up that populates a UI for a library book. There is a hasMany relationship in the bookStore that points to a model representing each time the book was checked out. This hasMany model is bound to a gridpanel in the Book's UI showing a list of checkouts.

I want to group the gridpanel rows by which library member checked out the book (say 3 users checked it out twice each, currently I have 6 rows with memberName and checkoutDate. I want to group those rows by memberName showing three headers each with two rows below them showing checkoutDate).

I can't make it work no matter which configurations I try, even custom groupFields, and different ways of referencing 'child' objects from a store (eg
ExtJS 6 grid group by associated models )

This is roughly what the model's look like just to help clarify my explanation. I know this might not be exactly syntactically correct, but I'm just trying to find out if my goal is possible and what approaches I could take.

Ext.define('Book.model.BookModel', {
    extend : 'Ext.data.Model',
    alias  : 'model.BookModel',
    fields : [{
        name: 'Title',
        type: 'String'
    }],
    hasMany:[{
        name: 'checkouts',
        model: 'Book.model.Checkouts'
    }]
});

Ext.define('Book.model.Checkouts', {
    extend : 'Ext.data.Model',
    alias  : 'model.Checkouts',
    fields: [{
        name: 'Name',
        type: 'string'
    },{
        name: 'checkoutDate',
        type: 'date'
    }],
    associations : [{
        model: 'Book.store.BookStore',
        type : 'belongsTo',
        name: 'bookStore'
    }]
});

Ext.define('Book.store.BookStore', {
extend: 'Ext.data.Store',
model : 'Book.model.BookModel',
groupField: '????',
//etc.
});

Config I've attempted:

--in the store:

groupField: 'Checkouts.Name',

groupField: 'checkouts.Name',

--in the grid config:

groupers: [{ftype:'grouping'}],
groupers:  [{
                      property: 'Checkouts.name',//and with checkouts.name
                      root: 'data',
                      groupFn: function (val) {
                         return val === val ? val : '';
                    }
           }]


问:
JQuery call function and multiple params from string
If I have a function:

```<code>function myfunc(param1, param2, param3) {
  // ...
}
</code>```

and I have a string:

```<code>var myCall = "myfunc(1, 'abc', 'true')"
</code>```

Is there a way to make the function call using the string and include the params?  I don't know the number of parameters in advance.
I have tried

```<code>var func = myCall.substr(0, myCall.indexOf('('));
var args = myCall.substring(myCall.indexOf('(')+1, myCall.length-1);
window[func](args.split(','));
</code>```

but that just calls the function with an array to the first parameter.  How do I split the arguments and pass them in with an unknown number of parameters?

答:
You can use .replace() again with RegExp /\(.*/ to replace all characters except for function name, .replace() with RegExp /^\w+(?=\))|[()]/ to remove function name and parenthesis from string, .match() with RegExp /[\w\d]+/g to match digit or word characters, .map() to return digit or word characters within an array, Function.prototype.apply() to pass array to function call

```<code>function myfunc(param1, param2, param3) {
  console.log(param1, param2, param3)
}

var myCall = "myfunc(1, 'abc', 'true')";

var fn = myCall.replace(/\(.*/, "");

var params = myCall.replace(/^\w+(?=\))|[()]/, "")
             .match(/[\w\d]+/g).map(function(param) {
               return /\d/.test(param) ? +param : param
             });

window[fn].apply(null, params);
</code>```

Body:
If I have a function:

function myfunc(param1, param2, param3) {
  // ...
}

and I have a string:

var myCall = "myfunc(1, 'abc', 'true')"

Is there a way to make the function call using the string and include the params?  I don't know the number of parameters in advance.
I have tried

var func = myCall.substr(0, myCall.indexOf('('));
var args = myCall.substring(myCall.indexOf('(')+1, myCall.length-1);
window[func](args.split(','));

but that just calls the function with an array to the first parameter.  How do I split the arguments and pass them in with an unknown number of parameters?

Body:
You can use .replace() again with RegExp /\(.*/ to replace all characters except for function name, .replace() with RegExp /^\w+(?=\))|[()]/ to remove function name and parenthesis from string, .match() with RegExp /[\w\d]+/g to match digit or word characters, .map() to return digit or word characters within an array, Function.prototype.apply() to pass array to function call

function myfunc(param1, param2, param3) {
  console.log(param1, param2, param3)
}

var myCall = "myfunc(1, 'abc', 'true')";

var fn = myCall.replace(/\(.*/, "");

var params = myCall.replace(/^\w+(?=\))|[()]/, "")
             .match(/[\w\d]+/g).map(function(param) {
               return /\d/.test(param) ? +param : param
             });

window[fn].apply(null, params);


问:
default assignment operator
Is there default assignment operator in c#?</p>

答:
Unlike C++, C# does not allow you to override the assignment operator.

For reference types, writing x = y will set x to refer to the same object (or null) that y does.

For value types, writing x = y will copy the fields in the y value to the x value.

Title: default assignment operator


问:
How To Resize A Div & Keep The Aspect Ratio
I have a div that will have a background image of the size 1170px x 929px. As I resize the width i.e. shrink it, I would like the height to also shrink so that the aspect ratio is kept. Can someone explain how this can be done using CSS? All I have so far is the following

```<code><section class="box">
            <article class="container ">
                <div class="content margin_tp_80 margin_bm_40 map_london">
                </div>
            </article>
        </section>
</code>```

Any help would be great thanks.

答:
This could be what you are looking for, the width and height always keep the same ratio

.box{
  position: relative;
 width: 100%; //width of your background image
  }
 .box:before{
  content: "";
 display: block;
 padding-top: 79.4%; //the ration (929/1170)*100
  }
  .container {
 position: absolute;
 top: 0;
 left: 0;
 bottom: 0;
 right: 0;
 background-color: #f1f1f1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="box">
      <article class="container">
          <div class="content margin_tp_80 margin_bm_40 map_london">
          </div>
      </article>
</section></code>```

Body:
I have a div that will have a background image of the size 1170px x 929px. As I resize the width i.e. shrink it, I would like the height to also shrink so that the aspect ratio is kept. Can someone explain how this can be done using CSS? All I have so far is the following

Any help would be great thanks.

Body:
This could be what you are looking for, the width and height always keep the same ratio

.box{
  position: relative;
 width: 100%; //width of your background image
  }
 .box:before{
  content: "";
 display: block;
 padding-top: 79.4%; //the ration (929/1170)*100
  }
  .container {
 position: absolute;
 top: 0;
 left: 0;
 bottom: 0;
 right: 0;
 background-color: #f1f1f1;
}

<section class="box">
      <article class="container">
          <div class="content margin_tp_80 margin_bm_40 map_london">
          </div>
      </article>
</section>


问:
Listing only the last version of a row in a composite key
I'm having a little bit of trouble understanding how composite keys are supposed to work with Entity Framework or SQL in general.

This is how my table looks like:

```<code>COD_ITEM    COD_ITEM_VERSION    ITEM_NAME
1           1                   A
1           2                   A
1           3                   A
2           1                   A
2           2                   A
2           3                   A
2           4                   A
2           5                   A
3           1                   A
</code>```

I need to list those items, but only the last version of each one... so I'd have this output:

```<code>COD_ITEM    COD_ITEM_VERSION    ITEM_NAME
1           3                   A
2           5                   A
3           1                   A
</code>```

I tried this but it didn't work, and it throws an error if the table is empty.

```<code>db.T_ITEMS.GroupBy(r => r.COD_ITEM).Last().ToList();
</code>```

How can I do this? My mind is completely blank right now.

答:
I think you are looking this:

```<code>var result=db.T_ITEMS.GroupBy(r => r.COD_ITEM)
                     .Select(g=>g.OrderByDescending(r=>r.COD_ITEM_VERSION).FirstOrDefault())
                     .ToList();
</code>```

After you group, order by (in descending order) COD_ITEM_VERSION each group to get just the last one

Body:
I'm having a little bit of trouble understanding how composite keys are supposed to work with Entity Framework or SQL in general.

This is how my table looks like:

COD_ITEM    COD_ITEM_VERSION    ITEM_NAME
1           1                   A
1           2                   A
1           3                   A
2           1                   A
2           2                   A
2           3                   A
2           4                   A
2           5                   A
3           1                   A

I need to list those items, but only the last version of each one... so I'd have this output:

COD_ITEM    COD_ITEM_VERSION    ITEM_NAME
1           3                   A
2           5                   A
3           1                   A

I tried this but it didn't work, and it throws an error if the table is empty.

db.T_ITEMS.GroupBy(r => r.COD_ITEM).Last().ToList();

How can I do this? My mind is completely blank right now.

Body:
I think you are looking this:

var result=db.T_ITEMS.GroupBy(r => r.COD_ITEM)
                     .Select(g=>g.OrderByDescending(r=>r.COD_ITEM_VERSION).FirstOrDefault())
                     .ToList();

After you group, order by (in descending order) COD_ITEM_VERSION each group to get just the last one


问:
KDBG debugger run with redirected input
Im trying to debug my AT&T assembly code with KDBG with redirected input for stdin but this doesnt work.

```<code>kdbg program1 < mydata.txt
</code>```

tried also

```<code>cat mydata.txt | kdbg program1
</code>```

any advices?

答:
Select Execution->Arguments, then put the following in the Run program1 with these arguments box:

```<code>< mydata.txt
</code>```

I also strongly suggest that you switch to Working Directory in that dialog and fill in the directory. This ensures that the program is run in the correct directory and actually finds mydata.txt.

Title: KDBG debugger run with redirected input

Body:
Im trying to debug my AT&T assembly code with KDBG with redirected input for stdin but this doesnt work.

kdbg program1 < mydata.txt

tried also

cat mydata.txt | kdbg program1

any advices?

Body:
Select Execution->Arguments, then put the following in the Run program1 with these arguments box:

< mydata.txt

I also strongly suggest that you switch to Working Directory in that dialog and fill in the directory. This ensures that the program is run in the correct directory and actually finds mydata.txt.


问:
How would one go about making this grid clickable?
I've created the grid below using a canvas as well as lines going through it, how would one go about making this grid clickable?

The ideal result would be when I click one of the boxes it turns yellow, and a value inside an array would be changed from 0 to 1. I'm fairly certain I know how to set up a 2D array but that is the general idea. Thanks for any help.

```<code>var cellCount=20;
var currentGrid = new Array(cellCount).fill().map(() => new Array(cellCount).fill(0));
var nextGrid = new Array(cellCount).fill().map(() => new Array(cellCount).fill(0));

for(var i=0;i<20;i++){
    for(var j=0;j<20;j++){
        currentGrid[i][j]=0;
        nextGrid[i][j]=0;
    }
}

var canvas=document.getElementById('grid');
var ctx=canvas.getContext('2d');

function drawGrid(h,w,id){
    for(var x=0;x<w;x++){
        ctx.moveTo(0,x*20);
        ctx.lineTo(h,x*20);
        ctx.lineWidth=1;
        ctx.strokeStyle='rgb(211,211,211)';
        ctx.stroke();
    }
    for(var y=0;y<h;y++){
        ctx.moveTo(y*20,0);
        ctx.lineTo(y*20,w);
        ctx.lineWidth=1;
        ctx.strokeStyle='rgb(211,211,211)';
        ctx.stroke();
    }
}

function getPosition(event)
  {

    if (event.x != undefined && event.y != undefined)
    {
      x = event.x;
      y = event.y;
    }

  }

  canvas.addEventListener("mousedown", getPosition, false);

drawGrid(421,421,'grid');
</code>```

答:
Looking at the code you provided, it appears there is no loop, meaning there will be no other updates to the grid visually.  Also, the draw function appears that it would draw offscreen, as you are multiplying your values by 20, which should probably be cellCount.

First I would recommend setting up a 'game loop'. A pattern that involves updating and drawing in a loop:

```<code>function loop(tick) {
  update(tick);
  draw(tick);
  requestAnimationFrame(loop);
}
// start the loop
requestAnimationFrame(loop);
</code>```

Then you'll need to define the update and draw function.  In this example you may not have anything to update yet, but you might in the future.  The draw function would first erase the background and then draw the grid:

```<code>function draw(tick) {
  // clear background
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // draw the grid
  drawGrid(numCols, numRows);
}
</code>```

Now you'll need to define numCols and numRows which is simply the width or height divided by the cellSize.  This tells you how many cells in the height and width of the canvas.  I see you have cellCount instead of cellSize, but cellSize can be calculated the opposite way by taking canvas height (or width) and dividing it by cellCount (assuming the canvas is square).

```<code> var numCols = Math.floor(canvas.width / cellSize);
 var numRows = Math.floor(canvas.height / cellSize);
</code>```

As for the click handler; you'll want to figure out which cell they clicked in by dividing the x and y you've captured by the cellSize.

```<code> // assuming x and y are the coordinates on the canvas where the user clicked
 var cellX = Math.floor(x / cellSize);
 var cellY = Math.floor(y / cellSize);
 // now set the cell
 nextGrid[cellY][cellX] = 1;
</code>```

Body:
I've created the grid below using a canvas as well as lines going through it, how would one go about making this grid clickable?

The ideal result would be when I click one of the boxes it turns yellow, and a value inside an array would be changed from 0 to 1. I'm fairly certain I know how to set up a 2D array but that is the general idea. Thanks for any help.

var cellCount=20;
var currentGrid = new Array(cellCount).fill().map(() => new Array(cellCount).fill(0));
var nextGrid = new Array(cellCount).fill().map(() => new Array(cellCount).fill(0));

for(var i=0;i<20;i++){
    for(var j=0;j<20;j++){
        currentGrid[i][j]=0;
        nextGrid[i][j]=0;
    }
}

var canvas=document.getElementById('grid');
var ctx=canvas.getContext('2d');

function drawGrid(h,w,id){
    for(var x=0;x<w;x++){
        ctx.moveTo(0,x*20);
        ctx.lineTo(h,x*20);
        ctx.lineWidth=1;
        ctx.strokeStyle='rgb(211,211,211)';
        ctx.stroke();
    }
    for(var y=0;y<h;y++){
        ctx.moveTo(y*20,0);
        ctx.lineTo(y*20,w);
        ctx.lineWidth=1;
        ctx.strokeStyle='rgb(211,211,211)';
        ctx.stroke();
    }
}

function getPosition(event)
  {

    if (event.x != undefined && event.y != undefined)
    {
      x = event.x;
      y = event.y;
    }

  }

  canvas.addEventListener("mousedown", getPosition, false);

drawGrid(421,421,'grid');

Body:
Looking at the code you provided, it appears there is no loop, meaning there will be no other updates to the grid visually.  Also, the draw function appears that it would draw offscreen, as you are multiplying your values by 20, which should probably be cellCount.

First I would recommend setting up a 'game loop'. A pattern that involves updating and drawing in a loop:

function loop(tick) {
  update(tick);
  draw(tick);
  requestAnimationFrame(loop);
}
// start the loop
requestAnimationFrame(loop);

Then you'll need to define the update and draw function.  In this example you may not have anything to update yet, but you might in the future.  The draw function would first erase the background and then draw the grid:

function draw(tick) {
  // clear background
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // draw the grid
  drawGrid(numCols, numRows);
}

Now you'll need to define numCols and numRows which is simply the width or height divided by the cellSize.  This tells you how many cells in the height and width of the canvas.  I see you have cellCount instead of cellSize, but cellSize can be calculated the opposite way by taking canvas height (or width) and dividing it by cellCount (assuming the canvas is square).

 var numCols = Math.floor(canvas.width / cellSize);
 var numRows = Math.floor(canvas.height / cellSize);

As for the click handler; you'll want to figure out which cell they clicked in by dividing the x and y you've captured by the cellSize.

 // assuming x and y are the coordinates on the canvas where the user clicked
 var cellX = Math.floor(x / cellSize);
 var cellY = Math.floor(y / cellSize);
 // now set the cell
 nextGrid[cellY][cellX] = 1;


问:
How do I make an SSL socket available between functions?
This is my class:

```<code>  class SSLIRC : public Bot
            {
              public:
                      SSLIRC(void);
                      void sockconnect(char*, int, bool);
                      void sockwrite(char*);
                      std::string sockread(void);
                      bool connected;
                      bool verbose;
              private:
                      WSADATA wsaData;
                      SOCKET m_socket;
                      sockaddr_in clientService;
                      LPHOSTENT hostEntry;

             };
</code>```

and this is my SSLIRC::sockconnect

```<code>void SSLIRC::sockconnect(char* hName, int portNum, bool debug)
{
    verbose = debug;
    SSL *sslSocket = 0;
    SSL_CTX *sslContext = 0;
    int error = WSAStartup(MAKEWORD(2,0),&wsaData);

    if (error != NO_ERROR)
        std::cout << "Client: Error at WSAStartup().\n";
    else
        std::cout << "Client: WSAStartup() is OK.\n";

    fflush(stdout);

    // socket
    int socket = 0;
    // struct for socket
    struct sockaddr_in host_addr = {0};
    //information about host
    struct hostent *host = {0};
    // name of host

    host = gethostbyname(hName);
    if (host == NULL)
    {
      printf("Unknown Host %s\n", hName);
      exit (0);
    }
    // create socket
    // for SSL need SOCK_STREAM socket
    socket = ::socket(PF_INET, SOCK_STREAM, 0);
    if (socket < 0)
    {
      printf("Socket Error\n");
      exit (0);
    }

    // create host struct
    host_addr.sin_family = AF_INET;
    // set IP addres
    host_addr.sin_addr = *((struct in_addr *)host->h_addr);
    // set HTTPS port
    host_addr.sin_port = htons(portNum);
    // connet
    if (connect(socket, (struct sockaddr *)&host_addr, sizeof(host_addr)) == -1)
    {
      closesocket(socket);
      printf("Connection Error\n");
      exit (0);
    }

    sslContext = SSL_CTX_new(SSLv23_client_method());
    sslSocket = SSL_new(sslContext);

    if(!sslSocket)
    {
      closesocket(socket);
      printf("SSL creation error\n");
      exit(0);
    }
    // join sslSocket and socket
    SSL_set_fd(sslSocket, socket);
    // conect sslSocket
    error = SSL_connect(sslSocket);
    if(!error)
    {
      closesocket(socket);
      printf("SSL connect error = %d\n", error);
      error = SSL_get_error(sslSocket, error);
      printf("SSL error: %d\n", error);
      exit (0);
    }

  printf("SSL handshake established.\n");

}
</code>```

How do I declare sslSocket so it's available in my class for the other functions to use?

答:
I would put sslSocket in the header like so:

```<code>class SSLIRC : public Bot
{
public:
    SSLIRC(void);
    void sockconnect(char*, int, bool);
    void sockwrite(char*);
    std::string sockread(void);
    bool connected;
    bool verbose;
private:
    WSADATA wsaData;
    SOCKET m_socket;
    sockaddr_in clientService;
    LPHOSTENT hostEntry;
    SSL *sslSocket;
    int socket;
};
</code>```

This way sslSocket and socket are available for the entire instance of the class to use, but not available outside of the class. Then, if you wanted a send_data method this method could use this->socket or this->sslSocket as required.

You could init these sockets in the method:

```<code>SSLIRC::SSLIRC()
{
    this->socket = 0;
    this->sslSocket = 0;
}
</code>```

i.e. in the constructor. This is the usual practise.

Body:
This is my class:

  class SSLIRC : public Bot
            {
              public:
                      SSLIRC(void);
                      void sockconnect(char*, int, bool);
                      void sockwrite(char*);
                      std::string sockread(void);
                      bool connected;
                      bool verbose;
              private:
                      WSADATA wsaData;
                      SOCKET m_socket;
                      sockaddr_in clientService;
                      LPHOSTENT hostEntry;

             };

and this is my SSLIRC::sockconnect

void SSLIRC::sockconnect(char* hName, int portNum, bool debug)
{
    verbose = debug;
    SSL *sslSocket = 0;
    SSL_CTX *sslContext = 0;
    int error = WSAStartup(MAKEWORD(2,0),&wsaData);

    if (error != NO_ERROR)
        std::cout << "Client: Error at WSAStartup().\n";
    else
        std::cout << "Client: WSAStartup() is OK.\n";

    fflush(stdout);

    // socket
    int socket = 0;
    // struct for socket
    struct sockaddr_in host_addr = {0};
    //information about host
    struct hostent *host = {0};
    // name of host

    host = gethostbyname(hName);
    if (host == NULL)
    {
      printf("Unknown Host %s\n", hName);
      exit (0);
    }
    // create socket
    // for SSL need SOCK_STREAM socket
    socket = ::socket(PF_INET, SOCK_STREAM, 0);
    if (socket < 0)
    {
      printf("Socket Error\n");
      exit (0);
    }

    // create host struct
    host_addr.sin_family = AF_INET;
    // set IP addres
    host_addr.sin_addr = *((struct in_addr *)host->h_addr);
    // set HTTPS port
    host_addr.sin_port = htons(portNum);
    // connet
    if (connect(socket, (struct sockaddr *)&host_addr, sizeof(host_addr)) == -1)
    {
      closesocket(socket);
      printf("Connection Error\n");
      exit (0);
    }

    sslContext = SSL_CTX_new(SSLv23_client_method());
    sslSocket = SSL_new(sslContext);

    if(!sslSocket)
    {
      closesocket(socket);
      printf("SSL creation error\n");
      exit(0);
    }
    // join sslSocket and socket
    SSL_set_fd(sslSocket, socket);
    // conect sslSocket
    error = SSL_connect(sslSocket);
    if(!error)
    {
      closesocket(socket);
      printf("SSL connect error = %d\n", error);
      error = SSL_get_error(sslSocket, error);
      printf("SSL error: %d\n", error);
      exit (0);
    }

  printf("SSL handshake established.\n");

}

How do I declare sslSocket so it's available in my class for the other functions to use?

Body:
I would put sslSocket in the header like so:

class SSLIRC : public Bot
{
public:
    SSLIRC(void);
    void sockconnect(char*, int, bool);
    void sockwrite(char*);
    std::string sockread(void);
    bool connected;
    bool verbose;
private:
    WSADATA wsaData;
    SOCKET m_socket;
    sockaddr_in clientService;
    LPHOSTENT hostEntry;
    SSL *sslSocket;
    int socket;
};

This way sslSocket and socket are available for the entire instance of the class to use, but not available outside of the class. Then, if you wanted a send_data method this method could use this->socket or this->sslSocket as required.

You could init these sockets in the method:

SSLIRC::SSLIRC()
{
    this->socket = 0;
    this->sslSocket = 0;
}

i.e. in the constructor. This is the usual practise.


问:
SSIS - Derived Columns - Case Statment - Charindex and Substring
I've the fololwing transformation in T-SQL:

```<code>SELECT [FIELD_A] = case when CHARINDEX('-', FIELD_B)>0 then LEFT(FIELD_B,CHARINDEX('-', FIELD_B)-1)
    else FIELD_B end,
</code>```

How can I put this into a expression in Derived Column object using SQL Server Integration Services 2014?

Regards!!!

答:
Derived Column transformations use SSIS Expression syntax.  The syntax for this would work something like this:

```<code>FINDSTRING(FIELD_B, "-", 1) > 0 ? LEFT(FIELD_B, FINDSTRING(FIELD_B, "-", 1)-1) : FIELD_B
</code>```

I haven't tested it, but it should get you going down the right path.  To walk through it:

FINDSTRING takes 3 values - what text you want to search in, what text you want to search for, and which occurrence you want to find.

The "If" logic in SSIS expressions is the ? and : symbols.  The ? follows the "If" boolean expression, and the : separates the "If true" and "If False" expressions.

Literal strings in SSIS Expressions need double-quotes around them.

Findstring reference:  https://learn.microsoft.com/en-us/sql/integration-services/expressions/findstring-ssis-expression

Conditional reference:  https://learn.microsoft.com/en-us/sql/integration-services/expressions/conditional-ssis-expression

Body:
I've the fololwing transformation in T-SQL:

SELECT [FIELD_A] = case when CHARINDEX('-', FIELD_B)>0 then LEFT(FIELD_B,CHARINDEX('-', FIELD_B)-1)
    else FIELD_B end,

How can I put this into a expression in Derived Column object using SQL Server Integration Services 2014?

Regards!!!

Body:
Derived Column transformations use SSIS Expression syntax.  The syntax for this would work something like this:

FINDSTRING(FIELD_B, "-", 1) > 0 ? LEFT(FIELD_B, FINDSTRING(FIELD_B, "-", 1)-1) : FIELD_B

I haven't tested it, but it should get you going down the right path.  To walk through it:

FINDSTRING takes 3 values - what text you want to search in, what text you want to search for, and which occurrence you want to find.

The "If" logic in SSIS expressions is the ? and : symbols.  The ? follows the "If" boolean expression, and the : separates the "If true" and "If False" expressions.

Literal strings in SSIS Expressions need double-quotes around them.

Findstring reference:  https://learn.microsoft.com/en-us/sql/integration-services/expressions/findstring-ssis-expression

Conditional reference:  https://learn.microsoft.com/en-us/sql/integration-services/expressions/conditional-ssis-expression


问:
In background script, browser.tabs.create opens the page but displays Error: No window matching {"matchesHost":["<all_urls>"]}
My  usecase is pretty simple:

Click a browserAction icon on toolbar

Listen the click in background script

Create a new tab with a page present in same directory as manifest.json

The said page has javascript file associated in

 after script

```

<p><strong>tabApp.js</strong></p>

```     //a simple console message
    console.log("hello from the other end");
```

<p><strong>Output</strong></p>

```- Message from backgroundjs.  background.js:8:2
- hello from the other end  tabApp.js:3:1
- Error: No window matching {"matchesHost":["<all_urls>"]}  (unknown)
```

The output is expected except the Error: No window matching {"matchesHost":["<all_urls>"]}. I am not sure what causes this error.

I have done following things to debug till now

added the  permission

Please give your inputs

答:
Can you please check what is the output of

```<code>console.log(browser.runtime.getURL("../tab/html/app.html")
</code>```

It looks like relative path is not from the manifest.json (https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/getURL)

Body:
My  usecase is pretty simple:

Click a browserAction icon on toolbar

Listen the click in background script

Create a new tab with a page present in same directory as manifest.json

The said page has javascript file associated in

 after script

tabApp.js

     //a simple console message
    console.log("hello from the other end");

Output

- Message from backgroundjs.  background.js:8:2
- hello from the other end  tabApp.js:3:1
- Error: No window matching {"matchesHost":["<all_urls>"]}  (unknown)

The output is expected except the Error: No window matching {"matchesHost":["<all_urls>"]}. I am not sure what causes this error.

I have done following things to debug till now

added the  permission

Please give your inputs

Body:
Can you please check what is the output of

console.log(browser.runtime.getURL("../tab/html/app.html")

It looks like relative path is not from the manifest.json (https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/getURL)


问:
Python beautifulsoup 4 selecting a class
I am trying to make a tool to automate sneaker purchase. And I am trying to check availability of sneakers online. I am new to programming and this is my first project. Thank you.

```<code>def CheckStock(url, model):
  url = "http://www.adidas.com/us/pureboost-ltd-shoes/S80701.html?pr=product_rr&slot=3"
  headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
  html = requests.get(url, headers=headers)
  page = bs4.BeautifulSoup(html.text, "lxml")
  Sizes = page.select('.size-dropdown-block')
  Sizes[0].getText()
</code>```

I know that the page is being selected because I use the command page.title.string and It shows the right title. I am getting the following error when attepmtng to execute Sizes.

```<code>Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    x[0].getText()
IndexError: list index out of range
</code>```

答:
Sizes is blue(it might be a function/methods use a different name for now)
Check if the (.size-dropdown-block) exists in the source code.
CTRL+U (most browsers) or right click > View page source.
It might be javascript generated. IF it is, you'll have to use Selenium or another other automated browser.</p>

Body:
I am trying to make a tool to automate sneaker purchase. And I am trying to check availability of sneakers online. I am new to programming and this is my first project. Thank you.

def CheckStock(url, model):
  url = "http://www.adidas.com/us/pureboost-ltd-shoes/S80701.html?pr=product_rr&slot=3"
  headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
  html = requests.get(url, headers=headers)
  page = bs4.BeautifulSoup(html.text, "lxml")
  Sizes = page.select('.size-dropdown-block')
  Sizes[0].getText()

I know that the page is being selected because I use the command page.title.string and It shows the right title. I am getting the following error when attepmtng to execute Sizes.

Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    x[0].getText()
IndexError: list index out of range


问:
MySQL query to extract email neighborhood
I have a MySQL table called personxmessage, extracted from emails.  It has three fields, id (primary key), MessageID, and PersonID.  For each message referenced by MessageID, there are two or more records, each with a PersonID for a person who was included in the email (i.e. in sender, sent to, or cc).

I want to query this table to get a link list showing all the people who were linked to a given PersonID=XXXX, and the links between them defined by being included on the emails that include XXXX, preferably including a weight on the links showing the number of occurrences.  Another way of saying this, in graph terminology, is I'm trying to get the neighborhood of XXXX. For example, for entries like

```<code>MID   PID
1     1
1     2
1     3
2     1
2     2
3     1
3     3
3     4
</code>```

For PersonID 1 I would like to get link list

```<code>P1    P2    Count
1     1     3
1     2     2
1     3     2
1     4     1
2     3     1
3     4     1
</code>```

Is it possible to do this with some kind of self-join?  If so what query would I use?  I have done some simpler joins (for example to get the star-graph of XXXX and other PersonIDs that are with XXXX on emails) but this one is over my head.

答:
You can use GROUP_CONCAT do to something sort of like that.  It's not a table but a result set of the related pids per mid.

```<code>select mid, group_concat(distinct pid order by pid separator ', ') as related_ppl
  from personxmessage
 group by mid;
</code>```

result

```<code>  mid   related_ppl
    1   1, 2, 3
    2   1, 2
    3   1, 3, 4
</code>```

I think this is what you're looking for:

```<code>select p.pid as pid1, pp.pid as pid2, count(*) as cnt
  from personxmessagep
  left join personxmessagepp
    on p.mid = pp.mid
   and p.pid < pp.pid
 group by p.pid, pp.pid;
</code>```

result

```<code>pid  pid2 cnt
1    2    2
1    3    2
1    4    1
2         1
2    3    1
3         1
3    4    1
4         1
</code>```

Body:
I have a MySQL table called personxmessage, extracted from emails.  It has three fields, id (primary key), MessageID, and PersonID.  For each message referenced by MessageID, there are two or more records, each with a PersonID for a person who was included in the email (i.e. in sender, sent to, or cc).

I want to query this table to get a link list showing all the people who were linked to a given PersonID=XXXX, and the links between them defined by being included on the emails that include XXXX, preferably including a weight on the links showing the number of occurrences.  Another way of saying this, in graph terminology, is I'm trying to get the neighborhood of XXXX. For example, for entries like

MID   PID
1     1
1     2
1     3
2     1
2     2
3     1
3     3
3     4

For PersonID 1 I would like to get link list

P1    P2    Count
1     1     3
1     2     2
1     3     2
1     4     1
2     3     1
3     4     1

Is it possible to do this with some kind of self-join?  If so what query would I use?  I have done some simpler joins (for example to get the star-graph of XXXX and other PersonIDs that are with XXXX on emails) but this one is over my head.

Body:
You can use GROUP_CONCAT do to something sort of like that.  It's not a table but a result set of the related pids per mid.

select mid, group_concat(distinct pid order by pid separator ', ') as related_ppl
  from personxmessage
 group by mid;

result

  mid   related_ppl
    1   1, 2, 3
    2   1, 2
    3   1, 3, 4

I think this is what you're looking for:

select p.pid as pid1, pp.pid as pid2, count(*) as cnt
  from personxmessagep
  left join personxmessagepp
    on p.mid = pp.mid
   and p.pid < pp.pid
 group by p.pid, pp.pid;

result

pid  pid2 cnt
1    2    2
1    3    2
1    4    1
2         1
2    3    1
3         1
3    4    1
4         1


问:
How to add values in a 2d matrix with same first index (c++)
I have a set of values stored in a 2d matrix.  I want to create separate totals for the values which have the same first index.  Here's a short example:

```<code>typedef int matrix [9][9];
matrix sampleMatrix;

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   for (int j = 0; j < 9; j++){
        //here's where I'm stuck
        //if i = 1, then total all values with i = 1 etc.
        if(sampleMatrix[i]){
        int sum = sum + sampleMatrix[i][j];
        }
        std::cout << i << " Total: " << sum << std::endl;
   }

}
</code>```

Thanks for any help.

答:
If you initialize all values of array with 0 then you would be able to sum up all values of each i'th index</p>

```<code>matrix sampleMatrix;
for(int i=0;i<9;i++){
    for(int j=0;j<9;j++){
         sampleMatrix[i][j]=0;
    }
}

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   int sum=0;
   for (int j = 0; j < 9; j++){
          sum = sum + sampleMatrix[i][j];
   }
   cout<<sum<<endl;
}
</code>```

Body:
I have a set of values stored in a 2d matrix.  I want to create separate totals for the values which have the same first index.  Here's a short example:

typedef int matrix [9][9];
matrix sampleMatrix;

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   for (int j = 0; j < 9; j++){
        //here's where I'm stuck
        //if i = 1, then total all values with i = 1 etc.
        if(sampleMatrix[i]){
        int sum = sum + sampleMatrix[i][j];
        }
        std::cout << i << " Total: " << sum << std::endl;
   }

}

Thanks for any help.

Body:
If you initialize all values of array with 0 then you would be able to sum up all values of each i'th index

matrix sampleMatrix;
for(int i=0;i<9;i++){
    for(int j=0;j<9;j++){
         sampleMatrix[i][j]=0;
    }
}

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   int sum=0;
   for (int j = 0; j < 9; j++){
          sum = sum + sampleMatrix[i][j];
   }
   cout<<sum<<endl;
}


问:
Groupby and where clause in Linq
I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote

```<code>var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
                  .Where(x => x.TripPath.PathNumber == pathnum)
                  .Select(x => x.TripPath.TripPathLink.Link.Speed).Min();
</code>```

I am not able to use group by and where together it keeps giving error .

My query should

Select all the values.

filter it through the where clause (pathnum).

Groupby the road Name

finally get the min value.

can some one tell me what i am doing wrong and how to achieve the desired result.

Thanks,
Pawan

答:
It's a little tricky not knowing the relationships between the data, but I think (without trying it) that this should give you want you want -- the minimum speed per road by name.  Note that it will result in a collection of anonymous objects with Name and Speed properties.</p>

```<code>var data = newTrips.Where(x => x.TripPath.PathNumber == pathnum)
                   .Select(x => x.TripPath.TripPathLink.Link)
                   .GroupBy(x => x.Road.Name)
                   .Select(g => new { Name = g.Key, Speed = g.Min(l => l.Speed) } );
</code>```

Title: Groupby and where clause in Linq

Body:
I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote

var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
                  .Where(x => x.TripPath.PathNumber == pathnum)
                  .Select(x => x.TripPath.TripPathLink.Link.Speed).Min();

I am not able to use group by and where together it keeps giving error .

My query should

Select all the values.

filter it through the where clause (pathnum).

Groupby the road Name

finally get the min value.

can some one tell me what i am doing wrong and how to achieve the desired result.

Thanks,
Pawan

Body:
It's a little tricky not knowing the relationships between the data, but I think (without trying it) that this should give you want you want -- the minimum speed per road by name.  Note that it will result in a collection of anonymous objects with Name and Speed properties.

var data = newTrips.Where(x => x.TripPath.PathNumber == pathnum)
                   .Select(x => x.TripPath.TripPathLink.Link)
                   .GroupBy(x => x.Road.Name)
                   .Select(g => new { Name = g.Key, Speed = g.Min(l => l.Speed) } );