问:
How to test Spring REST webservice when using a HandlerInterceptorAdapter?
I am developing a Spring web service. I want to test my endpoints but for some reason I always get the following exception when I run the tests:

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....IncomingInterceptor'
</code>```

However, I annotated the class with @Component. The interceptor works when I test the endpoint using an external client! Does somebody know how to solve this problem?

Here is my code when I test the endpoint:
    private MockMvc mockMvc;

```<code>@InjectMocks
private AccountController accountController;

@Mock
private IncomingInterceptor incomingInterceptor;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws
    mockMvc.perform(MockMvcRequestBuilders.post("/account/add")
            .content(gson.toJson(account))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNotEmpty());
}
</code>```

The code for the IncomingInterceptor:

```<code>@Component
public class IncomingInterceptor extends HandlerInterceptorAdapter {

@Autowired
private Gson gson;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//code in here works
    return true;
}
}
</code>```

Note: I do not want to test if the Interceptor works, I want to test the Endpoints!!!
Thanks in advance!

答:
Although your test code snippets do not reveal what test runner is used (@RunWith(...)), my guess is that you're using a SpringRunner or SpringJUnit4ClassRunner test runner.

Your snippet mocks an instance of IncomingInterceptor, however it isn't added to the (test)ApplicationContext as a bean. Use @MockBean instead of @Mock to add your mocked bean to the ApplicationContext.

```<code>@MockBean
private IncomingInterceptor incomingInterceptor;
</code>```

Body:
I am developing a Spring web service. I want to test my endpoints but for some reason I always get the following exception when I run the tests:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....IncomingInterceptor'

However, I annotated the class with @Component. The interceptor works when I test the endpoint using an external client! Does somebody know how to solve this problem?

Here is my code when I test the endpoint:
    private MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@Mock
private IncomingInterceptor incomingInterceptor;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws
    mockMvc.perform(MockMvcRequestBuilders.post("/account/add")
            .content(gson.toJson(account))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNotEmpty());
}

The code for the IncomingInterceptor:

@Component
public class IncomingInterceptor extends HandlerInterceptorAdapter {

@Autowired
private Gson gson;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//code in here works
    return true;
}
}

Note: I do not want to test if the Interceptor works, I want to test the Endpoints!!!
Thanks in advance!

Body:
Although your test code snippets do not reveal what test runner is used (@RunWith(...)), my guess is that you're using a SpringRunner or SpringJUnit4ClassRunner test runner.

Your snippet mocks an instance of IncomingInterceptor, however it isn't added to the (test)ApplicationContext as a bean. Use @MockBean instead of @Mock to add your mocked bean to the ApplicationContext.

@MockBean
private IncomingInterceptor incomingInterceptor;


来源: stackexchange

问:
Some of the css grid is not fitting in to the lines
Hi my css grid isn't working.. the red section fits in the first square, but the rest seem to just be out of the flow of the grid.. I'm completely new to this what am i missing?? I've tried everything but can't find the simple solution im sure..</p>
```<code><section class="pastevnts">
      <div class="pastevents__container">
        <div class="pastevents__title">
          PAST EVENTS
        </div>
        <div class="pastevents__event">
          <div class="pastevents__event-date">
            17<span>Feb</span><br>2019
          </div>
          <div class="pastevents__event-title">
            ELECTRIC LOVE PARADE
          </div>
          <div class="pastevents__event-body">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus aliquam purus in fringilla semper. In laoreet, urna ut porttitor cursus, lectus dolor ultrices ligula, sit amet tincidunt massa sem eget dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vehicula dolor
          </div>
        </div>
      </div>
    </section>

//pastevents
.pastevents {
  min-height: 100vh;
  background-color: #000;

  &__event {
    height: 200px;
    width: 500px;
    position: relative;
    display: grid;
    grid-template-columns: 30% 70%;
    grid-template-rows: 20% 80%;
  }

  &__event-date {
    background-color: red;
    grid-column: 1 / span 1;
    grid-row: 1 / span 1;
  }

  &__event-title {
    background-color: blue;
    grid-column: 2 / span 1;
    grid-row: 1 / span 1;
  }

  &__event-body {
    background-color: green;
    grid-column: 2 / span 1;
    grid-row: 2 / span 1;
  }
}
</code>```

答:
I may not be sure of your question but, if you want to align your grids horizontaly like your red grid. First of all, define how many columns you want</p>

```<code> &__event {
    height: 200px;
    width: 500px;
    position: relative;
    display: grid;
    grid-template-columns: 30% 30% 40%; //If you want to divide equally : 1fr 1fr 1fr;
    grid-template-rows: 20%; // You'll have to play around with this until it satisfies your needs
  }

&__event-date {
    background-color: red;
    grid-column: 1 / span 1;
    grid-row: 1 / span 1;
  }

  &__event-title {
    background-color: blue;
    grid-column: 2 / span 1;
  }

  &__event-body {
    background-color: green;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi my css grid isn't working.. the red section fits in the first square, but the rest seem to just be out of the flow of the grid.. I'm completely new to this what am i missing?? I've tried everything but can't find the simple solution im sure..

          PAST EVENTS

            17Feb
2019

            ELECTRIC LOVE PARADE

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus aliquam purus in fringilla semper. In laoreet, urna ut porttitor cursus, lectus dolor ultrices ligula, sit amet tincidunt massa sem eget dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vehicula dolor

//pastevents
.pastevents {
  min-height: 100vh;
  background-color: #000;

  &__event {
    height: 200px;
    width: 500px;
    position: relative;
    display: grid;
    grid-template-columns: 30% 70%;
    grid-template-rows: 20% 80%;
  }

  &__event-date {
    background-color: red;
    grid-column: 1 / span 1;
    grid-row: 1 / span 1;
  }

  &__event-title {
    background-color: blue;
    grid-column: 2 / span 1;
    grid-row: 1 / span 1;
  }

  &__event-body {
    background-color: green;
    grid-column: 2 / span 1;
    grid-row: 2 / span 1;
  }
}

Body:
I may not be sure of your question but, if you want to align your grids horizontaly like your red grid. First of all, define how many columns you want

 &__event {
    height: 200px;
    width: 500px;
    position: relative;
    display: grid;
    grid-template-columns: 30% 30% 40%; //If you want to divide equally : 1fr 1fr 1fr;
    grid-template-rows: 20%; // You'll have to play around with this until it satisfies your needs
  }

&__event-date {
    background-color: red;
    grid-column: 1 / span 1;
    grid-row: 1 / span 1;
  }

  &__event-title {
    background-color: blue;
    grid-column: 2 / span 1;
  }

  &__event-body {
    background-color: green;
  }


问:
How to implement cards in a QnA question which has follow up prompts and uses them in the cards
I've set up a simple QnA bot which is linked to a QnA service. Within the QnA service I have set up some questions which have follow up prompts(Dependents) e.g. how do I get to a campus, via bus, train etc. see image in link, within the Qna maker testing function you can just click a button called enable mutli-turn which provides functional buttons to inform you of what can/should be asked next via the dependents of the answer See image in link.

However when used within a channel/in the emulator nothing of the like appears see image, which is a bit odd. And obviously I want to implement such functionality in to the bot as it makes life so much easier for the users.

I am new to the whole bot thing(I started last month), so I have a browsed the internet to see what I could find but I could not see anything out side of writing the questions within the bot it self, see Microsofts documentation, which makes using QnA maker pretty much pointless.

What I think I need to do is intercept the message from QnA maker as it replies to the user, look at the Json received to find if has any dependents then run a different dialog, which gets the contextual dependents names and runs a simple for loop generating cards for each dependents, then send the message to the user with the generated cards, however I'm not sure how to intercept the Json and look for any dependents, or there is a button the I need to click within azure which just does it.

答:
There is this experimental sample that has been released by the Bot Framework team which demonstrates how to handle follow-up prompts.

You can download it (you will have to download the whole repo) then plug in your details to the appsettings.json file and you should be able to test it using the Bot Framework Emulator - these were the only steps that I had to perform.

The key part is this method which checks to see if the result contains any prompts and returns the response accordingly - it is called inside the FuctionDialog.

If you're only ever going to be implementing a single level of prompts i.e. you have a question which shows prompts and when you click on one of these prompts it will display an answer rather than taking you to another prompt, then it is possible to take the guts of the logic from the ProcessAsync method (checking for prompts) along with the required classes from the Models folder and the CardHelper class and get this to work in your existing application - you won't have to worry about the QnABotState because you'll only be going a single level deep so you don't need to track where you are in the series of prompts. e.g.

```<code>var query = inputActivity.Text;
var qnaResult = await _qnaService.QueryQnAServiceAsync(query, new QnABotState());
var qnaAnswer = qnaResult[0].Answer;
var prompts = qnaResult[0].Context?.Prompts;

if (prompts == null || prompts.Length < 1)
{
    outputActivity = MessageFactory.Text(qnaAnswer);
}
else
{
    outputActivity = CardHelper.GetHeroCard(qnaAnswer, prompts);
}

await turnContext.SendActivityAsync(outputActivity);
</code>```

Body:
There is this experimental sample that has been released by the Bot Framework team which demonstrates how to handle follow-up prompts.

You can download it (you will have to download the whole repo) then plug in your details to the appsettings.json file and you should be able to test it using the Bot Framework Emulator - these were the only steps that I had to perform.

The key part is this method which checks to see if the result contains any prompts and returns the response accordingly - it is called inside the FuctionDialog.

If you're only ever going to be implementing a single level of prompts i.e. you have a question which shows prompts and when you click on one of these prompts it will display an answer rather than taking you to another prompt, then it is possible to take the guts of the logic from the ProcessAsync method (checking for prompts) along with the required classes from the Models folder and the CardHelper class and get this to work in your existing application - you won't have to worry about the QnABotState because you'll only be going a single level deep so you don't need to track where you are in the series of prompts. e.g.

var query = inputActivity.Text;
var qnaResult = await _qnaService.QueryQnAServiceAsync(query, new QnABotState());
var qnaAnswer = qnaResult[0].Answer;
var prompts = qnaResult[0].Context?.Prompts;

if (prompts == null || prompts.Length < 1)
{
    outputActivity = MessageFactory.Text(qnaAnswer);
}
else
{
    outputActivity = CardHelper.GetHeroCard(qnaAnswer, prompts);
}

await turnContext.SendActivityAsync(outputActivity);


问:
Adding cookie expiration date
I found this javascript cookie script on SOF and it does exactly what I want. Redirecting first time visitors to a different URL. I only want it to have an expiration date of 1 day. </p>

```<code>if (getCookie("first_visit") != "true") {
document.cookie = "first_visit=true";
location.href="http://pgklavertjevier.nl";
}

function getCookie(cname) {
var name = cname + "=";
   var ca = document.cookie.split(';');
      for(var i = 0; i <ca.length; i++) {
         var c = ca[i];
         while (c.charAt(0)==' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
         }
     }
    return "";
}
</code>```

答:
You can set the expiration date (in your case 1 day) of cookie along with its value while creating it.

If you are creating cookies through javascript then you can use the below code:

```<code>function setCookie(name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + ";path=/";
    document.cookie = name + "=" + c_value;
}

setCookie("first_visit", true, 1);
</code>```

Title: Adding cookie expiration date

Body:
I found this javascript cookie script on SOF and it does exactly what I want. Redirecting first time visitors to a different URL. I only want it to have an expiration date of 1 day.

if (getCookie("first_visit") != "true") {
document.cookie = "first_visit=true";
location.href="http://pgklavertjevier.nl";
}

function getCookie(cname) {
var name = cname + "=";
   var ca = document.cookie.split(';');
      for(var i = 0; i <ca.length; i++) {
         var c = ca[i];
         while (c.charAt(0)==' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
         }
     }
    return "";
}

Body:
You can set the expiration date (in your case 1 day) of cookie along with its value while creating it.

If you are creating cookies through javascript then you can use the below code:

function setCookie(name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + ";path=/";
    document.cookie = name + "=" + c_value;
}

setCookie("first_visit", true, 1);


问:
POSTGRES - LIMIT 1 DESC for each ID in WHERE IN
Problem:
I have a table where there are several rows with same code but different date, I also have a query:

```<code>SELECT * FROM movies WHERE CODE IN ('action', 'comedy')
</code>```

Question:
How can I return row with latest date FOR EACH code in the list and limit it to 1 since there can be duplicates:

so it returns just ID 1 and 4.

Something like

```<code>SELECT * FROM movies WHERE CODE IN ('action', 'comedy') DESC LIMIT 1
</code>```

but for each code.

Thank you.

答:
In Postgres, use DISTINCT ON:

```<code>SELECT DISTINCT ON (CODE) m.*
FROM movies m
WHERE m.CODE IN ('action', 'comedy')
ORDER BY m.CODE, m.start_date DESC;
</code>```

DISTINCT ON is a Postgres extension.  It returns a result set with one row per unique combination of values of the expressions in parentheses (like GROUP BY keys in that respect).  The particular row is determined by the ORDER BY clause.  The unique keys come first and the rest of the keys define "which" row.

Body:
Problem:
I have a table where there are several rows with same code but different date, I also have a query:

SELECT * FROM movies WHERE CODE IN ('action', 'comedy')

Question:
How can I return row with latest date FOR EACH code in the list and limit it to 1 since there can be duplicates:

so it returns just ID 1 and 4.

Something like

SELECT * FROM movies WHERE CODE IN ('action', 'comedy') DESC LIMIT 1

but for each code.

Thank you.

Body:
In Postgres, use DISTINCT ON:

SELECT DISTINCT ON (CODE) m.*
FROM movies m
WHERE m.CODE IN ('action', 'comedy')
ORDER BY m.CODE, m.start_date DESC;

DISTINCT ON is a Postgres extension.  It returns a result set with one row per unique combination of values of the expressions in parentheses (like GROUP BY keys in that respect).  The particular row is determined by the ORDER BY clause.  The unique keys come first and the rest of the keys define "which" row.


问:
Why does active record pattern not work with rich domain models?
I'm reading the architectural patterns chapter of POEAA, and Fowler says that "As the domain logic gets more complicated and you begin moving toward a rich Domain Model (116), the simple approach of an Active Record (160) starts to break down.  The one-to-one match of domain classes to tables starts to fail as you factor domain logic into smaller classes. Relational databases don't handle inheritance, so it becomes difficult to use strategies [Gang of Four] and other neat OO patterns. As the domain logic gets feisty, you want to be able to test it without having to talk to the database all the time."

I didn't really understand this.  By "one to one match of domain classes to tables", does he mean that only for classes where there is no associations or single table inheritance hierarchy?

And why does factoring domain logic into smaller classes cause the pattern to fail?

答:
What he's trying to say is that more complex domain models are usually more than just "data from a table". These more complex models Fowler is talking about are models that get data from different tables, views or maybe even other sources.

The Active Record pattern is not very suitable for this purpose, and the DataMapper pattern combined with just model classes (containing just the business logic and do not communicate with the data access layer) is probably more suitable in situations like these.

The Active Record pattern fails here, because it maps more or less directly to a table in the database.

I don't know the exact pattern definition, so please correct me if i'm wrong.

ContentLicense: CC BY-SA 3.0


问:
Issue with 2nd y axis using sec.axis
I am trying to plot two sets of data: ch4 (scale of data is ~2e-06) and altitude (scale of data is ~10). I am using the sec.axis command in ggplot2. I can't get it to correctly scale both data sets. If I don't use limits within scale_y_continuous the ch4 data appear as a flat line because the left hand axis is scaled to altitude. If I include limits within scale_y_continuous my ch4 data plots ok, but altitude doesn't show up at all (even though the righthand axis scale is on the appropriate scale) Can someone please help me figure out what I'm doing wrong here.

Example data:

```<code>timestamp  ch4        alt

47232.42 1.923e-06  0.44

47232.57 1.908e-06  1.38

47232.77 1.931e-06  5.93

47233.03 1.946e-06  12.01

47233.20 1.904e-06  6.43

47233.43 1.913e-06  0.42
</code>```

Example code where ch4 is a flat line:

```<code>basicplot <- ggplot(data=mydata, aes(x=timestamp)) +

  geom_line(aes(y=ch4), color="red") +

  geom_line(aes(y=alt), color="blue") +

  scale_y_continuous(sec.axis = sec_axis(~ . * 20/0.000002, name="altitude"))

print(basicplot)
</code>```

Example code where altitude doesn't appear (even though right-hand scale seems ok):

```<code>basicplot <- ggplot(data=mydata, aes(x=timestamp)) +

  geom_line(aes(y=alt), color="blue") +

  geom_line(aes(y=ch4), color="red") +

  scale_y_continuous(sec.axis = sec_axis(~ . * 20/0.000002, name="altitude"), limits = c(0, 0.000005))

print(basicplot)
</code>```

答:
```<code>scale_coeff <- 20/0.000002

ggplot(data=mydata, aes(x=timestamp)) +
  geom_line(aes(y=alt / scale_coeff), color="blue") +
  geom_line(aes(y=ch4), color="red") +
  scale_y_continuous(name = "ch4",
                     sec.axis = sec_axis(~ . * scale_coeff, name="altitude"))  +
  theme(axis.text.y.left = element_text(color = "red"),
        axis.title.y.left = element_text(color = "red"),
        axis.text.y.right = element_text(color = "blue"),
        axis.title.y.right = element_text(color = "blue"))
</code>```

```<code>mydata<- read.table(header = T, stringsAsFactors = F,
  text = "timestamp  ch4        alt
47232.42 1.923e-06  0.44
47232.57 1.908e-06  1.38
47232.77 1.931e-06  5.93
47233.03 1.946e-06  12.01
47233.20 1.904e-06  6.43
47233.43 1.913e-06  0.42")
</code>```

Title: Issue with 2nd y axis using sec.axis

Body:
I am trying to plot two sets of data: ch4 (scale of data is ~2e-06) and altitude (scale of data is ~10). I am using the sec.axis command in ggplot2. I can't get it to correctly scale both data sets. If I don't use limits within scale_y_continuous the ch4 data appear as a flat line because the left hand axis is scaled to altitude. If I include limits within scale_y_continuous my ch4 data plots ok, but altitude doesn't show up at all (even though the righthand axis scale is on the appropriate scale) Can someone please help me figure out what I'm doing wrong here.

Example data:

timestamp  ch4        alt

47232.42 1.923e-06  0.44

47232.57 1.908e-06  1.38

47232.77 1.931e-06  5.93

47233.03 1.946e-06  12.01

47233.20 1.904e-06  6.43

47233.43 1.913e-06  0.42

Example code where ch4 is a flat line:

basicplot <- ggplot(data=mydata, aes(x=timestamp)) +

  geom_line(aes(y=ch4), color="red") +

  geom_line(aes(y=alt), color="blue") +

  scale_y_continuous(sec.axis = sec_axis(~ . * 20/0.000002, name="altitude"))

print(basicplot)

Example code where altitude doesn't appear (even though right-hand scale seems ok):

basicplot <- ggplot(data=mydata, aes(x=timestamp)) +

  geom_line(aes(y=alt), color="blue") +

  geom_line(aes(y=ch4), color="red") +

  scale_y_continuous(sec.axis = sec_axis(~ . * 20/0.000002, name="altitude"), limits = c(0, 0.000005))

print(basicplot)

Body:
scale_coeff <- 20/0.000002

ggplot(data=mydata, aes(x=timestamp)) +
  geom_line(aes(y=alt / scale_coeff), color="blue") +
  geom_line(aes(y=ch4), color="red") +
  scale_y_continuous(name = "ch4",
                     sec.axis = sec_axis(~ . * scale_coeff, name="altitude"))  +
  theme(axis.text.y.left = element_text(color = "red"),
        axis.title.y.left = element_text(color = "red"),
        axis.text.y.right = element_text(color = "blue"),
        axis.title.y.right = element_text(color = "blue"))

mydata<- read.table(header = T, stringsAsFactors = F,
  text = "timestamp  ch4        alt
47232.42 1.923e-06  0.44
47232.57 1.908e-06  1.38
47232.77 1.931e-06  5.93
47233.03 1.946e-06  12.01
47233.20 1.904e-06  6.43
47233.43 1.913e-06  0.42")


问:
Is there any way to pass media key events back to Windows from Chrome?
Chrome 73 added media key support for playing videos in the browser (e.g. YouTube). I'm trying to make a chrome extension that let's you use media keys for both Chrome and system media (like normal control for Spotify or media players). I can intercept the media key event in Chrome using the MediaSession API, but have no idea if it is possible to also 'free' the media key event and let it propagate to the next system media process. Does anyone even know it if possible/how I could do it?

This is how I am currently capturing the media key events ('play', 'pause', 'nexttrack' and 'previoustrack'):

```<code>window.onload = function() {

    navigator.mediaSession.setActionHandler('play', function() {
      console.log('play media key pressed');
      playMedia(document);
    });

}
</code>```

答: Couldn't find a way to get JS to play system media, so to get around this I sent a message from the content scripts to the background process, which then sent a message to every tab, telling them to stop their respective videos (pause it and remove the source) to let the user play system media, and then restart the videos.</p>

Body:
Chrome 73 added media key support for playing videos in the browser (e.g. YouTube). I'm trying to make a chrome extension that let's you use media keys for both Chrome and system media (like normal control for Spotify or media players). I can intercept the media key event in Chrome using the MediaSession API, but have no idea if it is possible to also 'free' the media key event and let it propagate to the next system media process. Does anyone even know it if possible/how I could do it?

This is how I am currently capturing the media key events ('play', 'pause', 'nexttrack' and 'previoustrack'):

window.onload = function() {

    navigator.mediaSession.setActionHandler('play', function() {
      console.log('play media key pressed');
      playMedia(document);
    });

}


问:
Using GeckoDriverManager().install() to run tests in Firefox
I have the following code to run tests in various browsers. Chrome of course works correctly on the machine I am wanting to run these tests on, however, Firefox, IE, and Edge do not. Is this the right way to go about this? I would prefer not to have to have a file I have to download and change every couple of months when the browsers update.

```<code>    def __init__(self, browser: str = TESTING_BROWSER, home: str = BASE_URL):
    """Hooray for inits."""
    if browser.lower() == "ie":
        webdriver.Ie.__init__(self, IEDriverManager().install())
    elif browser.lower() == 'edge':
        webdriver.Edge().__init__(self, EdgeDriverManager().install())
    elif browser.lower() == "firefox":
        webdriver.Firefox.__init__(self, GeckoDriverManager().install())
    else:
        chrome_options = Options()
        if os.environ.get('RUN_HEADLESS') == 'True':
            chrome_options.add_argument('--headless')
            chrome_options.add_argument("--disable-extensions")
            chrome_options.add_argument("--disable-gpu")
            webdriver.Chrome.__init__(self, ChromeDriverManager().install(), chrome_options=chrome_options)
        else:
            webdriver.Chrome.__init__(self, ChromeDriverManager().install())
</code>```

As a side note when I try and run Firefox, I am getting the following error:

```<code>NotADirectoryError: [Errno 20] Not a directory: '/Users/me/.wdm/geckodriver/v0.24.0/macos/geckodriver'
</code>```

I have tried adding executable_path=path to geckodriver and that is not working either.

答:
So RTD wins again:

webdriver.Firefox.__init__(self, executable_path=GeckoDriverManager().install())

For those interested, the documentation to webdriver_manager is here

Body:
I have the following code to run tests in various browsers. Chrome of course works correctly on the machine I am wanting to run these tests on, however, Firefox, IE, and Edge do not. Is this the right way to go about this? I would prefer not to have to have a file I have to download and change every couple of months when the browsers update.

    def __init__(self, browser: str = TESTING_BROWSER, home: str = BASE_URL):
    """Hooray for inits."""
    if browser.lower() == "ie":
        webdriver.Ie.__init__(self, IEDriverManager().install())
    elif browser.lower() == 'edge':
        webdriver.Edge().__init__(self, EdgeDriverManager().install())
    elif browser.lower() == "firefox":
        webdriver.Firefox.__init__(self, GeckoDriverManager().install())
    else:
        chrome_options = Options()
        if os.environ.get('RUN_HEADLESS') == 'True':
            chrome_options.add_argument('--headless')
            chrome_options.add_argument("--disable-extensions")
            chrome_options.add_argument("--disable-gpu")
            webdriver.Chrome.__init__(self, ChromeDriverManager().install(), chrome_options=chrome_options)
        else:
            webdriver.Chrome.__init__(self, ChromeDriverManager().install())

As a side note when I try and run Firefox, I am getting the following error:

NotADirectoryError: [Errno 20] Not a directory: '/Users/me/.wdm/geckodriver/v0.24.0/macos/geckodriver'

I have tried adding executable_path=path to geckodriver and that is not working either.


问:
How to set the syntax language for a specific file in atom?
Atom does not recognize that a file should be a shell script and defaults to plain text syntax. I can change it in the bottom right corner but the next time I open the file I have to change it again. How can I set the file to open with the correct syntax?

I found a atom package that would do this but it is unmaintained and no longer works: https://github.com/blezek/file-mode

You can set the atom defaults so that it opens anything it doesn't recognize as a shell script, but then if there's a file that should be plain text it will open as a shell script so doing it on a per file basis would be preferred.

答:
One solution I found for shell scripts specifically is adding a file identifier to the top line. I'm still not sure how to set the file type for any file in general.</p>

```<code>#!/bin/bash
</code>```

Body:
One solution I found for shell scripts specifically is adding a file identifier to the top line. I'm still not sure how to set the file type for any file in general.

#!/bin/bash


问:
codeigniter form validation set_value works only for the fields which have rules
Suppose if I have two fields in my form viz first_name and last_name

I have set the validation rule only for first_name.

set_value should work for both the fields regardless of rule ? right ?

For me it works only for the fields which have rules with them !!!

答:
set_value only works against the items you have chosen to validate using the form_validation class.

Easiest way is to pretend you are validating by adding this to your form validation config

        array(
            'field'   => 'address1',
            'label'   => '',
            'rules'   => ''
        ),

There is a hack someone has done to the CI library but I haven't been able to find the documentation on that today...Or use this modification instead:

http://codeigniter.com/forums/viewthread/159535/#775628


问:
env-cmd error failed to locate ./.env file in gatsby?
I have a file name .env.development in the root folder. I had install env-cmd as dev dependencies

when I start the server

```<code>  > npm run develop
</code>```

its give me an error

```<code>> gatsby-starter-hello-world@0.1.0 develop I:\learngatsby
> env-cmd .env-development gatsby develop

(node:1368) UnhandledPromiseRejectionWarning: Error: Unable to locate env file at default location (./.env)
at I:\learngatsby\node_modules\env-cmd\dist\get-env-vars.js:44:19
at Generator.throw (<anonymous>)
at rejected (I:\learngatsby\node_modules\env-cmd\dist\get-env-vars.js:5:65)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
</code>```
```<code>(node:1368) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:1368) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

答:
Ran into the same issue, here's a snippet of gatsby-config.js I added to make the ".env.development" file visible to gatsby. (Not sure if this is the only way, node/Gatsby experts please chime in)

```<code>
let activeEnv =
  process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || "development"

console.log('Using environment config: ${activeEnv}')

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})
</code>```

Based on this gatsby-config.js, here is the develop script in package.json (unchanged) -

```<code>
...
"develop": "gatsby develop",
...
</code>```

Finally, starting the gatsby app using ```<code>npm run develop</code>```, the logs mentions playground being available -

```<code>
You can now view gatsby-starter-hello-world in the

  http://localhost:8000/

View the GraphQL Playground, an in-browser IDE, to

  http://localhost:8000/___graphql
</code>```

Body:
I have a file name .env.development in the root folder. I had install env-cmd as dev dependencies

when I start the server

  > npm run develop

its give me an error

> gatsby-starter-hello-world@0.1.0 develop I:\learngatsby
> env-cmd .env-development gatsby develop

(node:1368) UnhandledPromiseRejectionWarning: Error: Unable to locate env file at default location (./.env)
at I:\learngatsby\node_modules\env-cmd\dist\get-env-vars.js:44:19
at Generator.throw (<anonymous>)
at rejected (I:\learngatsby\node_modules\env-cmd\dist\get-env-vars.js:5:65)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

(node:1368) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:1368) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Body:
Ran into the same issue, here's a snippet of gatsby-config.js I added to make the ".env.development" file visible to gatsby. (Not sure if this is the only way, node/Gatsby experts please chime in)

let activeEnv =
  process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || "development"

console.log('Using environment config: ${activeEnv}')

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

Based on this gatsby-config.js, here is the develop script in package.json (unchanged) -

...
"develop": "gatsby develop",
...

Finally, starting the gatsby app using
npm run develop
, the logs mentions playground being available -

You can now view gatsby-starter-hello-world in the

  http://localhost:8000/

View the GraphQL Playground, an in-browser IDE, to

  http://localhost:8000/___graphql


问:
Callins specific function depending on macro parameter in C
I have multiple functions with very similar identifiers (func1(), func2(), func3(), ...) and i need to create a macro to call them all in one.

i already tried to use concatenation but i couldn't figure it out.

void func1() {}
void func2() {}
void func3() {}

#define call(N) // here needs to go the code to call the N func like func#N()
```

<p>so that later in the code i can do something like this:</p>

<pre class="lang-c prettyprint-override"><code>int main()
{
    for(int i = 0; i < 3; i++)
        call(i);
}
</code>```

if there are other methods that i don't know or you can do it in another way show me your ideas. if possible i'd like to stick with macros

答:
Perhaps use the concatenation operator (##)

```<code>#define call(N) call##N()
</code>```

It's unclear why this would be necessary though - why not just type call1() instead of call(1). This won't help with dynamically selecting the right function to call based on a variable. For that you'd need conditional logic.

```<code>switch (n) {
    case 1: call1(); break;
    case 2: call2(); break;
    default: ...; break;
}
</code>```

Body:
I have multiple functions with very similar identifiers (func1(), func2(), func3(), ...) and i need to create a macro to call them all in one.

i already tried to use concatenation but i couldn't figure it out.

void func1() {}
void func2() {}
void func3() {}

#define call(N) // here needs to go the code to call the N func like func#N()

so that later in the code i can do something like this:

int main()
{
    for(int i = 0; i < 3; i++)
        call(i);
}

if there are other methods that i don't know or you can do it in another way show me your ideas. if possible i'd like to stick with macros

Body:
Perhaps use the concatenation operator (##)

#define call(N) call##N()

It's unclear why this would be necessary though - why not just type call1() instead of call(1). This won't help with dynamically selecting the right function to call based on a variable. For that you'd need conditional logic.

switch (n) {
    case 1: call1(); break;
    case 2: call2(); break;
    default: ...; break;
}


问:
How to handle "OSError: Cannot seek back after getting firstbytes" when trying to extract jpg files into numpy array
I'm trying to collect all images in a zip file into a numpy array.

Always getting an error:
OSError: Cannot seek back after getting firstbytes!

```<code>import urllib.request
import os
import zipfile
import scipy
import numpy as np
import pandas as pd
import glob
import imageio
from os.path import splitext

url = 'https://github.com/yoavram/Sign-Language/raw/master/Dataset.zip'
filename = '../data/sign-lang'
if not os.path.exists('../data'):
    os.mkdir('../data')
if not os.path.exists(filename):
    urllib.request.urlretrieve(url, filename)

zf = zipfile.ZipFile(filename)

for file in zf.namelist():
    basename,extension = splitext(file)
    if extension == '.jpg':
        with zf.open(file) as img_file:
            img = imageio.read(img_file)
</code>```

Help?

答:
I had a similar problem for the longest time.

The problem is that imageio.read() expects bytes but is being provided with a file-type object.

To fix this, simply read the bytes from the file.

img = imageio.read(img_file.read())

Also, if you want numpy arrays you should use imageio.imread()

Body:
I'm trying to collect all images in a zip file into a numpy array.

Always getting an error:
OSError: Cannot seek back after getting firstbytes!

import urllib.request
import os
import zipfile
import scipy
import numpy as np
import pandas as pd
import glob
import imageio
from os.path import splitext

url = 'https://github.com/yoavram/Sign-Language/raw/master/Dataset.zip'
filename = '../data/sign-lang'
if not os.path.exists('../data'):
    os.mkdir('../data')
if not os.path.exists(filename):
    urllib.request.urlretrieve(url, filename)

zf = zipfile.ZipFile(filename)

for file in zf.namelist():
    basename,extension = splitext(file)
    if extension == '.jpg':
        with zf.open(file) as img_file:
            img = imageio.read(img_file)

Help?


问:
How to correctly design a regular expression in pymongo?
I use python 3.7.1 (default, Dec 14 2018, 19:28:38), and pymongo 3.7.2.

In mongodb this works:

```<code>db.collection.find(
    {$and:[
    {"field":{$regex:"bon?"}},
    {"field":{$not:{$regex:"bon souple"}}},
    {"field":{$not:{$regex:"bon léger"}}}
    ]}
    )
</code>```

So in pymongo I did the same as:

```<code>db.collection.find(
    {"$and":[
    {"field":{"$regex":"bon?"}},
    {"field":{"$not":{"$regex":"bon souple"}}},
    {"field":{"$not":{"$regex":"bon léger"}}}
    ]}
    )
</code>```

but it indicatespymongo.errors.OperationFailure: $regex has to be a string.

So I tried this as proposed here:

```<code>liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}},
{'field': {'$regex': {'$not': re.compile('bon léger')}}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

I noticed that even when there is no special character it indicates the same error:

```<code>liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}} #where no special char is present
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

So I tried to use "/" as:

```<code>liste_reg=[
{'field': {'$regex': {'$not':'/bon souple/'}}} #where no special char is present
#even tried re.compile('/bon souple/')
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

the same error pymongo.errors.OperationFailure: $regex has to be a string still occurs.

What can I do?

SOME UPDATE OF MY RESEARCH OF SOLUTION

the core of the issue seems to be with $not because when I do:

```<code>liste_reg=[{'field': {'$regex': 'bon?'}}]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
len(rslt)#gives 23 013, what is ok.
</code>```

There is no error.

SOME SAMPLES

As asked by Emma I can give a sample, and it will explicit my request in mongo.
Normally I must have these modalities in the field:

sec

très léger

léger

bon léger

bon

bon souple

souple

très souple

collant

lourd

très Lourd

profond

The main problem for me is my spider did not parse correctly because I did not write a strong enough script for that.
Instead of obtaining just "bon", I obtain this kind of result:

```<code>{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon",
...}
</code>```

and that's an example between many others wrong parsing.
So that's why I want result that begins with "bon?" but not "bon souple" or "bon léger" because they have correct values, no \n or \t.

So as samples:

```<code>[{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon"},
{"_id":"ID2",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpremière"},
{"_id":"ID3",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t2ème"},
{"_id":"ID4",
"field":"bon souple"},
{"_id":"ID5",
"field":"bon léger"}]
</code>```

答:
Here, we might be able to approach solving this problem, maybe without using the $not feature. For instance, if we wish to not have bon souple or bon léger which are bon followed by an space, we could maybe use an expression similar to:

```<code>"bon[^\s].+"
</code>```

DEMO

I'm not so sure about what we wish to extract here, but I was just guessing that maybe we would want to swipe bon values not followed by an space and in between the ".

Also, we would likely want to look into regex query requirements and adjust our expressions to it, if necessary, such as with escaping or using capturing group:

```<code>(bon[^\s].+)
</code>```

or:

```<code>"(bon[^\s].+)"
</code>```

or:

```<code>\"(bon[^\s].+)\"
</code>```

or:

```<code>([\s\S]*?)\"(bon[^\s].+)\"
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

I'm not quite sure if this would be what we might want or if it would be relevant, yet according to this documentation, we can try using:

```<code>{ name: { $regex: /([\s\S]*?)\"(bon[^\s].+)\"/, $options: "mi" } }
</code>```

or:

```<code>{ name: { $regex: '([\s\S]*?)\"(bon[^\s].+)\"', $options: "mi" } }
</code>```

db.collection.find

```<code>db.collection.find({"field":{ $regex: /(bon[^\s].+)/, $options: "mi" }})
</code>```

or:

```<code>db.collection.find({"field":{ $regex: /(bon[^\s].+)/, $options: "si" }})
</code>```

Reference:

PyMongo $in + $regex

Performing regex Queries with pymongo

Body:
I use python 3.7.1 (default, Dec 14 2018, 19:28:38), and pymongo 3.7.2.

In mongodb this works:

db.collection.find(
    {$and:[
    {"field":{$regex:"bon?"}},
    {"field":{$not:{$regex:"bon souple"}}},
    {"field":{$not:{$regex:"bon léger"}}}
    ]}
    )

So in pymongo I did the same as:

db.collection.find(
    {"$and":[
    {"field":{"$regex":"bon?"}},
    {"field":{"$not":{"$regex":"bon souple"}}},
    {"field":{"$not":{"$regex":"bon léger"}}}
    ]}
    )

but it indicatespymongo.errors.OperationFailure: $regex has to be a string.

So I tried this as proposed here:

liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}},
{'field': {'$regex': {'$not': re.compile('bon léger')}}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

I noticed that even when there is no special character it indicates the same error:

liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}} #where no special char is present
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

So I tried to use "/" as:

liste_reg=[
{'field': {'$regex': {'$not':'/bon souple/'}}} #where no special char is present
#even tried re.compile('/bon souple/')
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

the same error pymongo.errors.OperationFailure: $regex has to be a string still occurs.

What can I do?

SOME UPDATE OF MY RESEARCH OF SOLUTION

the core of the issue seems to be with $not because when I do:

liste_reg=[{'field': {'$regex': 'bon?'}}]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
len(rslt)#gives 23 013, what is ok.

There is no error.

SOME SAMPLES

As asked by Emma I can give a sample, and it will explicit my request in mongo.
Normally I must have these modalities in the field:

sec

très léger

léger

bon léger

bon

bon souple

souple

très souple

collant

lourd

très Lourd

profond

The main problem for me is my spider did not parse correctly because I did not write a strong enough script for that.
Instead of obtaining just "bon", I obtain this kind of result:

{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon",
...}

and that's an example between many others wrong parsing.
So that's why I want result that begins with "bon?" but not "bon souple" or "bon léger" because they have correct values, no \n or \t.

So as samples:

[{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon"},
{"_id":"ID2",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpremière"},
{"_id":"ID3",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t2ème"},
{"_id":"ID4",
"field":"bon souple"},
{"_id":"ID5",
"field":"bon léger"}]

Body:
Here, we might be able to approach solving this problem, maybe without using the $not feature. For instance, if we wish to not have bon souple or bon léger which are bon followed by an space, we could maybe use an expression similar to:

"bon[^\s].+"

DEMO

I'm not so sure about what we wish to extract here, but I was just guessing that maybe we would want to swipe bon values not followed by an space and in between the ".

Also, we would likely want to look into regex query requirements and adjust our expressions to it, if necessary, such as with escaping or using capturing group:

(bon[^\s].+)

or:

"(bon[^\s].+)"

or:

\"(bon[^\s].+)\"

or:

([\s\S]*?)\"(bon[^\s].+)\"

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

I'm not quite sure if this would be what we might want or if it would be relevant, yet according to this documentation, we can try using:

{ name: { $regex: /([\s\S]*?)\"(bon[^\s].+)\"/, $options: "mi" } }

or:

{ name: { $regex: '([\s\S]*?)\"(bon[^\s].+)\"', $options: "mi" } }

db.collection.find

db.collection.find({"field":{ $regex: /(bon[^\s].+)/, $options: "mi" }})

or:

db.collection.find({"field":{ $regex: /(bon[^\s].+)/, $options: "si" }})

Reference:

PyMongo $in + $regex

Performing regex Queries with pymongo


答:
```<code>SELECT code, MAX(start_date)
FROM movies
GROUP BY code
</code>```

Title: POSTGRES - LIMIT 1 DESC for each ID in WHERE IN


问:
what is the problem with oauth 2.0 and how open id connect fixes it?
I read the article by Dominick Baier and what he says in his article that there are problems with Oauth 2.0 and Open Id connect fixes it.

Since, I'm new to Oauth and Opend Id, not sure what are the problems with Oauth and how does Open Id fixes it?

Anybody can shed some light?

答:
A good read is here https://oauth.net/articles/authentication/ :

The OAuth 2.0 specification defines a delegation protocol that is
  useful for conveying authorization decisions across a network of
  web-enabled applications and APIs. OAuth is used in a wide variety of
  applications, including providing mechanisms for user authentication.
  This has led many developers and API providers to incorrectly conclude
  that OAuth is itself an authentication protocol and to mistakenly use
  it as such. Let's say that again, to be clear:

OAuth 2.0 is not an authentication protocol.

Much of the confusion
  comes from the fact that OAuth is used inside of authentication
  protocols, and developers will see the OAuth components and interact
  with the OAuth flow and assume that by simply using OAuth, they can
  accomplish user authentication. This turns out to be not only untrue,
  but also dangerous for service providers, developers, and end users.

This article is intended to help potential identity providers with the
  question of how to build an authentication and identity API using
  OAuth 2.0 as the base. Essentially, if you're saying "I have OAuth
  2.0, and I need authentication and identity", then read on.


问:
Return 0 to second instance of duplicate
I have a similar data set to the following:

```<code>A  B   C
1  10  5
1  20  1
2  30  1
2  30  1
</code>```

I'd like to add a column returning 1, until we hit a duplicate of A & B, when I need to return a 0, but only for the second instance, so:

```<code>A  B   C  D
1  10  5  1
1  20  1  1
2  30  1  1
2  30  1  0
</code>```

Any help appreciated.

答:
Just a doodle with library(dplyr):

df %>% group_by(A,B) %>% mutate(D = +((1:n())==1))
```

<p>Or if you want it to be zero <em>"only for the second instance"</em>, meaning the third instance would be also one, then the following works:</p>

<pre class="lang-r prettyprint-override"><code>df %>% group_by(A,B) %>% mutate(D = +!((1:n())==2))
</code>```

In the example your duplicates are not for A and B only but also C. If that's actually the case, you can use group_by_all instead of group_by(A,B).

Body:
I have a similar data set to the following:

A  B   C
1  10  5
1  20  1
2  30  1
2  30  1

I'd like to add a column returning 1, until we hit a duplicate of A & B, when I need to return a 0, but only for the second instance, so:

A  B   C  D
1  10  5  1
1  20  1  1
2  30  1  1
2  30  1  0

Any help appreciated.

Body:
Just a doodle with library(dplyr):

df %>% group_by(A,B) %>% mutate(D = +((1:n())==1))

Or if you want it to be zero "only for the second instance", meaning the third instance would be also one, then the following works:

df %>% group_by(A,B) %>% mutate(D = +!((1:n())==2))

In the example your duplicates are not for A and B only but also C. If that's actually the case, you can use group_by_all instead of group_by(A,B).


问:
Reading single document from DocumentDB
I cannot read single document by id from DocumentDB. I am building application and I have exact problem like this one. I don't understand what am I missing. Let's say I have Users collection and I have /UserId for my partition key, I cannot read document I always receive "Resource Not Found". It is confusing because according to Microsoft's documentation I can only supply Uri to ReadDocumentAsync method, but doing that I get error partition key is required. I inderstand partition keys, but I have hard time understanding how are they connected to document. For example, my partition key is /UserId, which is a path, for method ReadDocumentAsync I actually have to provide value of partition key. And I have hard time understanding what is that value.

I attempted creating document with c# code and retrieving same document with ID created by system (GUID) it does not work... This sound simple and basic, but can someone point out to me where am I wrong? Or show me a reference to C# .NET Core code that I can use, sample collection, sample document and sample code. Microsoft's documentation/sample code does not work for me.

My code looks like this:

```<code>            documentId = "1c230b2d-1e37-9e02-d3a0-10364a188487";
            collectionId = "Users";
            RequestOptions options = new RequestOptions();
            options.PartitionKey = new PartitionKey("201801-M");
            var document = await _serverConnection.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, documentId),options);
            return document;
</code>```

My DB looks like this:

And my Partition Key looks like this:

答:
I had this problem. The solution for me was ensuring that the PartitionKey with its value were written to the json data object exactly as it is in the collection. For example, if your collection's partition key is /state and you want a value of "Florida" then in your json data object must contain the following in your json data: "state":"Florida" in your WriteDocumentAsync. In my case I am using dynamic json data so I had to inject the partitionkey and value into my json data object. If it is not done correctly you will get and error, Entity with specified id was not found when you try to read the data.
You have two choice: 1 write the data out with a matching partition key to the collection's or 2 in your request options use "Undefined.Value" for the partition key. Using the Undefined.Value will find any matching id in the collection.
When reading the document back using ReadDocumentAsync you must set your RequestOptions.PartitionKey to your desired partition key value you are seeking.
Hope this helps.

Title: Reading single document from DocumentDB

Body:
I cannot read single document by id from DocumentDB. I am building application and I have exact problem like this one. I don't understand what am I missing. Let's say I have Users collection and I have /UserId for my partition key, I cannot read document I always receive "Resource Not Found". It is confusing because according to Microsoft's documentation I can only supply Uri to ReadDocumentAsync method, but doing that I get error partition key is required. I inderstand partition keys, but I have hard time understanding how are they connected to document. For example, my partition key is /UserId, which is a path, for method ReadDocumentAsync I actually have to provide value of partition key. And I have hard time understanding what is that value.

I attempted creating document with c# code and retrieving same document with ID created by system (GUID) it does not work... This sound simple and basic, but can someone point out to me where am I wrong? Or show me a reference to C# .NET Core code that I can use, sample collection, sample document and sample code. Microsoft's documentation/sample code does not work for me.

My code looks like this:

            documentId = "1c230b2d-1e37-9e02-d3a0-10364a188487";
            collectionId = "Users";
            RequestOptions options = new RequestOptions();
            options.PartitionKey = new PartitionKey("201801-M");
            var document = await _serverConnection.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, documentId),options);
            return document;

My DB looks like this:

And my Partition Key looks like this:


问:
strip interval's (inconsistent) start and end date within a large data frame
I have a data frame which consists of 2 columns.
Date  - Quarterly date
Indicator Value - Ranges from 1 to -1 for a given date.

```<code>Date(Quarter)   Indicator Value

1872-12-31        0.5
1873-03-31       -0.2
1873-06-30       -0.15
1873-09-30        0.7
1873-12-31        0.4
1874-03-31        0.9
1874-06-30       -0.3
1874-09-30       -0.1
1874-12-31        0.8
</code>```

I am interested in negative value cycle. I want to get the start and end date for all negative values but not individually. For example,

```<code>First one starts at 1873/01/01 and ends in 1873/06/30
The second one starts at 1874/04/01 and ends in 1874/09/30
</code>```

I tried creating binary values. For example, all the positive will still have zero and the negative numbers will have 1. Then I can strip out smaller data frames and get the dates.

It seems like I am making this harder it looks.

def f(row):
    if row['Indicator value'] < 0:
        val = 1
    else:
        val = 0
    return val

df['Binary Value'] = df3.apply(f, axis = 1)
```

<p>Data frame looked liked this:</p>

```    Date(Quaterly)   Indicator Value    Binary Value

1872-12-31        0.5                  0
1873-03-31       -0.2                  1
1873-06-30       -0.15                 1
1873-09-30        0.7                  0
1873-12-31        0.4                  0
1874-03-31        0.9                  0
1874-06-30       -0.3                  1
1874-09-30       -0.1                  1
1874-12-31        0.8                  0
```

<p>I am kind of stuck after this. I don't know where to go from here. </p>

<p>I want to create a list of start and end dates </p>

```Start Date     End date
1873/01/01     1873/06/30
1874/04/01     1874/09/30
```

答:
```<code>g = (df['Indicator Value'].gt(0) == df['Indicator Value'].lt(0).shift()).cumsum()
g.name = 'value'

df = df.groupby(g).apply(lambda x: x.iloc[np.r_[0:1, -1:0]])

allneg = df[df['Indicator Value'].lt(0)].reset_index().drop(columns = ['value','level_1'])

pd.DataFrame(np.hstack([allneg.loc[::2, 'Date(Quarter)'].values.reshape(-1,1), allneg.loc[1::2, 'Date(Quarter)'].values.reshape(-1,1)]))\
  .rename(columns = {0:'Start Date', 1:'End Date'})

    Start Date   End Date
0   1873-03-31  1873-06-30
1   1874-06-30  1874-09-30
</code>```

g is the creation of groupings that we want for our Indicator Value column. The value goes up whenever the sign changes.

We then group by g, then apply a function that takes the first value and last value in each group (so if there are 3 or more neg values in a row it will only take the first and the last).

Next we filter out the positive values and do a little cleaning. Finally, we manipulate allneg to get just the starting and ending dates and make it a new dataframe.

For my start dates, I use the initial negative one, I'm not sure where you got yours from.

Body:
I have a data frame which consists of 2 columns.
Date  - Quarterly date
Indicator Value - Ranges from 1 to -1 for a given date.

Date(Quarter)   Indicator Value

1872-12-31        0.5
1873-03-31       -0.2
1873-06-30       -0.15
1873-09-30        0.7
1873-12-31        0.4
1874-03-31        0.9
1874-06-30       -0.3
1874-09-30       -0.1
1874-12-31        0.8

I am interested in negative value cycle. I want to get the start and end date for all negative values but not individually. For example,

First one starts at 1873/01/01 and ends in 1873/06/30
The second one starts at 1874/04/01 and ends in 1874/09/30

I tried creating binary values. For example, all the positive will still have zero and the negative numbers will have 1. Then I can strip out smaller data frames and get the dates.

It seems like I am making this harder it looks.

def f(row):
    if row['Indicator value'] < 0:
        val = 1
    else:
        val = 0
    return val

df['Binary Value'] = df3.apply(f, axis = 1)

Data frame looked liked this:

    Date(Quaterly)   Indicator Value    Binary Value

1872-12-31        0.5                  0
1873-03-31       -0.2                  1
1873-06-30       -0.15                 1
1873-09-30        0.7                  0
1873-12-31        0.4                  0
1874-03-31        0.9                  0
1874-06-30       -0.3                  1
1874-09-30       -0.1                  1
1874-12-31        0.8                  0

I am kind of stuck after this. I don't know where to go from here.

I want to create a list of start and end dates

Start Date     End date
1873/01/01     1873/06/30
1874/04/01     1874/09/30

Body:
g = (df['Indicator Value'].gt(0) == df['Indicator Value'].lt(0).shift()).cumsum()
g.name = 'value'

df = df.groupby(g).apply(lambda x: x.iloc[np.r_[0:1, -1:0]])

allneg = df[df['Indicator Value'].lt(0)].reset_index().drop(columns = ['value','level_1'])

pd.DataFrame(np.hstack([allneg.loc[::2, 'Date(Quarter)'].values.reshape(-1,1), allneg.loc[1::2, 'Date(Quarter)'].values.reshape(-1,1)]))\
  .rename(columns = {0:'Start Date', 1:'End Date'})

    Start Date   End Date
0   1873-03-31  1873-06-30
1   1874-06-30  1874-09-30

g is the creation of groupings that we want for our Indicator Value column. The value goes up whenever the sign changes.

We then group by g, then apply a function that takes the first value and last value in each group (so if there are 3 or more neg values in a row it will only take the first and the last).

Next we filter out the positive values and do a little cleaning. Finally, we manipulate allneg to get just the starting and ending dates and make it a new dataframe.

For my start dates, I use the initial negative one, I'm not sure where you got yours from.


问:
Need help on Kafka to get data from web api GET Call
As of now we are using curl and GET call  to  get data from outside using their ENDPOINT URL.

i'm planning to setup a new process and is there anyway to leverage kafka here instead of CURL.

unfortunately we dont have kafka confluent version.

答:
Kafka doesn't perform or accept HTTP calls.

You'd have to write some HTTP scraper, then combine this with a Kafka producer.

Note: You don't need Confluent Platform to just setup and run their REST proxy next to your existing brokers


问:
Automate SQL Server database schema only Backups
I need to backup SQL Server schema of all databases on a daily basis. This way I don't have to restore the whole 700GB database for a single table structure.

Any help is appreciated.

Thanks

答:
You can extract a .dacpac file and it will contain definition of all object in the database. Then you will use it in Visual Studio schema compare to find changed objects.

Obfuscated ("encrypted") stored procedures will not be included in the extract.

Sample script:

```<code>## Set a SMO Server object to the default instance on the local computer.
CD SQLSERVER:\SQL\localhost\DEFAULT
$srv = get-item .

## Specify the database to extract to a DAC.
$dbname = "MyDB"

## Specify the DAC metadata.
$applicationname = "MyApplication"
$version = "1.0.0.0"
$description = "This DAC defines the database used by my application."

## Specify the location and name for the extracted DAC package.
$dacpacPath = "C:\MyDACs\MyApplication.dacpac"

## Extract the DAC.
$extractionunit = New-Object Microsoft.SqlServer.Management.Dac.DacExtractionUnit($srv, $dbname, $applicationname, $version)
$extractionunit.Description = $description
$extractionunit.Extract($dacpacPath)
</code>```

Body:
You can extract a .dacpac file and it will contain definition of all object in the database. Then you will use it in Visual Studio schema compare to find changed objects.

Obfuscated ("encrypted") stored procedures will not be included in the extract.

Sample script:

## Set a SMO Server object to the default instance on the local computer.
CD SQLSERVER:\SQL\localhost\DEFAULT
$srv = get-item .

## Specify the database to extract to a DAC.
$dbname = "MyDB"

## Specify the DAC metadata.
$applicationname = "MyApplication"
$version = "1.0.0.0"
$description = "This DAC defines the database used by my application."

## Specify the location and name for the extracted DAC package.
$dacpacPath = "C:\MyDACs\MyApplication.dacpac"

## Extract the DAC.
$extractionunit = New-Object Microsoft.SqlServer.Management.Dac.DacExtractionUnit($srv, $dbname, $applicationname, $version)
$extractionunit.Description = $description
$extractionunit.Extract($dacpacPath)


问:
Using Silverlight for an entire website?
We need to build an administration portal website to support our client/server application. Since we're a .Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend?

The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application.

I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills.

Are there any big no-nos from the experience of StackOverflowers? What are the big positives?

答:
I would definitely go for a full Silverlight application, specially if you have good experience from WPF. You will be able to reuse your knowledge from WPF, and should be able to pick up Silverlight fairly quickly. I've been working with Silverlight since Beta 1, and the current Beta 2 is of solid quality. I guess it's safe to assume that a RTW version is just around the corner.

Pilf has some valid point, specially around printing. For that I would probably use SQL Reporting Services, or some other reporting framework, on the server side, and then pop up a new window with printable reports. For linking and bookmarking the issues are no different than any other AJAX application. I did a blog post today about how to provide deep linking and back-forward navigation in Silverlight.

Silverlight also has all the hooks needed for great accessibility support, as the UI Automation API from WPF is brought into Silverlight. I don't know if the screen reader vendors have caught up yet. The styling/template support in Silverlight makes it easy to provide high-contrast skins for visual impaired users if that is a concern.

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sam

OwnerDisplayName: Jonas Follesø


问:
C#: How to add an attributes to an object at run-time?
As an entity class, I want to add an attributes at run-time, how should I do?</p>

答:
Take a look at the Dynamic Language Runtime. You also might consider a dynamic language like IronRuby or IronPython.

What problam are you trying to solve?

http://en.wikipedia.org/wiki/Dynamic_Language_Runtime

LastEditorDisplayName: Samuel

OwnerDisplayName: Ralph


问:
Efficient large dicts of dicts to represent M:M relationships in Python
I have a very large dataset - millions of records - that I want to store in Python.  I might be running on 32-bit machines so I want to keep the dataset down in the hundreds-of-MB range and not ballooning much larger than that.

These records - represent a M:M relationship - two IDs (foo and bar) and some simple metadata like timestamps (baz).

Some foo have too nearly all bar in them, and some bar have nearly all foo.  But there are many bar that have almost no foos and many foos that have almost no bar.

If this were a relational database, a M:M relationship would be modelled as a table with a compound key.  You can of course search on either component key individually comfortably.

If you store the rows in a hashtable, however, you need to maintain three hashtables as the compound key is hashed and you can't search on the component keys with it.

If you have some kind of sorted index, you can abuse lexical sorting to iterate the first key in the compound key, and need a second index for the other key; but its less obvious to me what actual data-structure in the standard Python collections this equates to.

I am considering a dict of foo where each value is automatically moved from tuple (a single row) to list (of row tuples) to dict depending on some thresholds, and another dict of bar where each is a single foo, or a list of foo.

Are there more efficient - speedwise and spacewise - ways of doing this?  Any kind of numpy for indices or something?

(I want to store them in Python because I am having performance problems with databases - both SQL and NoSQL varieties.  You end up being IPC memcpy and serialisation-bound.  That is another story; however the key point is that I want to move the data into the application rather than get recommendations to move it out of the application ;) )

答:
NoSQL systems like redis don't provide MM tables.

In the end, a python dict keyed by pairs holding the values, and a dict of the set of pairings for each term was the best I could come up with.

```<code>class MM:
    def __init__(self):
        self._a = {} # Bs for each A
        self._b = {} # As for each B
        self._ab = {}
</code>```

Body:
NoSQL systems like redis don't provide MM tables.

In the end, a python dict keyed by pairs holding the values, and a dict of the set of pairings for each term was the best I could come up with.

class MM:
    def __init__(self):
        self._a = {} # Bs for each A
        self._b = {} # As for each B
        self._ab = {}