问:
Using percent ( % ) sign in react-router :id
I'm trying to use a percent sign in a react-router id. As using % in URI is forbidden, I have to encode my URI manually to be able to use this percent sign. Using a Link, I therefore use the encodeURI function to encode the URI:

```<code><Link to={`/r/${encodeURI(my_str_with_unencoded_percent_sign)}`} >
</code>```

In the source code of my page, I can see that the link uses %25 and not %.

Still, when clicking on the link, I get the error "URIError: malformed URI sequence" (in another part of my code, I have a
<Match pattern="/r/:id" …).

What did I do wrong? It seems the url is decoded before being passed to the parseParams function of react-router, which tries to decode it a second time, which leads to this error.

I found issues such as https://github.com/ReactTraining/history/issues/461 or https://github.com/ReactTraining/history/issues/461, but I didn't find any solution to this problem: how can I use a percent sign in a react-router :id ?

答:
Here is a working modified version of the URL Parameters example provided by Recat-Training.

Copy paste the below into your index.js and test it to see it works. I was going to provide a codesandbox of this for you, but their internal routing has issues that cause the screen to go black even with uri encoded % signs... I did test this locally and works like a charm.

```<code>import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const ParamsExample = () => (
  <Router>
    <div>
      <h2>Accounts</h2>
      <ul>
        <li><Link to={`/${encodeURI("%netflix")}`}>Netflix</Link></li>
        <li><Link to="/zillow-group">Zillow Group</Link></li>
        <li><Link to="/yahoo">Yahoo</Link></li>
        <li><Link to="/modus-create">Modus Create</Link></li>
      </ul>

      <Route path="/:id" component={Child} />
    </div>
  </Router>
)

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

render(<ParamsExample />, document.getElementById("react"));
</code>```

Body:
I'm trying to use a percent sign in a react-router id. As using % in URI is forbidden, I have to encode my URI manually to be able to use this percent sign. Using a Link, I therefore use the encodeURI function to encode the URI:

<Link to={`/r/${encodeURI(my_str_with_unencoded_percent_sign)}`} >

In the source code of my page, I can see that the link uses %25 and not %.

Still, when clicking on the link, I get the error "URIError: malformed URI sequence" (in another part of my code, I have a
<Match pattern="/r/:id" …).

What did I do wrong? It seems the url is decoded before being passed to the parseParams function of react-router, which tries to decode it a second time, which leads to this error.

I found issues such as https://github.com/ReactTraining/history/issues/461 or https://github.com/ReactTraining/history/issues/461, but I didn't find any solution to this problem: how can I use a percent sign in a react-router :id ?

Body:
Here is a working modified version of the URL Parameters example provided by Recat-Training.

Copy paste the below into your index.js and test it to see it works. I was going to provide a codesandbox of this for you, but their internal routing has issues that cause the screen to go black even with uri encoded % signs... I did test this locally and works like a charm.

import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const ParamsExample = () => (
  <Router>
    <div>
      <h2>Accounts</h2>
      <ul>
        <li><Link to={`/${encodeURI("%netflix")}`}>Netflix</Link></li>
        <li><Link to="/zillow-group">Zillow Group</Link></li>
        <li><Link to="/yahoo">Yahoo</Link></li>
        <li><Link to="/modus-create">Modus Create</Link></li>
      </ul>

      <Route path="/:id" component={Child} />
    </div>
  </Router>
)

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

render(<ParamsExample />, document.getElementById("react"));


来源: stackexchange

问:
Dynamically change the path of imported component in Angular 2 s
I want to change the path of imported component dynamically according to built environment.

Like when I am building my app with below command:

```<code>ng build --environment client1-testing --output-path ../dist/my-app
</code>```

Then in app.module.ts I am importing a component like this:

```<code>import { ClientComponent } from './components/client1/client1.component';
</code>```

I want to make the ClientComponent path dynamic like if I am building app for client1 then path should be

```<code>'./components/client1/client.component';
</code>```

If I am building app for client2 then path should be

```<code>'./components/client2/client.component';
</code>```

I am new to Angular so don't know how to implement it. We have separate folders for every client and want to import Components from those folders dynamically.

答:
I think you should consider looking at Dynamic Components as because AFAIK, you cannot change the component path based on the env variables in Angular.

What you can do is have a environment set up which will make a particular variable as true and then use it in creating a Dynamic Component like.

```<code>export const environment = {
  production: false,
  client1: true,
  client2:true
};
</code>```

Dynamic Component

From here on it is a gist you have to use the data inside your Builder component to create a particular component for the client.

More on How to create Dynamic Component

Small Snippet from the Link

```<code>//pass data to this component like from any other component
<dynamic [componentData] = "componentData"></dynamic>

// Dynamic Logic
import { Component, OnInit, Input, ViewChild, ViewContainerRef, ComponentFactoryResolver, ReflectiveInjector } from '@angular/core';
import { AngularService } from "app/shared/angular.service";

import { HelloWorldComponent } from 'app/dynamic-component/dynamic/hello-world-component';
import { WorldHelloComponent } from './world-hello-component';

@Component({
  selector: 'dynamic',
  entryComponents: [HelloWorldComponent, WorldHelloComponent],
  template: `<div #dynamicContainer></div>`
})
export class DynamicComponent implements OnInit{

  currentComponent = null;

  @ViewChild('dynamicContainer' , {read : ViewContainerRef}) decorator : ViewContainerRef;  // this is the container where we
  // we will load our dynamic component in short Represents a container where one or more Views can be attached.
  @Input() set componentData (data : {component: any , inputs :any}){ // getting the input from the called component which instantiates this component
    if (!data){
      return;
    }
    // Inputs need to be in the following format to be resolved properly
    let inputProviders = Object.keys(data.inputs).map((inputName) => {return {provide: inputName, useValue: data.inputs[inputName]};});
    let resolvedInputs = ReflectiveInjector.resolve(inputProviders);

    // We create an injector out of the data we want to pass down and this components injector
    let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.decorator.parentInjector);

    // We create a factory out of the component we want to create
    let factory = this.resolver.resolveComponentFactory(data.component);

    // We create the component using the factory and the injector
    let component = factory.create(injector);
    //console.log(component.hostView);
    // We insert the component into the dom container
    this.decorator.insert(component.hostView);
    // We can destroy the old component is we like by calling destroy
    // keep this if you want only one instacne of the component as in this example else remove it and play around
    if (this.currentComponent) {
      this.currentComponent.destroy();
    }

    this.currentComponent = component;
    this.currentComponent.instance.ref = component; // this method passes the ref of the component to the dynamic component which helps
    //us to destroy the component at will

  }

  constructor(private resolver : ComponentFactoryResolver) {}

  ngOnInit() {

  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to change the path of imported component dynamically according to built environment.

Like when I am building my app with below command:

ng build --environment client1-testing --output-path ../dist/my-app

Then in app.module.ts I am importing a component like this:

import { ClientComponent } from './components/client1/client1.component';

I want to make the ClientComponent path dynamic like if I am building app for client1 then path should be

'./components/client1/client.component';

If I am building app for client2 then path should be

'./components/client2/client.component';

I am new to Angular so don't know how to implement it. We have separate folders for every client and want to import Components from those folders dynamically.

Body:
I think you should consider looking at Dynamic Components as because AFAIK, you cannot change the component path based on the env variables in Angular.

What you can do is have a environment set up which will make a particular variable as true and then use it in creating a Dynamic Component like.

export const environment = {
  production: false,
  client1: true,
  client2:true
};

Dynamic Component

From here on it is a gist you have to use the data inside your Builder component to create a particular component for the client.

More on How to create Dynamic Component

Small Snippet from the Link

//pass data to this component like from any other component
<dynamic [componentData] = "componentData"></dynamic>

// Dynamic Logic
import { Component, OnInit, Input, ViewChild, ViewContainerRef, ComponentFactoryResolver, ReflectiveInjector } from '@angular/core';
import { AngularService } from "app/shared/angular.service";

import { HelloWorldComponent } from 'app/dynamic-component/dynamic/hello-world-component';
import { WorldHelloComponent } from './world-hello-component';

@Component({
  selector: 'dynamic',
  entryComponents: [HelloWorldComponent, WorldHelloComponent],
  template: `<div #dynamicContainer></div>`
})
export class DynamicComponent implements OnInit{

  currentComponent = null;

  @ViewChild('dynamicContainer' , {read : ViewContainerRef}) decorator : ViewContainerRef;  // this is the container where we
  // we will load our dynamic component in short Represents a container where one or more Views can be attached.
  @Input() set componentData (data : {component: any , inputs :any}){ // getting the input from the called component which instantiates this component
    if (!data){
      return;
    }
    // Inputs need to be in the following format to be resolved properly
    let inputProviders = Object.keys(data.inputs).map((inputName) => {return {provide: inputName, useValue: data.inputs[inputName]};});
    let resolvedInputs = ReflectiveInjector.resolve(inputProviders);

    // We create an injector out of the data we want to pass down and this components injector
    let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.decorator.parentInjector);

    // We create a factory out of the component we want to create
    let factory = this.resolver.resolveComponentFactory(data.component);

    // We create the component using the factory and the injector
    let component = factory.create(injector);
    //console.log(component.hostView);
    // We insert the component into the dom container
    this.decorator.insert(component.hostView);
    // We can destroy the old component is we like by calling destroy
    // keep this if you want only one instacne of the component as in this example else remove it and play around
    if (this.currentComponent) {
      this.currentComponent.destroy();
    }

    this.currentComponent = component;
    this.currentComponent.instance.ref = component; // this method passes the ref of the component to the dynamic component which helps
    //us to destroy the component at will

  }

  constructor(private resolver : ComponentFactoryResolver) {}

  ngOnInit() {

  }


问:
Add implicit promotion to complex class, last step
I would like to allow implicit conversion when summing complex numbers.
For example:

```<code> complex<double> a;
 complex<long double> b;
 int i;

 auto sum = a + b; // (1)
 auto SUM = a + i; // (2)
</code>```

I have the code that enable conversion (1) thanks to answer implicit type promotion in summing two complex<>
In order to enable also the (2) conversion I used enable_if_t

```<code>  template <typename T, typename U>
  auto operator +(const ::std::complex<T> &a,     std::enable_if_t<std::is_arithmetic<U>::value, U>  &b)
  {
   typedef decltype(::std::declval<T>() + ::std::declval<U>()) comcomp_t;
   typedef ::std::complex<comcomp_t> result_t;
   return ::std::operator +(result_t{a}, result_t{b});
  }
</code>```

However, I got a compilation error saying "couldn't deduce template paramter 'U'. I guess my comprehension of SFINAE is very shallow. Any help would be highly appreciated. Thanks

答:
The second argument is a non-deduced context. You have to rewrite this so that U can actually be deduced. The typical way is to stick the SFINAE into the return type.

```<code> template <typename T, typename U>
 using add_t = decltype(std::declval<T>() + std::declval<U>());

 template <typename T, typename U>
 auto operator+(const std::complex<T>& a, const U& b)
     -> std::enable_if_t<std::is_arithmetic<U>::value,
                         std::complex<add_t<T, U>>>
 {
     std::complex<add_t<T, U>> res = a;
     res += b;
     return res;
 }
</code>```

Body:
I would like to allow implicit conversion when summing complex numbers.
For example:

 complex<double> a;
 complex<long double> b;
 int i;

 auto sum = a + b; // (1)
 auto SUM = a + i; // (2)

I have the code that enable conversion (1) thanks to answer implicit type promotion in summing two complex<>
In order to enable also the (2) conversion I used enable_if_t

  template <typename T, typename U>
  auto operator +(const ::std::complex<T> &a,     std::enable_if_t<std::is_arithmetic::value, U>  &b)
  {
   typedef decltype(::std::declval<T>() + ::std::declval()) comcomp_t;
   typedef ::std::complex<comcomp_t> result_t;
   return ::std::operator +(result_t{a}, result_t{b});
  }

However, I got a compilation error saying "couldn't deduce template paramter 'U'. I guess my comprehension of SFINAE is very shallow. Any help would be highly appreciated. Thanks

Body:
The second argument is a non-deduced context. You have to rewrite this so that U can actually be deduced. The typical way is to stick the SFINAE into the return type.

 template <typename T, typename U>
 using add_t = decltype(std::declval<T>() + std::declval<U>());

 template <typename T, typename U>
 auto operator+(const std::complex<T>& a, const U& b)
     -> std::enable_if_t<std::is_arithmetic<U>::value,
                         std::complex<add_t<T, U>>>
 {
     std::complex<add_t<T, U>> res = a;
     res += b;
     return res;
 }


问:
How can I have my bot start in a different dialog depending on user
Basically, I want to have my bot on different pages using iframes and Bot Framework Web Chat.

Depending on what page the user opens the bot, a different dialog is called.

Without Direct Line, this is as simple as adding a query parameter to api/messages and adjust the controller. But with Direct Line, I can only specify one endpoint in the portal.

I tried to change user.id in the JavaScript BotChat.App call to a different identifier and then select the correct dialog in my MessagesController based on that.
BUT: my custom id doesn't seem to be available as early as the activity "ConversationUpdate" occures where I send my welcome message. I need to send a dialog-specific welcome message though (so I need to navigate there as soon as possible and not only when the user types his first message).

答:
Take a look at the backchannel.  In your scenario you can pass a parameter from the Javascript via the back channel to set some value in UserData.  Now your parameter will exist in state (in this case the IDataBag UserData) when your user first hits the bot.

Here is a C# sample of a 2-way backchannel

another C# sample using a 1 way backchannel


问:
Split after n words Power BI
I have this in PowerBI : Data
And I would like to split the data after the 2 first words.

Any idea ?

答:
Try creating these two custom columns in the Query Editor:

Left Text: Text.BeforeDelimiter([Colonne 2], " ", 1)

Right Text: Text.AfterDelimiter([Colonne 2], " ", 1)

This searches for the second space (the index starts at 0) in Colonne 2 and gives you the part before or the part after.

Title: Split after n words Power BI


问:
How to remove the coulmn name in Json in c#
For example this is my JSON:

```<code>[
   {
      "id":1,
      "name":"Core"
   },
   {
      "id":2,
      "name":"Moderate"
   },
   {
      "id":3,
      "name":"Remote"
   }
]
</code>```

How can I remove id and name?

My desired output:

```<code>[
  {
    "1":"Core"
  },
  {
    "2":"Moderate"
  },
  {
    "3":"Remote"
  }
]
</code>```

答:
You can do it like this:     </p>

```<code>            JArray arr = JArray.Parse(json);

            foreach (var el in arr.ToList())
            {
              var obj = new JObject();
              obj[el["id"].Value<string>()] = el["name"].Value<string>();
              el.Replace(obj);
            }

            var res = arr.ToString();
</code>```

Body:
For example this is my JSON:

[
   {
      "id":1,
      "name":"Core"
   },
   {
      "id":2,
      "name":"Moderate"
   },
   {
      "id":3,
      "name":"Remote"
   }
]

How can I remove id and name?

My desired output:

[
  {
    "1":"Core"
  },
  {
    "2":"Moderate"
  },
  {
    "3":"Remote"
  }
]

Body:
You can do it like this:

            JArray arr = JArray.Parse(json);

            foreach (var el in arr.ToList())
            {
              var obj = new JObject();
              obj[el["id"].Value<string>()] = el["name"].Value<string>();
              el.Replace(obj);
            }

            var res = arr.ToString();


问:
'no matching index found' when using ORDER BY
I've gone through all the questions and created a multitude of indexes that all work independently, but the second I try to add an ORDER BY I get an 'no matching index found.' error

These are the indexes I'm using

```<code>indexes:
- kind: gallery-public
  properties:
  - name: public
  - name: flavor
  - name: created
    direction : desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: public
  - name: created
    direction: desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: created
    direction: asc
- kind: get-all
  properties:
  - name: public
  - name: created
    direction: desc
- kind: get-all-old
  properties:
  - name: public
  - name: created
    direction: asc
- kind: get-all-two
  properties:
  - name: flavor
  - name: created
    direction: desc
</code>```

Every query works

```<code>SELECT * FROM upload WHERE flavor="whatever" AND public=true
</code>```

Until I add an ORDER BY, in which case nothing works. Such as:

```<code>SELECT * FROM upload WHERE public=true ORDER BY created DESC
</code>```

I've created all of those indexes, explicitly defined the description, left the order field to the end, and I still can't get it to work. What am I missing?

答:
There are more properties being returned by that query than public, created, and flavor.

Instead:

```<code>SELECT public,created,flavor FROM upload WHERE public=true ORDER BY created DESC
</code>```

Give us a sample record from SELECT * if that's not the case.

Any property(field) that is returned by a query must also be part of your custom index.

Body:
I've gone through all the questions and created a multitude of indexes that all work independently, but the second I try to add an ORDER BY I get an 'no matching index found.' error

These are the indexes I'm using

indexes:
- kind: gallery-public
  properties:
  - name: public
  - name: flavor
  - name: created
    direction : desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: public
  - name: created
    direction: desc
- kind: get-selfies
  properties:
  - name: flavor
  - name: created
    direction: asc
- kind: get-all
  properties:
  - name: public
  - name: created
    direction: desc
- kind: get-all-old
  properties:
  - name: public
  - name: created
    direction: asc
- kind: get-all-two
  properties:
  - name: flavor
  - name: created
    direction: desc

Every query works

SELECT * FROM upload WHERE flavor="whatever" AND public=true

Until I add an ORDER BY, in which case nothing works. Such as:

SELECT * FROM upload WHERE public=true ORDER BY created DESC

I've created all of those indexes, explicitly defined the description, left the order field to the end, and I still can't get it to work. What am I missing?

Body:
There are more properties being returned by that query than public, created, and flavor.

Instead:

SELECT public,created,flavor FROM upload WHERE public=true ORDER BY created DESC

Give us a sample record from SELECT * if that's not the case.

Any property(field) that is returned by a query must also be part of your custom index.


问:
Return top 5 rated computers
We asked people to rate, among 5 computers, which is their favorite. For each person, I want to get their top 3 ratings.

Sample Data:

```<code>Apple <-         c(1,2,3,4,5)
Dell <-          c(2,1,4,3,3)
Samsung <-       c(3,5,1,2,4)
Acer <-          c(4,4,2,1,1)
ChromeBook <-    c(5,3,5,5,2)
RespondentID <-  c(1,2,3,4,5)
df <- data.frame(RespondentID,Apple, Dell, Samsung,Acer, ChromeBook)
</code>```

What I hope to get is, for each respondent, what is the top 3 computers.

So essentially, for each row, how I do return the column names for the top 3 rated computers?

RespondentID FirstChoice  Second Choice  ThirdChoice
1             Apple           Dell        Samsung
2             Dell            Apple       Chromebook
.
.
.

答:
You can use gather() and spread() to better frame your data.

```<code>library(tidyverse)

df %>% gather(Computer, Rating, -RespondentID)

   RespondentID   Computer Rating
1             1      Apple      1
2             2      Apple      2
3             3      Apple      3
4             4      Apple      4
5             5      Apple      5
6             1       Dell      2
7             2       Dell      1
8             3       Dell      4
9             4       Dell      3
10            5       Dell      3
</code>```

You can then filter to only ratings 3 or higher, and then spread it back to columns.

```<code>df %>%
    gather(Computer, Rating, -RespondentID) %>%
    filter(Rating >= 3) %>%
    spread(Rating, Computer) %>%
    select(RespondentID,
           FirstChoice = `5`,
           SecondChoice = `4`,
           ThirdChoice = `3`)

  RespondentID FirstChoice SecondChoice ThirdChoice
1            1  ChromeBook         Acer     Samsung
2            2     Samsung         Acer  ChromeBook
3            3  ChromeBook         Dell       Apple
4            4  ChromeBook        Apple        Dell
5            5       Apple      Samsung        Dell
</code>```

Title: Return top 5 rated computers

Body:
We asked people to rate, among 5 computers, which is their favorite. For each person, I want to get their top 3 ratings.

Sample Data:

Apple <-         c(1,2,3,4,5)
Dell <-          c(2,1,4,3,3)
Samsung <-       c(3,5,1,2,4)
Acer <-          c(4,4,2,1,1)
ChromeBook <-    c(5,3,5,5,2)
RespondentID <-  c(1,2,3,4,5)
df <- data.frame(RespondentID,Apple, Dell, Samsung,Acer, ChromeBook)

What I hope to get is, for each respondent, what is the top 3 computers.

So essentially, for each row, how I do return the column names for the top 3 rated computers?

RespondentID FirstChoice  Second Choice  ThirdChoice
1             Apple           Dell        Samsung
2             Dell            Apple       Chromebook
.
.
.

Body:
You can use gather() and spread() to better frame your data.

library(tidyverse)

df %>% gather(Computer, Rating, -RespondentID)

   RespondentID   Computer Rating
1             1      Apple      1
2             2      Apple      2
3             3      Apple      3
4             4      Apple      4
5             5      Apple      5
6             1       Dell      2
7             2       Dell      1
8             3       Dell      4
9             4       Dell      3
10            5       Dell      3

You can then filter to only ratings 3 or higher, and then spread it back to columns.

df %>%
    gather(Computer, Rating, -RespondentID) %>%
    filter(Rating >= 3) %>%
    spread(Rating, Computer) %>%
    select(RespondentID,
           FirstChoice = `5`,
           SecondChoice = `4`,
           ThirdChoice = `3`)

  RespondentID FirstChoice SecondChoice ThirdChoice
1            1  ChromeBook         Acer     Samsung
2            2     Samsung         Acer  ChromeBook
3            3  ChromeBook         Dell       Apple
4            4  ChromeBook        Apple        Dell
5            5       Apple      Samsung        Dell


问:
CSS using z-index doesn't place child element behind its parent
I am trying to make a drop down menu that slides from header.
I have a header and inside it I have some div with border-bottom 1px line and background-color. Inside this div I would like to place logo, searchbox some links and a user profile button. When this button is clicked I would like to drop down menu below this button. Unfortunately this dropdown menu appears in front of header and not slides from behind of header (obscuring the header background and bottom-border line). I have tried solution like below (it is simplified version).

header {
  position: relative;
  z-index: 5;
}

.dropdown {
  background-color: yellow;
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
}

.background {
  position: absolute;
  background-color: #ccca;
  border-bottom: 1px solid black;
  width: 100%;
  height: 50px;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="background">
    <div class="dropdown">
    </div>
  </div>
</header></code>```

I have tried many z-index configurations and none of them seems to work.
1. div.background with z-index 2, div.dropdown with z-index 1 or even -1
2. div.background without z-index and position, div.dropdown with z-index -1 (here dropdown was behind header but menu links stopped working and menu was also behind main content of webpage)

How can I make my div.dropdown to slide from behind the header bar with background and border bottom line? Isn't it possible to have this div.dropdown inside header div tree as the descendant element.

答:
z-index is based on elements at the same level in the DOM, in other words, elements with the same parent.

Since your class="dropdown" element is a child of the class="background" element it can never be below its parent.

Body:
I am trying to make a drop down menu that slides from header.
I have a header and inside it I have some div with border-bottom 1px line and background-color. Inside this div I would like to place logo, searchbox some links and a user profile button. When this button is clicked I would like to drop down menu below this button. Unfortunately this dropdown menu appears in front of header and not slides from behind of header (obscuring the header background and bottom-border line). I have tried solution like below (it is simplified version).

header {
  position: relative;
  z-index: 5;
}

.dropdown {
  background-color: yellow;
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
}

.background {
  position: absolute;
  background-color: #ccca;
  border-bottom: 1px solid black;
  width: 100%;
  height: 50px;
  z-index: 2;
}

I have tried many z-index configurations and none of them seems to work.
1. div.background with z-index 2, div.dropdown with z-index 1 or even -1
2. div.background without z-index and position, div.dropdown with z-index -1 (here dropdown was behind header but menu links stopped working and menu was also behind main content of webpage)

How can I make my div.dropdown to slide from behind the header bar with background and border bottom line? Isn't it possible to have this div.dropdown inside header div tree as the descendant element.


问:
How should I determine if an MSAL account has an Exchange based email system? (got an exception)
I am working with MSAL and have a user who received the following error:

```<code>{
   "error":{
      "code":"ResourceNotFound",
      "message":"Resource could not be discovered.",
      "innerError":{
         "request-id":"99b44a33-e5cd-4b69-9730-32d72e1f4ebf",
         "date":"2016-12-11T03:51:37"
      }
   }
}
</code>```

The code is the default MSAL demo code:

```<code>    public async Task<ActionResult> ReadMail()
    {
        try
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, null,
                new ClientCredential(appKey), new MSALSessionCache(signedInUserID, this.HttpContext));
            string[] scopes = { "Mail.Read" };
            AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes);

            HttpClient hc = new HttpClient();
            hc.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", result.Token);
            HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me/messages");
            string rez = await hrm.Content.ReadAsStringAsync();
            ViewBag.Message = rez;

            return View();
        }
        catch (MsalSilentTokenAcquisitionException)
        {
            ViewBag.Relogin = "true";
            return View();
        }
        catch (Exception eee)
        {
            ViewBag.Error = "An error has occurred. Details: " + eee.Message;
            return View();
        }
    }
</code>```

It turns out that the integration is like this:

It's a Hybrid Exchange system

Some mailboxes are located on Office 365.

Some mailboxes are located on premise.

Other mailboxes are on a 3rd party mail system (Intermedia) (the directory syncs to AD Connect via a custom script)

Question

How should I defensively code for the above situation? (or similar hybrid situations)?

答:
Old question but it seems others have run into this.

This isn't really an MSAL issue since the token itself isn't the problem here. The exception stems from calling https://graph.microsoft.com/v1.0/me/messages when the user doesn't have an accessible mailbox.

You generally can determine which resources have been assigned to a user by looking at that user's provisionedPlans collection:

```<code> https://graph.microsoft.com/v1.0/me?$select=provisionedPlans
</code>```

This will return a collection resources that have been provisioned for the user. For example, this user does not have Exchange provisioned:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(provisionedPlans)/$entity",
    "provisionedPlans": [
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        }
    ]
}
```

<p>Compare this with this user that does have Excange provisioned:</p>

<pre class="lang-json prettyprint-override"><code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(provisionedPlans)/$entity",
    "provisionedPlans": [
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "MicrosoftOffice"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "exchange"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "MicrosoftCommunicationsOnline"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        }
    ]
}
</code>```

A similar property that may also be useful is assignedPlans. This returns the resources that have been assigned to the user and is useful for determining if provisioning simply hasn't occurred yet or for resources that are not formally "provisioned" such as Microsoft Teams.

That said, you should always defensively code for the possibility that a user doesn't have or lacks permission for a resource you're requesting. There are several scenarios where a resource may be inaccessible due to an outage or user permissions and the only sure fire way to handle these scenarios is to backstop with solid exception handling.

Body:
I am working with MSAL and have a user who received the following error:

{
   "error":{
      "code":"ResourceNotFound",
      "message":"Resource could not be discovered.",
      "innerError":{
         "request-id":"99b44a33-e5cd-4b69-9730-32d72e1f4ebf",
         "date":"2016-12-11T03:51:37"
      }
   }
}

The code is the default MSAL demo code:

    public async Task<ActionResult> ReadMail()
    {
        try
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, null,
                new ClientCredential(appKey), new MSALSessionCache(signedInUserID, this.HttpContext));
            string[] scopes = { "Mail.Read" };
            AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes);

            HttpClient hc = new HttpClient();
            hc.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", result.Token);
            HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me/messages");
            string rez = await hrm.Content.ReadAsStringAsync();
            ViewBag.Message = rez;

            return View();
        }
        catch (MsalSilentTokenAcquisitionException)
        {
            ViewBag.Relogin = "true";
            return View();
        }
        catch (Exception eee)
        {
            ViewBag.Error = "An error has occurred. Details: " + eee.Message;
            return View();
        }
    }

It turns out that the integration is like this:

It's a Hybrid Exchange system

Some mailboxes are located on Office 365.

Some mailboxes are located on premise.

Other mailboxes are on a 3rd party mail system (Intermedia) (the directory syncs to AD Connect via a custom script)

Question

How should I defensively code for the above situation? (or similar hybrid situations)?

Body:
Old question but it seems others have run into this.

This isn't really an MSAL issue since the token itself isn't the problem here. The exception stems from calling https://graph.microsoft.com/v1.0/me/messages when the user doesn't have an accessible mailbox.

You generally can determine which resources have been assigned to a user by looking at that user's provisionedPlans collection:

 https://graph.microsoft.com/v1.0/me?$select=provisionedPlans

This will return a collection resources that have been provisioned for the user. For example, this user does not have Exchange provisioned:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(provisionedPlans)/$entity",
    "provisionedPlans": [
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        }
    ]
}

Compare this with this user that does have Excange provisioned:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(provisionedPlans)/$entity",
    "provisionedPlans": [
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "MicrosoftOffice"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "exchange"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "MicrosoftCommunicationsOnline"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        },
        {
            "capabilityStatus": "Enabled",
            "provisioningStatus": "Success",
            "service": "SharePoint"
        }
    ]
}

A similar property that may also be useful is assignedPlans. This returns the resources that have been assigned to the user and is useful for determining if provisioning simply hasn't occurred yet or for resources that are not formally "provisioned" such as Microsoft Teams.

That said, you should always defensively code for the possibility that a user doesn't have or lacks permission for a resource you're requesting. There are several scenarios where a resource may be inaccessible due to an outage or user permissions and the only sure fire way to handle these scenarios is to backstop with solid exception handling.


问:
How do GNU assembler x86 instruction suffixes like ".s" in "mov.s" work?
GNU assembler appears to have some means of controlling the alternative forms of the opcode being emitted for some instructions. E.g.

```<code>.intel_syntax noprefix
mov   eax, ecx
mov.s eax, ecx
</code>```

Processing the above code with as test.s -o test.o && objdump -d test.o -M intel gives the following disassembly:

```<code>0:   89 c8                   mov    eax,ecx
2:   8b c1                   mov    eax,ecx
</code>```

We can see that .s suffix appears to switch 89 opcode to the 8b version (and appropriately change the ModRM byte).

How does this syntax work in GAS?  I can't find any relevant documentation.

答:
As of Binutils 2.29 the instruction suffixes are now deprecated in favor of pseudo-prefixes. You can find the older suffixes documented in the GNU Assembler (pre-2.29) info pages. Earlier info as pages say this:

9.15.4.1 Instruction Naming

[snip]

Different encoding options can be specified via optional mnemonic suffix. .s suffix swaps 2 register operands in encoding when moving from one register to another. .d8 or .d32 suffix prefers 8bit or 32bit displacement in encoding.

Documenting the new pseudo prefixes, Binutils 2.29 (and later) info as pages were revised to read:

Different encoding options can be specified via pseudo prefixes:

{disp8} – prefer 8-bit displacement.

{disp32} – prefer 32-bit displacement.

{load} – prefer load-form instruction.

{store} – prefer store-form instruction.

{vex2} – prefer 2-byte VEX prefix for VEX instruction.

{vex3} – prefer 3-byte VEX prefix for VEX instruction.

{evex} – encode with EVEX prefix.

ContentLicense: CC BY-SA 4.0

Body:
GNU assembler appears to have some means of controlling the alternative forms of the opcode being emitted for some instructions. E.g.

.intel_syntax noprefix
mov   eax, ecx
mov.s eax, ecx

Processing the above code with as test.s -o test.o && objdump -d test.o -M intel gives the following disassembly:

0:   89 c8                   mov    eax,ecx
2:   8b c1                   mov    eax,ecx

We can see that .s suffix appears to switch 89 opcode to the 8b version (and appropriately change the ModRM byte).

How does this syntax work in GAS?  I can't find any relevant documentation.


问:
Website with 2 separate WordPress blogs
I have a website, which runs an integrated wordpress blog, the wordpress was installed by my hosting company and it was a one click install. I then went into my FTP and took all the files from the original style and edited it to look like my website and still function. this is all well and good.

However, I would like to run another page on a separate wordpress blog (so there is basically two seperate archiving systems in place as one of the pages is a blog, and the other is articles which are produced monthly).

is there anyway to do this with the one click install, for example through the WP admin Control panel?

Thanks for your help in advance.

答:
Yes you can use two blogs by the two methods

Install wordpress on SubDomain like  site.domain.com

Install wordpress on SubDirectories like  domain.com/site

And then you can use both of your site in one another according to your needs and requirements ...

ContentLicense: CC BY-SA 2.5

Title: Website with 2 separate WordPress blogs


问:
how to get the first day of the first month of the current year in RPGLE

dcl-s today date inz(*Sys) is  the current sytem date
 How do i get the first day of the first month of the current year in this format 2017/01/01</p>

答:
Here's a slick trick:

```<code>   dcl-proc BuildDate;
     dcl-pi *n date;
       pyear     int(5) const;
       pmonth    int(5) const;
       pday      int(5) const;
     end-pi;

     dcl-ds *n;
       dateds   date(*iso) inz(d'0001-01-01');
       year     zoned(4:0) pos(1);
       month    zoned(2:0) pos(6);
       day      zoned(2:0) pos(9);
     end-ds;

     year = pyear;
     month = pmonth;
     day = pday;

     test(e) dateds;
     if %error;
       reset dateds;
     endif;

     return dateds;
   end-proc;
</code>```

Now all you need to do to construct a valid date given Day Month and Year is:

```<code>FirstDOY = BuildDate(%subdt(%date(): *Y): 1: 1);
</code>```

Body:
Here's a slick trick:

   dcl-proc BuildDate;
     dcl-pi *n date;
       pyear     int(5) const;
       pmonth    int(5) const;
       pday      int(5) const;
     end-pi;

     dcl-ds *n;
       dateds   date(*iso) inz(d'0001-01-01');
       year     zoned(4:0) pos(1);
       month    zoned(2:0) pos(6);
       day      zoned(2:0) pos(9);
     end-ds;

     year = pyear;
     month = pmonth;
     day = pday;

     test(e) dateds;
     if %error;
       reset dateds;
     endif;

     return dateds;
   end-proc;

Now all you need to do to construct a valid date given Day Month and Year is:

FirstDOY = BuildDate(%subdt(%date(): *Y): 1: 1);


问:
Get foreign key without requesting the whole object
I have a model Foo which have a ForeignKey to the User model.

Later, I need to grab all the User's id and put then on a list

```<code>foos = Foo.objects.filter(...)

l = [ f.user.id for f in foos ]
</code>```

But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo row.

How can I get all the ids without querying each user or using a select_related?

Thanks

答:
Nevermind... I´m not sure why this didn´t work before when I tried, but this is how to do:</p>

```<code>l = [ f.user_id for f in foos ]
</code>```

OwnerDisplayName: Tiago

Body:
I have a model Foo which have a ForeignKey to the User model.

Later, I need to grab all the User's id and put then on a list

foos = Foo.objects.filter(...)

l = [ f.user.id for f in foos ]

But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo row.

How can I get all the ids without querying each user or using a select_related?

Thanks

LastEditorDisplayName: Fabian Steeg

Body:
Nevermind... I´m not sure why this didn´t work before when I tried, but this is how to do:

l = [ f.user_id for f in foos ]


问:
How to add Supplement type type into the ggplot
I was wondering how I can add the information of each line into the Plot, For example, dashed line in red color refers to 90%CI for male
           twodash line in green color refers to 90%CI for female
           longdash line in black color refers to 90%CI for all population</p>

```<code>ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs),
      fill = factor(vs)), shape=21, size = 4) +
      scale_fill_manual(values=c("blue", "pink")) +
      scale_colour_manual(values=c("black", "black"))+
      geom_hline(yintercept=200, linetype="dashed", color = "darkred")+
      geom_hline(yintercept=250, linetype="dashed", color = "darkred")+
      geom_hline(yintercept=210, linetype="twodash", color = "green")+
      geom_hline(yintercept=215, linetype="twodash", color = "green")+
      geom_hline(yintercept=279, linetype="longdash", color = "black")+
      geom_hline(yintercept=280, linetype="longdash", color = "black")
</code>```

答:
The advice from Axeman is apt.  Build a data.frame with the wanted yintercepts and a factor for the grouping of the lines.  A single call to geom_hline will the needed aes will generate the plot and a meaningful legend.

```<code>library(ggplot2)

lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                 grp  = factor(c(1, 1, 2, 2, 3, 3),
                               levels = 1:3,
                               labels = c("Group 1", "Group 2", "Group 3")))

ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs),
      fill = factor(vs)), shape=21, size = 4) +
      scale_fill_manual(values=c("blue", "pink")) +
      scale_colour_manual(values=c("black", "black"))+
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint, linetype = grp))
</code>```

Body:
I was wondering how I can add the information of each line into the Plot, For example, dashed line in red color refers to 90%CI for male
           twodash line in green color refers to 90%CI for female
           longdash line in black color refers to 90%CI for all population

ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs),
      fill = factor(vs)), shape=21, size = 4) +
      scale_fill_manual(values=c("blue", "pink")) +
      scale_colour_manual(values=c("black", "black"))+
      geom_hline(yintercept=200, linetype="dashed", color = "darkred")+
      geom_hline(yintercept=250, linetype="dashed", color = "darkred")+
      geom_hline(yintercept=210, linetype="twodash", color = "green")+
      geom_hline(yintercept=215, linetype="twodash", color = "green")+
      geom_hline(yintercept=279, linetype="longdash", color = "black")+
      geom_hline(yintercept=280, linetype="longdash", color = "black")

Body:
The advice from Axeman is apt.  Build a data.frame with the wanted yintercepts and a factor for the grouping of the lines.  A single call to geom_hline will the needed aes will generate the plot and a meaningful legend.

library(ggplot2)

lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                 grp  = factor(c(1, 1, 2, 2, 3, 3),
                               levels = 1:3,
                               labels = c("Group 1", "Group 2", "Group 3")))

ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs),
      fill = factor(vs)), shape=21, size = 4) +
      scale_fill_manual(values=c("blue", "pink")) +
      scale_colour_manual(values=c("black", "black"))+
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint, linetype = grp))


问:
Count the number of elements in a comma separated string in Oracle
Say I have a table where Col2 is varchar

```<code>Col1 Col2
1    001,002
2    003,004,005
</code>```

I need to count the number of elements in Col2,and return it, if I do:

```<code>select --do something here with column-- from table
</code>```

it'll give me:

```<code>2
3
</code>```

答:
Linger's answer is incorrect in the special case that Col2 is empty. Instead of yielding a count of 0 you'd get an incorrect count of 1. You can account for this special case with a CASE statement as follows:

```<code>SELECT CASE WHEN Col2='' THEN 0 ELSE LENGTH(Col2)-LENGTH(REPLACE(Col2,",",""))+1 END AS MyCol2Count
FROM MyTable
</code>```

Edit: As William has pointed out the empty string WHEN test may be inaccurate if your table is setup to allow NULLs for the column in question. In such a case you'd need to replace the Col2='' test with Col2 IS NULL (at least in SQL Server).

Note: Apologies, I would have put this as a comment on Linger's answer but I'm not allowed to comment yet.

Body:
Say I have a table where Col2 is varchar

Col1 Col2
1    001,002
2    003,004,005

I need to count the number of elements in Col2,and return it, if I do:

select --do something here with column-- from table

it'll give me:

2
3

Body:
Linger's answer is incorrect in the special case that Col2 is empty. Instead of yielding a count of 0 you'd get an incorrect count of 1. You can account for this special case with a CASE statement as follows:

SELECT CASE WHEN Col2='' THEN 0 ELSE LENGTH(Col2)-LENGTH(REPLACE(Col2,",",""))+1 END AS MyCol2Count
FROM MyTable

Edit: As William has pointed out the empty string WHEN test may be inaccurate if your table is setup to allow NULLs for the column in question. In such a case you'd need to replace the Col2='' test with Col2 IS NULL (at least in SQL Server).

Note: Apologies, I would have put this as a comment on Linger's answer but I'm not allowed to comment yet.


问:
Dividing bootstrap column under col-1
I would like to be able to divide a bootstrap gid even more. Without to much hassle or workarounds. What is the best way of creating column 1/24 of a grid.

Fiddle to understand better what I mean: https://jsfiddle.net/Lmm1ra7d/

```<code><div class='row'>
    <div class="col-xs-8">8/12</div>
    <div class="col-xs-4">4/12</div>
</div>

<br/>
Now I need to transform this to  a 0.5/12 => 1/24 What would be the best approach without a hacky fix. Also not to break the responsiveness.
This is the smallest column bootstrap can make 8.3333%
<br/>
<br/>

<div class='row'>
    <div class="col-xs-1">1/12</div>
    <div class="col-xs-11">11/12</div>
</div>

<br/>
What I really want would be 4%
<br/>
<br/>

<div class='row'>
    <div style="width:3%; display: inline-block;">1/24</div><div style="width:96%;display: inline-block;">23/24</div>
</div>
</code>```

答:
You can just nest another column setup in the col-*-1. If the padding on the nested row/columns is unwanted you can just add a class to override the padding.

```<code><div class="row">
    <div class="col-xs-1">
        <div class="row">
            <div class="col-xs-6"></div>
            <div class="col-xs-6"></div>
        </div>
    </div>
</div>
</code>```

Title: Dividing bootstrap column under col-1

Body:
I would like to be able to divide a bootstrap gid even more. Without to much hassle or workarounds. What is the best way of creating column 1/24 of a grid.

Fiddle to understand better what I mean: https://jsfiddle.net/Lmm1ra7d/

8/12

4/12

Now I need to transform this to  a 0.5/12 => 1/24 What would be the best approach without a hacky fix. Also not to break the responsiveness.
This is the smallest column bootstrap can make 8.3333%

1/12

11/12

What I really want would be 4%

1/24

23/24

Body:
You can just nest another column setup in the col-*-1. If the padding on the nested row/columns is unwanted you can just add a class to override the padding.

<div class="row">
    <div class="col-xs-1">
        <div class="row">
            <div class="col-xs-6"></div>
            <div class="col-xs-6"></div>
        </div>
    </div>
</div>


问:
UNION 2 sql queries - wp_posts vs wp_terms - PHP, WORDPRESS
I have a page where I'm displaying all taxonomy categories and all posts/pages. There I need to have ajax pagination so that my page won't load ages (or even not load). So I've built the pagination via sql query and now need to get both terms and posts with sql query, then union them so that my pagination will work properly and count including them all.

Here is my code:

```<code>$sql1 = "SELECT * FROM wp_term_taxonomy LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id =
wp_terms.term_id) WHERE wp_term_taxonomy.taxonomy = 'product-category'";

$sql2 = "SELECT * FROM wp_posts WHERE (post_type = 'products' OR post_type = 'page')
AND (post_status = 'publish' OR post_status = 'suspended') AND ID NOT IN
(231, 236, 1070, 1245) order by post_title ASC";

$sql = $sql1." UNION ".$sql2;

$query =  $sql . " limit " . $start . "," . $resultPerPage->perpage;
$list = $db_handle->runBackendQuery($query);
</code>```

Above returns me following errors:

```<code>Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in .../dbcontroller.php on line 29

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
.../dbcontroller.php on line 38
</code>```

I think I can join such 2 different things. Is there anything I'm missing?

答:
The error could happen because you have some error in your query for avoid this

You should select the same number of column and with corresponding data type so try avoiding select all  (*) and use explicit select column you should use a sintax  like eg:

```<code>$sql1 = "SELECT col_a1, col_a2, col_a3 FROM wp_term_taxonomy LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id =
wp_terms.term_id) WHERE wp_term_taxonomy.taxonomy = 'product-category'";

$sql2 = "SELECT col_b1, col_b2, col_b3 FROM wp_posts WHERE (post_type = 'products' OR post_type = 'page')
AND (post_status = 'publish' OR post_status = 'suspended') AND ID NOT IN
(231, 236, 1070, 1245) order by post_title ASC";

$sql = $sql1." UNION ".$sql2;

$query =  $sql . " limit " . $start . "," . $resultPerPage->perpage;
$list = $db_handle->runBackendQuery($query);
</code>```

Body:
I have a page where I'm displaying all taxonomy categories and all posts/pages. There I need to have ajax pagination so that my page won't load ages (or even not load). So I've built the pagination via sql query and now need to get both terms and posts with sql query, then union them so that my pagination will work properly and count including them all.

Here is my code:

$sql1 = "SELECT * FROM wp_term_taxonomy LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id =
wp_terms.term_id) WHERE wp_term_taxonomy.taxonomy = 'product-category'";

$sql2 = "SELECT * FROM wp_posts WHERE (post_type = 'products' OR post_type = 'page')
AND (post_status = 'publish' OR post_status = 'suspended') AND ID NOT IN
(231, 236, 1070, 1245) order by post_title ASC";

$sql = $sql1." UNION ".$sql2;

$query =  $sql . " limit " . $start . "," . $resultPerPage->perpage;
$list = $db_handle->runBackendQuery($query);

Above returns me following errors:

Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in .../dbcontroller.php on line 29

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
.../dbcontroller.php on line 38

I think I can join such 2 different things. Is there anything I'm missing?

Body:
The error could happen because you have some error in your query for avoid this

You should select the same number of column and with corresponding data type so try avoiding select all  (*) and use explicit select column you should use a sintax  like eg:

$sql1 = "SELECT col_a1, col_a2, col_a3 FROM wp_term_taxonomy LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id =
wp_terms.term_id) WHERE wp_term_taxonomy.taxonomy = 'product-category'";

$sql2 = "SELECT col_b1, col_b2, col_b3 FROM wp_posts WHERE (post_type = 'products' OR post_type = 'page')
AND (post_status = 'publish' OR post_status = 'suspended') AND ID NOT IN
(231, 236, 1070, 1245) order by post_title ASC";

$sql = $sql1." UNION ".$sql2;

$query =  $sql . " limit " . $start . "," . $resultPerPage->perpage;
$list = $db_handle->runBackendQuery($query);


问:
Can't call a function from a separate file
I'm trying to run a function that's inside an included file. The file get's included properly but I still get a undefined function error. Tried everything and nothing seems to work. Here's a simplified version of my code...

File functions.php

```<code><?php function myFunction($foo){ echo $foo; } ?>
</code>```

File index.php

```<code><?php include('functions.php'); $string = "Hello, world!"; myFunction($string); ?>
</code>```

I'm getting the following error:

Fatal error: Uncaught Error: Call to undefined function myFunction()
  in /functions.php on line 1

I tried with include, include_once, request, request_once and even creating a class with a public function but nothing works. The file is being properly included because if I added an echo at the beginning of functions.php and it displays properly on index.php. Also, there is no error in my function because if I run it from the functions.php file it works like a charm. The problem is that index.php isn't recognizing myFunction() as a defined function. Could it be a problem with the php.ini file? The include works so that can't be it.

How can I call myFunction($foo) from index.php?

Thanks in advance!

答:
It worked, please make sure that you put functions.php and index.php in the same location. Then do the following...

functions.php

```<code><?php

 function showmsg($msg=''){
    echo 'Hi' . ' ' . $msg;
}

?>
</code>```

index.php

```<code><?php

include 'functions.php';

$str = 'Nilesh';
showmsg($str);

?>
</code>```

Body:
I'm trying to run a function that's inside an included file. The file get's included properly but I still get a undefined function error. Tried everything and nothing seems to work. Here's a simplified version of my code...

File functions.php

<?php function myFunction($foo){ echo $foo; } ?>

File index.php

<?php include('functions.php'); $string = "Hello, world!"; myFunction($string); ?>

I'm getting the following error:

Fatal error: Uncaught Error: Call to undefined function myFunction()
  in /functions.php on line 1

I tried with include, include_once, request, request_once and even creating a class with a public function but nothing works. The file is being properly included because if I added an echo at the beginning of functions.php and it displays properly on index.php. Also, there is no error in my function because if I run it from the functions.php file it works like a charm. The problem is that index.php isn't recognizing myFunction() as a defined function. Could it be a problem with the php.ini file? The include works so that can't be it.

How can I call myFunction($foo) from index.php?

Thanks in advance!

Body:
It worked, please make sure that you put functions.php and index.php in the same location. Then do the following...

functions.php

<?php

 function showmsg($msg=''){
    echo 'Hi' . ' ' . $msg;
}

?>

index.php

<?php

include 'functions.php';

$str = 'Nilesh';
showmsg($str);

?>


问:
How to turn a dictionary into list in Python
I'm using Flask to grab the input from an HTML form, which returns it as a dictionary object, for example:

```<code>form = {'Name': 'Eddie', 'Comment': 'Nice location', 'Days Stayed': '7'}
</code>```

Now, I can use dict.items() to get the dictionary into a format which I can display in an HTML table (list of tuples):

```<code>formList = [('Name', Eddie), ('Comment', 'Nice Location'), ('Days Stayed', '7')]
</code>```

This stores nicely into a .csv in the following way:

```<code>Name,['Eddie']
Comment,['Nice Location']
Days Stayed,['7']
</code>```

However, I'd like my .csv (and therefore HTML Table) to store like this:

```<code>Eddie, Nice Location, 7
Dave, Good Food, 14
Steve, Room was cosy, 10
</code>```

So I can have my field names at the top and create a nice looking table. How can I achieve this?

答:
Assuming you're already working with Python's csv module, here's a longform way of doing it, if you wanted headers.

This example uses the DictWriter which is specifically designed to work with dictionaries.

```<code>import csv

form_data = [
    {'Name': 'Eddie', 'Comment': 'Nice location', 'Days Stayed': '7'},
    {'Name': 'Dave', 'Comment': 'Good Food', 'Days Stayed': '14'},
    {'Name': 'Steve', 'Comment': 'Room was cosy', 'Days Stayed': '10'}
]

with open('output.csv', 'w') as csvfile:
    # this defines the fields you want from dictionaries
    # you pass to the writer, and the order in which they should
    # be emitted in the resulting CSV
    fields = ['Name', 'Comment', 'Days Stayed']
    dw = csv.DictWriter(csvfile, fieldnames)

    # omit this if you don't want a header written
    dw.writeheader()
    for row in form_data:
        dw.writerow(row)
</code>```

Resulting output.csv looks like this:

```<code>Name,Comment,Days Stayed
Eddie,Nice location,7
Dave,Good Food,14
Steve,Room was cosy,10
</code>```

You can similarly deserialize using the DictReader class provided by csv.

```<code>import csv

rows = None
with open('output.csv') as csvfile:
    fields = ['Name', 'Comment', 'Days Stayed']
    reader = csv.DictReader(csvfile)
    rows = [row for row in reader]
</code>```

rows will look like this:

```<code>[{'Comment': 'Nice location', 'Days Stayed': '7', 'Name': 'Eddie'},
 {'Comment': 'Good Food', 'Days Stayed': '14', 'Name': 'Dave'},
 {'Comment': 'Room was cosy', 'Days Stayed': '10', 'Name': 'Steve'}]
</code>```

Body:
I'm using Flask to grab the input from an HTML form, which returns it as a dictionary object, for example:

form = {'Name': 'Eddie', 'Comment': 'Nice location', 'Days Stayed': '7'}

Now, I can use dict.items() to get the dictionary into a format which I can display in an HTML table (list of tuples):

formList = [('Name', Eddie), ('Comment', 'Nice Location'), ('Days Stayed', '7')]

This stores nicely into a .csv in the following way:

Name,['Eddie']
Comment,['Nice Location']
Days Stayed,['7']

However, I'd like my .csv (and therefore HTML Table) to store like this:

Eddie, Nice Location, 7
Dave, Good Food, 14
Steve, Room was cosy, 10

So I can have my field names at the top and create a nice looking table. How can I achieve this?

Body:
Assuming you're already working with Python's csv module, here's a longform way of doing it, if you wanted headers.

This example uses the DictWriter which is specifically designed to work with dictionaries.

import csv

form_data = [
    {'Name': 'Eddie', 'Comment': 'Nice location', 'Days Stayed': '7'},
    {'Name': 'Dave', 'Comment': 'Good Food', 'Days Stayed': '14'},
    {'Name': 'Steve', 'Comment': 'Room was cosy', 'Days Stayed': '10'}
]

with open('output.csv', 'w') as csvfile:
    # this defines the fields you want from dictionaries
    # you pass to the writer, and the order in which they should
    # be emitted in the resulting CSV
    fields = ['Name', 'Comment', 'Days Stayed']
    dw = csv.DictWriter(csvfile, fieldnames)

    # omit this if you don't want a header written
    dw.writeheader()
    for row in form_data:
        dw.writerow(row)

Resulting output.csv looks like this:

Name,Comment,Days Stayed
Eddie,Nice location,7
Dave,Good Food,14
Steve,Room was cosy,10

You can similarly deserialize using the DictReader class provided by csv.

import csv

rows = None
with open('output.csv') as csvfile:
    fields = ['Name', 'Comment', 'Days Stayed']
    reader = csv.DictReader(csvfile)
    rows = [row for row in reader]

rows will look like this:

[{'Comment': 'Nice location', 'Days Stayed': '7', 'Name': 'Eddie'},
 {'Comment': 'Good Food', 'Days Stayed': '14', 'Name': 'Dave'},
 {'Comment': 'Room was cosy', 'Days Stayed': '10', 'Name': 'Steve'}]


问:
DBSCAN for clustering data by location and density
I'm using the method dbscan::dbscan in order to cluster my data by location and density.

My data looks like this:

```<code>str(data)
'data.frame': 4872 obs. of 3 variables:
 $ price    : num ...
 $ lat      : num ...
 $ lng      : num ...
</code>```

Now I'm using following code:

```<code>EPS = 7
cluster.dbscan <- dbscan(data, eps = EPS, minPts = 30, borderPoints = T,
search = "kdtree")
plot(lat ~ lng, data = data, col = cluster.dbscan$cluster + 1L, pch = 20)
</code>```

but the result isn't satisfying at all, the point's aren't really clustered.

I would like to have the clusters nicely defined, something like this:

I also tried to use use a decision tree classifier tree:tree which works better, but I can't tell if it is really a good classification.

File:

http://www.file-upload.net/download-11246655/file.csv.html

Question:

is it possible to achieve what I want?

am I using the right method?

should I play more with the parameters? if yes, with which?

答:
You can use something called as Hullplot

In your cases

hullplot(select(data, lng, lat), cluster.dbscan$cluster)

Body:
I'm using the method dbscan::dbscan in order to cluster my data by location and density.

My data looks like this:

str(data)
'data.frame': 4872 obs. of 3 variables:
 $ price    : num ...
 $ lat      : num ...
 $ lng      : num ...

Now I'm using following code:

EPS = 7
cluster.dbscan <- dbscan(data, eps = EPS, minPts = 30, borderPoints = T,
search = "kdtree")
plot(lat ~ lng, data = data, col = cluster.dbscan$cluster + 1L, pch = 20)

but the result isn't satisfying at all, the point's aren't really clustered.

I would like to have the clusters nicely defined, something like this:

I also tried to use use a decision tree classifier tree:tree which works better, but I can't tell if it is really a good classification.

File:

http://www.file-upload.net/download-11246655/file.csv.html

Question:

is it possible to achieve what I want?

am I using the right method?

should I play more with the parameters? if yes, with which?


问:
How to search through multiple properties in a sorted list with Vue
I have a data set with people's first names and last names and I want users to be able to search through these with Vue 2.

So far, I managed to sort the list first by first name, then by last name using Lodash and I also managed to categorize them by type. Now I want to filter/search (I don't know the correct word) the array and only show people of whom (part of) the first or last name or both match the input field's content.

A vanilla JS solution would be as much appreciated as a Lodash solution!

```<code>props: {
  people: {
    type: Array,
    required: true
  }
},

data: function(){
  return {
    filter: '',
    people:[{
      "FirstName" : "Stefan",
      "LastName" : "Braun",
      "Type" : "EN",
    },
    {
      "FirstName" : "Jenny",
      "LastName" : "Smith",
      "Type" : "VO",
    },
    {
      "FirstName" : "Susan",
      "LastName" : "Jones",
      "Type" : "EN",
    }]
  }
}

methods: {

  matchingType: function (people, type) {
    people = this.alphabeticallyOrdered(this.searchFiltered(people))

    return people.filter(function (person) {
      return person.Type == type
    })
  },

  alphabeticallyOrdered: function(arr){
    return _.orderBy(arr, ['FirstName', 'LastName'])
  },

  searchFiltered: function(arr){
    filter = this.filter
    return _.some(arr, _.unary(_.partialRight(_.includes, this.filter)));
  }
},

template: `
  <div>
    <input type="text" model="filter"></input>
    <div v-for="type in types" class="type" :class="type.short">
      <h2 class="type-name">{{type.long}}</h2>
      <div class="people">
        <div v-for="person in matchingType(people, type.short)" class="person">
          <div class="personal-details">
            <p class="h2">{{person.FirstName}}</p>
            <p class="h4">{{person.LastName}}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
`
</code>```

答:
Typically you would handle this using a computed property.

Here is an example. I'm eliminating a lot of the extra code in your example as there are parts I cannot replicate without knowing exactly what you are doing (you don't post the fill code for the component), but in essence, you would write a computed property like the following and iterate over that in your template.

console.clear()

new Vue({
 el: "#app",
  data:{
     people:[{
      "FirstName" : "Stefan",
      "LastName" : "Braun",
      "Type" : "EN",
    },
    {
      "FirstName" : "Jenny",
      "LastName" : "Smith",
      "Type" : "VO",
    },
    {
      "FirstName" : "Susan",
      "LastName" : "Jones",
      "Type" : "EN",
    }],
    filterText: null
  },
  computed:{
    filteredPeople(){
      // If there is no filter text, just return everyone
      if (!this.filterText) return this.people

      // Convert the search text to lower case
      let searchText = this.filterText.toLowerCase()

      // Use the standard javascript filter method of arrays
      // to return only people whose first name or last name
      // includes the search text
      return this.people.filter(p => {
        // if IE support is required and not pre-compiling,
        // use indexOf instead of includes
        return p.FirstName.toLowerCase().includes(searchText) ||
        p.LastName.toLowerCase().includes(searchText)
      })
    }

  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js"></script>
<div id="app">
  <input type="text" v-model="filterText">
  <ul>
    <li v-for="person in filteredPeople">
      {{person.FirstName}}  {{person.LastName}}
    </li>
  </ul>
</div></code>```

Body:
I have a data set with people's first names and last names and I want users to be able to search through these with Vue 2.

So far, I managed to sort the list first by first name, then by last name using Lodash and I also managed to categorize them by type. Now I want to filter/search (I don't know the correct word) the array and only show people of whom (part of) the first or last name or both match the input field's content.

A vanilla JS solution would be as much appreciated as a Lodash solution!

props: {
  people: {
    type: Array,
    required: true
  }
},

data: function(){
  return {
    filter: '',
    people:[{
      "FirstName" : "Stefan",
      "LastName" : "Braun",
      "Type" : "EN",
    },
    {
      "FirstName" : "Jenny",
      "LastName" : "Smith",
      "Type" : "VO",
    },
    {
      "FirstName" : "Susan",
      "LastName" : "Jones",
      "Type" : "EN",
    }]
  }
}

methods: {

  matchingType: function (people, type) {
    people = this.alphabeticallyOrdered(this.searchFiltered(people))

    return people.filter(function (person) {
      return person.Type == type
    })
  },

  alphabeticallyOrdered: function(arr){
    return _.orderBy(arr, ['FirstName', 'LastName'])
  },

  searchFiltered: function(arr){
    filter = this.filter
    return _.some(arr, _.unary(_.partialRight(_.includes, this.filter)));
  }
},

template: `

    <input type="text" model="filter"></input>

{{type.long}}

{{person.FirstName}}

{{person.LastName}}

`

Body:
Typically you would handle this using a computed property.

Here is an example. I'm eliminating a lot of the extra code in your example as there are parts I cannot replicate without knowing exactly what you are doing (you don't post the fill code for the component), but in essence, you would write a computed property like the following and iterate over that in your template.

console.clear()

new Vue({
 el: "#app",
  data:{
     people:[{
      "FirstName" : "Stefan",
      "LastName" : "Braun",
      "Type" : "EN",
    },
    {
      "FirstName" : "Jenny",
      "LastName" : "Smith",
      "Type" : "VO",
    },
    {
      "FirstName" : "Susan",
      "LastName" : "Jones",
      "Type" : "EN",
    }],
    filterText: null
  },
  computed:{
    filteredPeople(){
      // If there is no filter text, just return everyone
      if (!this.filterText) return this.people

      // Convert the search text to lower case
      let searchText = this.filterText.toLowerCase()

      // Use the standard javascript filter method of arrays
      // to return only people whose first name or last name
      // includes the search text
      return this.people.filter(p => {
        // if IE support is required and not pre-compiling,
        // use indexOf instead of includes
        return p.FirstName.toLowerCase().includes(searchText) ||
        p.LastName.toLowerCase().includes(searchText)
      })
    }

  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js"></script>
<div id="app">
  <input type="text" v-model="filterText">
  <ul>
    <li v-for="person in filteredPeople">
      {{person.FirstName}}  {{person.LastName}}
    </li>
  </ul>
</div>


答:
The timestamps are stored as strings. When you try to divide it, the database tries to convert it to a number, which results in 2017. So all timestamps end up being the same.

Dividing cannot determine the distance; the values 9999 and 10000 will end up different although they are right near each other. (And an integer division results in an integer result, so the ROUND() has no effect.)

To compute the distance, convert the timestamp into a number of seconds first, and then use abs():

```<code>SELECT ...
FROM master_animal m
JOIN animal_inventory i ON m.cownumber = i.cownumber
                       AND abs(strftime('%s', m.ts) - strftime('%s', i.ts)) <= 50
JOIN experiment e       ON m.cownumber = e.cownumber
                       AND abs(strftime('%s', m.ts) - strftime('%s', e.ts)) <= 50;
</code>```

Title: Creating a view that joins multiple tables on an ID and a timestamp that needs to be rounded

Body:
I have a web application that sends data to my sqlite database into different tables depending on the information. I would like to make a view that merges multiple tables together based on cownumber and TS[timestamp] (There are no updates to my table, so a change to the same cownumber send the full record as a new entry with a new timestamp). The ajax calls are made table by table so the TS do not exactly sync up generally they can be  5-20 seconds off depending on the connection

Here is a sample of the three tables

+----master_animal-----+
+----------------------------------------------------+
| cownumber | height   | weight | ts                 |
+-----------+----------+--------+--------------------+
| 1         | 150      | ...    | 2017-12-01 12:28:00|
| 2         | 170      | ...    | 2017-12-03 17:16:00|
| 3         | 60       | ...    | 2017-12-03 08:09:00|
| 4         | 109      | ...    | 2017-12-04 23:23:00|

+----animal_inventory-----+
+-------------------------------------------------------------+
| cownumber | brandlocation| dateacquired| ts                 |
+-----------+--------------+-------------+--------------------+
| 1         | ...          | ...         | 2017-12-01 12:28:50|
| 2         | ...          | ...         | 2017-12-03 17:16:30|
| 3         | ...          | ...         | 2017-12-03 08:09:12|
| 4         |  ...         | ...         | 2017-12-04 23:23:23|

+----experiment-----+
+-------------------------------------------------------------+
| cownumber | ageatwean    | birthweight | ts                 |
+-----------+--------------+-------------+--------------------+
| 1         | ...          | ...         | 2017-12-01 12:28:20|
| 2         | ...          | ...         | 2017-12-03 17:16:41|
| 3         | ...          | ...         | 2017-12-03 08:09:24|
| 4         |  ...         | ...         | 2017-12-04 23:23:11|

The View I wrote

CREATE VIEW testing
AS SELECT a.height,a.weight,a.cownumber,
b.brandlocation,b.dateacquired,
c.ageatwean,c.birthweight
FROM master_animal a, animal_inventory b, experiment c
WHERE a.cownumber=b.cownumber
AND ROUND(a.ts/10000) = ROUND(b.ts/10000)
AND a.cownumber=c.cownumber
AND ROUND(a.ts/10000) = ROUND(c.ts/10000);

The query I wrote

Select * from testing where cownumber = 1;

What I was hoping to get back was

+----testing-----+
+----------------------------------------------------+
| cownumber | height | weight | brandlocation| dateacquired | ageatwean |birthweight |
+-----------+--------+--------+--------------+--------------+-----------+------------+
| 941        | 0     | ...    |       ...    |     ...      |     ...   |   ..       |

Where there will be one row for cownumber 941 as long as all the correlated records were within a few seconds of each other. I am not exactly sure if I need to divide by 10000 or smaller. The same record should be no more than 50 seconds apart from each other. Anything more than 50 seconds apart should be considered a new record.

When I test this where there is only one record for that cownumber it works fine. But lets say I change some information from each table. I provide a new height, a new brandlocation.

Instead of getting two rows. The first row being the initial data entry and the second row showing the same cownumber with the changed values, I get back 8 rows with partial changes.

height|weight|cownumber|brandlocation|dateacquired|ageatwean|birthweight|
0.0|0.0|941|0|0|0.0|0
0.0|0.0|941|0|0|0.0|0
0.0|0.0|941|Left Hip|0|0.0|0
0.0|0.0|941|Left Hip|0|0.0|0
50.0|0.0|941|0|0|0.0|0
50.0|0.0|941|0|0|0.0|0
50.0|0.0|941|Left Hip|0|0.0|0
50.0|0.0|941|Left Hip|0|0.0|0

I assume the issue is in my where clause but I am not sure exactly how to fix it

Body:
The timestamps are stored as strings. When you try to divide it, the database tries to convert it to a number, which results in 2017. So all timestamps end up being the same.

Dividing cannot determine the distance; the values 9999 and 10000 will end up different although they are right near each other. (And an integer division results in an integer result, so the ROUND() has no effect.)

To compute the distance, convert the timestamp into a number of seconds first, and then use abs():

SELECT ...
FROM master_animal m
JOIN animal_inventory i ON m.cownumber = i.cownumber
                       AND abs(strftime('%s', m.ts) - strftime('%s', i.ts)) <= 50
JOIN experiment e       ON m.cownumber = e.cownumber
                       AND abs(strftime('%s', m.ts) - strftime('%s', e.ts)) <= 50;


问:
Php artisan serve require fatal error after upgrading php7
After upgrading php from 7.0.14 to 7.0.26 php artisan serve throws this error

Warning: Unknown: failed to open stream: No such file or directory in
  Unknown on line 0
      Fatal error: Unknown: Failed opening required '/Applications/XAMPP/xamppfiles/htdocs/school-dashboard/public/server.php'
  (include_path='.:') in Unknown on line 0

答:
Ok, after hours of pulling my hair out I finally found out what the issue was.

In laravel 4 php artisan serve does this under the hood

```<code><?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

class ServeCommand extends Command {

   public function fire()
   {
       $this->checkPhpVersion();

       chdir($this->laravel['path.base']);

       $host = $this->input->getOption('host');

       $port = $this->input->getOption('port');

       $public = $this->laravel['path.public'];

       $this->info("Laravel development server started on http://{$host}:{$port}");

       passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$public}\" server.php");
    }
}
</code>```

That is essentially this in plain php:
php -S 127.0.0.1:8000 -t public serve.php - see the docs for php built in server for more info.

And this worked well and dandy before php 7.0.26, where the last parameter for the php -S built in server was changed to a flag as well, so you have to call it like this php -S 127.0.0.1:8000 -t public -f serve.php.

If you want to serve it with php artisan serve you will have to override  the ServeCommand and change the last line of the fire() method to this:

passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$public}\" -f server.php");

Or you can change it directly in the ServeCommand, but if you do a composer update or install you will have to do it again.

Body:
Ok, after hours of pulling my hair out I finally found out what the issue was.

In laravel 4 php artisan serve does this under the hood

<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

class ServeCommand extends Command {

   public function fire()
   {
       $this->checkPhpVersion();

       chdir($this->laravel['path.base']);

       $host = $this->input->getOption('host');

       $port = $this->input->getOption('port');

       $public = $this->laravel['path.public'];

       $this->info("Laravel development server started on http://{$host}:{$port}");

       passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$public}\" server.php");
    }
}

That is essentially this in plain php:
php -S 127.0.0.1:8000 -t public serve.php - see the docs for php built in server for more info.

And this worked well and dandy before php 7.0.26, where the last parameter for the php -S built in server was changed to a flag as well, so you have to call it like this php -S 127.0.0.1:8000 -t public -f serve.php.

If you want to serve it with php artisan serve you will have to override  the ServeCommand and change the last line of the fire() method to this:

passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$public}\" -f server.php");

Or you can change it directly in the ServeCommand, but if you do a composer update or install you will have to do it again.


问:
Understanding the limits of Cloud Firestore's security rules

I'm writing the security rules for my Firestore database, and I got to the point where I'm probably writing too many checks and the authorization automatically fails.

For example the rules for a specific path are

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /pending/{userId} {
      match /rate/{vendorId}/events/{eventId}/ratings/{rateId} {
        allow write: if request.auth.uid == userId
            && exists(/databases/$(database)/documents/vendors/$(vendorId)) // The vendor must exist
            && exists(/databases/$(database)/documents/users/$(userId)/subscriptions/$(vendorId)) // The user must be subscribed to the vendor
            && exists(/databases/$(database)/documents/vendors/$(vendorId)/events/$(eventId)) //  The event must exist
            && !exists(/databases/$(database)/documents/vendors/$(vendorId)/events/$(eventId)/ratings/$(userId)) // The user must not have already voted for the event
      }
    }
  }
}
</code>```

These rules apply when writing to /pending/{userId}/rate/{vendorId}/events/{eventId}/ratings/{rateId}

Removing one or a combination of rules makes everything work again.
I read on the documentation about a limit of 10 developer-defined functions here, but exists and get are listed as service-defined and should not be counted. Even if they were, here I'm only using five.

Is there a more efficient way to check the same fields? How do I calculate how much a single line counts into reaching the 10 functions limit?

Thanks

答:
Firebase PM here: Currently, we limit the number of get() and exists() calls in a given rule evaluation to three, which is why you're seeing the behavior fail after adding the fourth. I'll make sure the docs are appropriately updated to include this info.

EDIT (4/2/18): These limits are now documented: https://firebase.google.com/docs/firestore/security/rules-structure#security_rule_limits

EDIT (5/14/18): We increased the limit to 10: https://firebase.google.com/docs/firestore/security/rules-structure#security_rule_limits

get() and exists() calls are more computationally expensive than "normal" rule evaluations, and we want to ensure a tight bound on evaluation time, so as to not slow down incoming requests. I'm pretty sure we can increase the number greater than three, but be aware that we'll look up all of these keys/values and it may take a little longer/cost a little more to evaluate each request.

Note that in this specific case, you're able to do this with three calls:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /pending/{userId} {
      match /rate/{vendorId}/events/{eventId}/ratings/{rateId} {
        // Only allow a document to be created
        allow create:
            // The user must not have already voted for the event
            if request.auth.uid == userId
            && request.auth.uid == rateId
            // The vendor must exist
            && exists(/databases/$(database)/documents/vendors/$(vendorId))
            // The user must be subscribed to the vendor
            && exists(/databases/$(database)/documents/users/$(userId)/subscriptions/$(vendorId))
            //  The event must exist
            && exists(/databases/$(database)/documents/vendors/$(vendorId)/events/$(eventId));
        // Not necessary unless you want to allow updates
        allow update: if ...;
      }
    }
  }
}
</code>```

Body:
I'm writing the security rules for my Firestore database, and I got to the point where I'm probably writing too many checks and the authorization automatically fails.

For example the rules for a specific path are

service cloud.firestore {
  match /databases/{database}/documents {
    match /pending/{userId} {
      match /rate/{vendorId}/events/{eventId}/ratings/{rateId} {
        allow write: if request.auth.uid == userId
            && exists(/databases/$(database)/documents/vendors/$(vendorId)) // The vendor must exist
            && exists(/databases/$(database)/documents/users/$(userId)/subscriptions/$(vendorId)) // The user must be subscribed to the vendor
            && exists(/databases/$(database)/documents/vendors/$(vendorId)/events/$(eventId)) //  The event must exist
            && !exists(/databases/$(database)/documents/vendors/$(vendorId)/events/$(eventId)/ratings/$(userId)) // The user must not have already voted for the event
      }
    }
  }
}

These rules apply when writing to /pending/{userId}/rate/{vendorId}/events/{eventId}/ratings/{rateId}

Removing one or a combination of rules makes everything work again.
I read on the documentation about a limit of 10 developer-defined functions here, but exists and get are listed as service-defined and should not be counted. Even if they were, here I'm only using five.

Is there a more efficient way to check the same fields? How do I calculate how much a single line counts into reaching the 10 functions limit?

Thanks

Body:
Firebase PM here: Currently, we limit the number of get() and exists() calls in a given rule evaluation to three, which is why you're seeing the behavior fail after adding the fourth. I'll make sure the docs are appropriately updated to include this info.

EDIT (4/2/18): These limits are now documented: https://firebase.google.com/docs/firestore/security/rules-structure#security_rule_limits

EDIT (5/14/18): We increased the limit to 10: https://firebase.google.com/docs/firestore/security/rules-structure#security_rule_limits

get() and exists() calls are more computationally expensive than "normal" rule evaluations, and we want to ensure a tight bound on evaluation time, so as to not slow down incoming requests. I'm pretty sure we can increase the number greater than three, but be aware that we'll look up all of these keys/values and it may take a little longer/cost a little more to evaluate each request.

Note that in this specific case, you're able to do this with three calls:

service cloud.firestore {
  match /databases/{database}/documents {
    match /pending/{userId} {
      match /rate/{vendorId}/events/{eventId}/ratings/{rateId} {
        // Only allow a document to be created
        allow create:
            // The user must not have already voted for the event
            if request.auth.uid == userId
            && request.auth.uid == rateId
            // The vendor must exist
            && exists(/databases/$(database)/documents/vendors/$(vendorId))
            // The user must be subscribed to the vendor
            && exists(/databases/$(database)/documents/users/$(userId)/subscriptions/$(vendorId))
            //  The event must exist
            && exists(/databases/$(database)/documents/vendors/$(vendorId)/events/$(eventId));
        // Not necessary unless you want to allow updates
        allow update: if ...;
      }
    }
  }
}


问:
Anagram generation with F# Async
I am trying to think of a way of how to improve speed of my program and one of the parts is anagram generation. Would the async features help in this case or there is another technique of manipulating strings? </p>

```<code>let anagramWords = [|"rolex";"viagra";"win";"free";"cash";"grand";"prize";
                     "nude";"porn";"casino";"lottery";"spins";"sex";"gold"; "buy"; "clearance";
                     "business"; "biz"; "money"; "opportunity"; "earn"; "extra"; "potential"; "sleep"; "discount";
                     "bargain"; "credit"; "affordable"; "loans"; "mortages"; "quote"; "dollars"; "invest"; "investment";
                     "bitcoin"; "silver"; "save"; "unsecured"; "pennies"; "million"; "billion";"bureaus";"stock";
                     "bankruptcy"; "eliminate"; "debt"; "billing"; "iphone"; "selling"; "obligation";"trial";
                     "vacation"; "winner";"membership"; "preview"; "sample"; "priority"; "website"; "gift"; "gifts";
                     "present"; "deal"; "fantastic"; "outstanding"; "values"; "act"; "lifetime"; "urgent"|]

let rec distribute e = function
  | [] -> [[e]]
  | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]

let rec permute = function
  | [] -> [[]]
  | e::xs -> List.collect (distribute e) (permute xs)

let genAnagrams word =
  word
  |>List.ofSeq
  |>permute
  |> List.map (fun x -> String(x |> Array.ofList))
  |> Seq.ofList
  |> Seq.toList
</code>```

答:
One very simple way to make this a bit faster is to make permute use arrays instead of lists and use Array.Parallel.collect instead of List.collect. Even with the inefficiency of taking the head off an array, it becomes about 30% faster for me for a word of 10 characters.

```<code>open System

let rec distribute e = function
  | [] -> [[e]]
  | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]

let arrayHeadTail = function [||] -> None | xs -> Some (xs.[0], Array.tail xs)

let rec permute xs =
    match arrayHeadTail xs with
    | None -> [| [] |]
    | Some (e, xs) -> Array.Parallel.collect (distribute e >> List.toArray) (permute xs)

let genAnagrams word =
  word
  |> Seq.toArray
  |> permute
  |> Array.map String.Concat<char>
</code>```

Title: Anagram generation with F# Async

Body:
I am trying to think of a way of how to improve speed of my program and one of the parts is anagram generation. Would the async features help in this case or there is another technique of manipulating strings?

let anagramWords = [|"rolex";"viagra";"win";"free";"cash";"grand";"prize";
                     "nude";"porn";"casino";"lottery";"spins";"sex";"gold"; "buy"; "clearance";
                     "business"; "biz"; "money"; "opportunity"; "earn"; "extra"; "potential"; "sleep"; "discount";
                     "bargain"; "credit"; "affordable"; "loans"; "mortages"; "quote"; "dollars"; "invest"; "investment";
                     "bitcoin"; "silver"; "save"; "unsecured"; "pennies"; "million"; "billion";"bureaus";"stock";
                     "bankruptcy"; "eliminate"; "debt"; "billing"; "iphone"; "selling"; "obligation";"trial";
                     "vacation"; "winner";"membership"; "preview"; "sample"; "priority"; "website"; "gift"; "gifts";
                     "present"; "deal"; "fantastic"; "outstanding"; "values"; "act"; "lifetime"; "urgent"|]

let rec distribute e = function
  | [] -> [[e]]
  | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]

let rec permute = function
  | [] -> [[]]
  | e::xs -> List.collect (distribute e) (permute xs)

let genAnagrams word =
  word
  |>List.ofSeq
  |>permute
  |> List.map (fun x -> String(x |> Array.ofList))
  |> Seq.ofList
  |> Seq.toList

Body:
One very simple way to make this a bit faster is to make permute use arrays instead of lists and use Array.Parallel.collect instead of List.collect. Even with the inefficiency of taking the head off an array, it becomes about 30% faster for me for a word of 10 characters.

open System

let rec distribute e = function
  | [] -> [[e]]
  | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]

let arrayHeadTail = function [||] -> None | xs -> Some (xs.[0], Array.tail xs)

let rec permute xs =
    match arrayHeadTail xs with
    | None -> [| [] |]
    | Some (e, xs) -> Array.Parallel.collect (distribute e >> List.toArray) (permute xs)

let genAnagrams word =
  word
  |> Seq.toArray
  |> permute
  |> Array.map String.Concat<char>


问:
Where do you add 'commons-codec-1.4.jar' to if you want access to encodeHexString etc?
Hey, this question links into another post  I made today: Reading the first 10 bytes of a file in Java

Having been told that my solution could involve the apache commons codec library, I've tried to figure out where the file needs to be placed and am seriously not getting it. Can't find anything online that simply says 'It goes here...' so maybe someone on here can help?

I've got Windows 7, I'm using JCreator and have the 'jre6' and 'jdk1.6.0_23' folders in my Program Files/Java folder

Any help at all would be appreciated so please let me know :)

Thanks :D

答:
You need to reference the jar file (not the containing directory) via your class path (a list of directories and .jar files)

e.g. from a command line:

```<code>$ java -cp {complete path to jar file} YourClass
</code>```

Alternatively you can set the CLASSPATH environment variable.

See here for more details.

Body:
You need to reference the jar file (not the containing directory) via your class path (a list of directories and .jar files)

e.g. from a command line:

$ java -cp {complete path to jar file} YourClass

Alternatively you can set the CLASSPATH environment variable.

See here for more details.


问:
aspx.designer.cs how does it work?
I'm a really beginner so my question may be appear ridiculous.. But, i wonder how the files .aspx.designer.cs works..
It's the first time i work with a solution containing files .aspx.designer.cs for each pages. So i understand it's declaration of controls used in the .aspx for code-behind..

Here is my questions:

Why sometimes solutions doen't have .aspx.designer.cs files? (is the files hidden or doesn't exists?)

I often have problems with this files, they don't Automatically recreate declarations of controls when i add some in the .aspx code, what am i doing wrong?

答:
As p.campbell pointed-out, the .designer.cs file links the .aspx file to its .aspx.cs CodeBehind file. Without the .designer.cs file, every .aspx page control in the .aspx.cs CodeBehind file will return the error, "does not exist in the current context". The linkage in .designer.cs is done based on the "Inherits" property of the @ Page directive in the aspx file together with the namespace and class of the .aspx.cs CodeBehind file. The final segment of the "Inherits" property must match the class defined in both the CodeBehind file and the .designer.cs file, and the segments prior to it must match the namespace of the .designer.cs and CodeBehind files.

Example:
myfile.aspx

```<code><%@ Page Language="C#"
    AutoEventWireup="true"
    CodeBehind="myfile.aspx.cs"
    Inherits="my.namespace.dot.classname" %>
</code>```

myfile.aspx.cs

```<code>namespace my.namespace.dot {
    public partial class classname : Page { ... }
}
</code>```

Note: the CodeBehind file class must inherit from the Page class, or some derivative thereof.

myfile.designer.aspx.cs

```<code>namespace my.namespace.dot {
    public partial class classname { ... }
}
</code>```

Note: the .designer.cs class doesn't care about inheritance, just that the class name matches the CodeBehind and .aspx files.

You can regenerate a lost .designer file like this (w3cgeek.com "Regenerate designer.cs"):

Create a new, blank file in same dir as your .aspx and .aspx.cs files named "myfile.aspx.designer.cs" where "myfile" is the name of the .aspx and .aspx.cs files that you want to link.

Add a namespace with an empty class to the new file, and ensure their names match the namespace and class specified in the .aspx and .aspx.cs files which you are linking.

Save the .designer.cs file, make any change to the .aspx file (e.g., adding a space), and save the .aspx file.

Visual Studio should auto-populate the .designer.cs file with all the necessary code to link your .aspx and CodeBehind files. The "does not exist in the current context" errors should now be gone!

EDIT: I added the .designer.cs instructions because the link is dead which was originally posted by p.campbell.

Title: aspx.designer.cs how does it work?

Body:
As p.campbell pointed-out, the .designer.cs file links the .aspx file to its .aspx.cs CodeBehind file. Without the .designer.cs file, every .aspx page control in the .aspx.cs CodeBehind file will return the error, "does not exist in the current context". The linkage in .designer.cs is done based on the "Inherits" property of the @ Page directive in the aspx file together with the namespace and class of the .aspx.cs CodeBehind file. The final segment of the "Inherits" property must match the class defined in both the CodeBehind file and the .designer.cs file, and the segments prior to it must match the namespace of the .designer.cs and CodeBehind files.

Example:
myfile.aspx

<%@ Page Language="C#"
    AutoEventWireup="true"
    CodeBehind="myfile.aspx.cs"
    Inherits="my.namespace.dot.classname" %>

myfile.aspx.cs

namespace my.namespace.dot {
    public partial class classname : Page { ... }
}

Note: the CodeBehind file class must inherit from the Page class, or some derivative thereof.

myfile.designer.aspx.cs

namespace my.namespace.dot {
    public partial class classname { ... }
}

Note: the .designer.cs class doesn't care about inheritance, just that the class name matches the CodeBehind and .aspx files.

You can regenerate a lost .designer file like this (w3cgeek.com "Regenerate designer.cs"):

Create a new, blank file in same dir as your .aspx and .aspx.cs files named "myfile.aspx.designer.cs" where "myfile" is the name of the .aspx and .aspx.cs files that you want to link.

Add a namespace with an empty class to the new file, and ensure their names match the namespace and class specified in the .aspx and .aspx.cs files which you are linking.

Save the .designer.cs file, make any change to the .aspx file (e.g., adding a space), and save the .aspx file.

Visual Studio should auto-populate the .designer.cs file with all the necessary code to link your .aspx and CodeBehind files. The "does not exist in the current context" errors should now be gone!

EDIT: I added the .designer.cs instructions because the link is dead which was originally posted by p.campbell.


问:
Pycparser not getting imported
2.7.11 python pckg for Mac - and installed the same.

Now I am trying to execute a python file

python file1.py

It throws up the error :

File "file1.py", line 107, in
      from pycparser import parse_file, c_parser, c_ast ImportError: No module named pycparser

How do I install this pycparser module ? can someone please help me here .

答: You Should go to File -> Settings -> Project: -> Project Interpreter and then on right hand side is a green plus and after clicking it add the "pycparser". Of course after instaling pycparser in cmd"pip3 install pycparser".</p>

Title: Pycparser not getting imported