问:
redux devtools does not show state in extension devtools tab
I'm writing a chrome extension using react and redux. The extension has it's own tabs in the chrome devtools. If I try to debug the react code, a new chrome devtools opens, where I can view the console, sources , etc.

I have the following in the store creation:

```<code>const store = createStore(rootReducer, preloadedState, compose(
    applyMiddleware(...middleware),
    global.devToolsExtension ? global.devToolsExtension() : f => f
))
</code>```

The problem is, redux devtools appears, but no store is detected. I've also tried the instructions from here, but still to no effect.

I'd also like to mention that both, global.devToolsExtension, as well as window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ are undefined.

Has anyone encountered this?

答:
I've managed to get the state to display using remote-redux-devtools. The trick was to right click Open Remote Devtools, and there, in the settings, mark to use local server.

In a separate tab, make sure you install remotedev-server, via npm or yarn. Example:

```<code>yarn add -D remotedev-server
</code>```

and run the following:

```<code>var remotedev = require('remotedev-server');
remotedev({ hostname: 'localhost', port: 8000 });
</code>```

Afte all this, the state should be visible in the redux devtools.

Body:
I'm writing a chrome extension using react and redux. The extension has it's own tabs in the chrome devtools. If I try to debug the react code, a new chrome devtools opens, where I can view the console, sources , etc.

I have the following in the store creation:

const store = createStore(rootReducer, preloadedState, compose(
    applyMiddleware(...middleware),
    global.devToolsExtension ? global.devToolsExtension() : f => f
))

The problem is, redux devtools appears, but no store is detected. I've also tried the instructions from here, but still to no effect.

I'd also like to mention that both, global.devToolsExtension, as well as window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ are undefined.

Has anyone encountered this?

Body:
I've managed to get the state to display using remote-redux-devtools. The trick was to right click Open Remote Devtools, and there, in the settings, mark to use local server.

In a separate tab, make sure you install remotedev-server, via npm or yarn. Example:

yarn add -D remotedev-server

and run the following:

var remotedev = require('remotedev-server');
remotedev({ hostname: 'localhost', port: 8000 });

Afte all this, the state should be visible in the redux devtools.


来源: stackexchange

问:
PowerBI: Change chart type upon selecting an element in Slicer
So I have this line chart in PowerBI which has Weeknumber as its X-axis. My Slicer also has Weeknumber as its Field (Element). When I select one single week from the slicer, the line chart turns to dots for obvious reasons. Is there any way in PowerBI for this line chart to be converted into bar chart in the same area when I select any element in my slicer.

This is what I have

This is what I want

答:
Let's say your table is named ChartData and has the values for the line are given by measures [Line1] and [Line2].

Change your chart into a Line and Clustered Column Chart with [Line1] and [Line2] in the Line Values section and ChartData[FiscalWeek] in the shared axis section.

Define new measures which are blank unless a single week is selected:

```<code>Bar1 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) = 1, [Line1], BLANK())
Bar2 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) = 1, [Line2], BLANK())
</code>```

Put those measures in the Column Values section and you should be good to go.

Note that this will still show the dots when you have the single week selected. If you don't want this, then define the line measures to only be non-blank when multiple weeks are selected and use those in place of [Line1] and [Line2]. E.g.

```<code>LineMeasure1 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) > 1, [Line1], BLANK())
LineMeasure2 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) > 1, [Line2], BLANK())
</code>```

It should look like this with no week selected:

And like this when one week is selected:

ContentLicense: CC BY-SA 3.0

Body:
Let's say your table is named ChartData and has the values for the line are given by measures [Line1] and [Line2].

Change your chart into a Line and Clustered Column Chart with [Line1] and [Line2] in the Line Values section and ChartData[FiscalWeek] in the shared axis section.

Define new measures which are blank unless a single week is selected:

Bar1 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) = 1, [Line1], BLANK())
Bar2 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) = 1, [Line2], BLANK())

Put those measures in the Column Values section and you should be good to go.

Note that this will still show the dots when you have the single week selected. If you don't want this, then define the line measures to only be non-blank when multiple weeks are selected and use those in place of [Line1] and [Line2]. E.g.

LineMeasure1 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) > 1, [Line1], BLANK())
LineMeasure2 = IF(COUNTROWS(ALLSELECTED(ChartData[FiscalWeek])) > 1, [Line2], BLANK())

It should look like this with no week selected:

And like this when one week is selected:


问:
JQUERY $(function() { initialisation
I've been working with JQuery for some time now and I've always used the following to initalise my javascript:

```<code>$(document).ready( function() {
// Initalisation logic
});
</code>```

However, recently I've noticed a lot of examples using the following:

```<code>$(function() {

});
</code>```

Whats the difference?

Thanks

答:
The difference is a matter of style.  One is just a shortcut of the other. :)
See http://api.jquery.com/jQuery/ near the bottom where it says "Executes the function when the DOM is ready to be used"

When I asked one of the jQuery UI people what they preferred, he said he preferred the more verbose way. However, people in my shop use this version:

```<code>$(function() {

});
</code>```

ContentLicense: CC BY-SA 2.5

Title: JQUERY $(function() { initialisation

Body:
I've been working with JQuery for some time now and I've always used the following to initalise my javascript:

$(document).ready( function() {
// Initalisation logic
});

However, recently I've noticed a lot of examples using the following:

$(function() {

});

Whats the difference?

Thanks

Body:
The difference is a matter of style.  One is just a shortcut of the other. :)
See http://api.jquery.com/jQuery/ near the bottom where it says "Executes the function when the DOM is ready to be used"

When I asked one of the jQuery UI people what they preferred, he said he preferred the more verbose way. However, people in my shop use this version:

$(function() {

});


问:
How to pass the date from the calendar to another activity [Android]
I am having trouble with passing the date from the calendar to another activity. It's not the current date that I wanted to show, it's the date that the user selects on the calendar that I have coded.

Below are my codes.

```<code>                            @Override
                public void onClick(View view)
                {
                    String date_month_year = (String)view.getTag();
                    selectedDayMonthYearButton.setText(new StringBuilder().append("Selected:").append(date_month_year));

                    Intent k = new Intent(Calendar_Event.this, Create_Events.class);
                 startActivity(k);

                    try
                    {
                        Date parsedDate = dateFormatter.parse(date_month_year);
                        Log.d(tag, "Parsed Date: " + parsedDate.toString());
                    }
                    catch(ParseException e)
                    {
                        e.printStackTrace();
                    }
                }

                public int getCurrentDayOfMonth()
                    {
                        return currentDayOfMonth;
                    }

                private void setCurrentDayOfMonth(int currentDayOfMonth)
                    {
                        this.currentDayOfMonth = currentDayOfMonth;
                    }
                public void setCurrentWeekDay(int currentWeekDay)
                    {
                        this.currentWeekDay = currentWeekDay;
                    }
                public int getCurrentWeekDay()
                    {
                        return currentWeekDay;
                    }

        }//end GridCellAdapter
</code>```

I trying to pass the date selected onClick to the next activity that this class is linked to.
 Any help will be greatly appreciated, Thanks you!

答:
Consider to convert calendar variable into long by calling getTimeInMillis()

```<code>/* GetDateActivity.java */

Intent intent = new Intent();

Calendar myDate = Calendar.getInstance();
myDate.set(Calendar.YEAR, 1970);
myDate.set(Calendar.MONTH, 1);
myDate.set(Calendar.DAY_OF_MONTH, 1);

intent.putExtra("myDateKey", myDate.getTimeInMillis());
setResult(RESULT_OK, intent);
// Terminate current activity
finish();
</code>```

Then, inside activity which called startActivityForResult(intent), i.e. MainActivity.java

```<code>public static final int REQUEST_DATE_CODE = 777;

...

Intent i = new Intent(MainActivity.class, GetDateActivity.class);
startActivityForResult(i, REQUEST_DATE_CODE);

...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_DATE_CODE:
            if (resultCode == RESULT_OK && data != null) {

                Calendar myDate = Calendar.getInstance();
                myDate.setTimeInMillis(extras.getLong("myDateKey"));

                Date date = myDate.getTime();
                SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("EEE, MMM d, ''yy", Locale.getDefault());
                Log.d(tag, "Parsed Date: " + simpleDateFormatter.format(date));
           }
           break;
    }
}
</code>```

Body:
I am having trouble with passing the date from the calendar to another activity. It's not the current date that I wanted to show, it's the date that the user selects on the calendar that I have coded.

Below are my codes.

                            @Override
                public void onClick(View view)
                {
                    String date_month_year = (String)view.getTag();
                    selectedDayMonthYearButton.setText(new StringBuilder().append("Selected:").append(date_month_year));

                    Intent k = new Intent(Calendar_Event.this, Create_Events.class);
                 startActivity(k);

                    try
                    {
                        Date parsedDate = dateFormatter.parse(date_month_year);
                        Log.d(tag, "Parsed Date: " + parsedDate.toString());
                    }
                    catch(ParseException e)
                    {
                        e.printStackTrace();
                    }
                }

                public int getCurrentDayOfMonth()
                    {
                        return currentDayOfMonth;
                    }

                private void setCurrentDayOfMonth(int currentDayOfMonth)
                    {
                        this.currentDayOfMonth = currentDayOfMonth;
                    }
                public void setCurrentWeekDay(int currentWeekDay)
                    {
                        this.currentWeekDay = currentWeekDay;
                    }
                public int getCurrentWeekDay()
                    {
                        return currentWeekDay;
                    }

        }//end GridCellAdapter

I trying to pass the date selected onClick to the next activity that this class is linked to.
 Any help will be greatly appreciated, Thanks you!

Body:
Consider to convert calendar variable into long by calling getTimeInMillis()

/* GetDateActivity.java */

Intent intent = new Intent();

Calendar myDate = Calendar.getInstance();
myDate.set(Calendar.YEAR, 1970);
myDate.set(Calendar.MONTH, 1);
myDate.set(Calendar.DAY_OF_MONTH, 1);

intent.putExtra("myDateKey", myDate.getTimeInMillis());
setResult(RESULT_OK, intent);
// Terminate current activity
finish();

Then, inside activity which called startActivityForResult(intent), i.e. MainActivity.java

public static final int REQUEST_DATE_CODE = 777;

...

Intent i = new Intent(MainActivity.class, GetDateActivity.class);
startActivityForResult(i, REQUEST_DATE_CODE);

...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_DATE_CODE:
            if (resultCode == RESULT_OK && data != null) {

                Calendar myDate = Calendar.getInstance();
                myDate.setTimeInMillis(extras.getLong("myDateKey"));

                Date date = myDate.getTime();
                SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("EEE, MMM d, ''yy", Locale.getDefault());
                Log.d(tag, "Parsed Date: " + simpleDateFormatter.format(date));
           }
           break;
    }
}


问:
How to get the value from Parameterized Test Fixtures?
How to get the TestFixture parameter value as string and pass to Switch statement? I tried but can't solve the issue "Member 'ClassLibrary1.Browsers.browser1' cannot be accessed with an instance reference; qualify it with a type name instead".
Init method should be a static because i used this in another class.

Code here:

```<code>[TestFixture("Chrome")]
public class Browsers
{
    public static IWebDriver webDriver;
    private static string baseURL = "https://www.google.com";
    private static string browser;

    private static string browser1;

    public Browsers(string browser1)
    {
         this.browser1 = browser1;
    }

    public static void Init()
    {
        switch (browser1)
        {
            case "Chrome":
                webDriver = new ChromeDriver();
                break;
            case "IE":
                webDriver = new InternetExplorerDriver();
                break;
            case "Firefox":
                webDriver = new FirefoxDriver();
                break;
        }
        webDriver.Manage().Window.Maximize();
        Goto(baseURL);
    }
    public static string Title
    {
        get { return webDriver.Title; }
    }
    public static IWebDriver getDriver
    {
        get { return webDriver; }
    }
    public static void Goto(string url)
    {
        webDriver.Navigate().GoToUrl(url);
    }
    public static void Close()
    {
        webDriver.Quit();
    }
}
</code>```

答:
The issue is that you are trying to assign to a static field inside the constructor of the class. The constructor gets executed when creating an instance of the class. So you cannot do:

```<code>//This doesn't compile:
public class Browsers
{
    //snip
    private static string browser1;

    public Browsers(string browser1)
    {
        this.browser1 = browser1;
    }
    //snip
}
</code>```

because there is no this.browser1 field - browser1 was declared as static so doesn't exist on an instance.

I think you were aiming for something like this instead:

```<code>[TestFixture("My String")]
public class When_Working_Up_A_Storm
{
    public When_Working_Up_A_Storm(string myString)
    {
        _myString = myString;
    }

    private string _myString;

    [Test]
    public void Magic_Happens()
    {
        Assert.AreEqual("My String", _myString);
    }
}
</code>```

Body:
How to get the TestFixture parameter value as string and pass to Switch statement? I tried but can't solve the issue "Member 'ClassLibrary1.Browsers.browser1' cannot be accessed with an instance reference; qualify it with a type name instead".
Init method should be a static because i used this in another class.

Code here:

[TestFixture("Chrome")]
public class Browsers
{
    public static IWebDriver webDriver;
    private static string baseURL = "https://www.google.com";
    private static string browser;

    private static string browser1;

    public Browsers(string browser1)
    {
         this.browser1 = browser1;
    }

    public static void Init()
    {
        switch (browser1)
        {
            case "Chrome":
                webDriver = new ChromeDriver();
                break;
            case "IE":
                webDriver = new InternetExplorerDriver();
                break;
            case "Firefox":
                webDriver = new FirefoxDriver();
                break;
        }
        webDriver.Manage().Window.Maximize();
        Goto(baseURL);
    }
    public static string Title
    {
        get { return webDriver.Title; }
    }
    public static IWebDriver getDriver
    {
        get { return webDriver; }
    }
    public static void Goto(string url)
    {
        webDriver.Navigate().GoToUrl(url);
    }
    public static void Close()
    {
        webDriver.Quit();
    }
}

Body:
The issue is that you are trying to assign to a static field inside the constructor of the class. The constructor gets executed when creating an instance of the class. So you cannot do:

//This doesn't compile:
public class Browsers
{
    //snip
    private static string browser1;

    public Browsers(string browser1)
    {
        this.browser1 = browser1;
    }
    //snip
}

because there is no this.browser1 field - browser1 was declared as static so doesn't exist on an instance.

I think you were aiming for something like this instead:

[TestFixture("My String")]
public class When_Working_Up_A_Storm
{
    public When_Working_Up_A_Storm(string myString)
    {
        _myString = myString;
    }

    private string _myString;

    [Test]
    public void Magic_Happens()
    {
        Assert.AreEqual("My String", _myString);
    }
}


问:
Is ragel not designed to be used with files?
Looking into ragel and can't figure out how to reasonably read from a file. As far as I understand, it requires a memory buffer that is not broken in the middle of a token. This is obviously quite a lot of work to implement, especially if I don't know the size of the tokens, e.g. strings with new-lines, escapes, etc. If I'm implementing all that, I'm not sure I need ragel any more.

Is there no better way?

答:
If you map a file into memory (mmap, CreateFileMapping) you'll have the entire file available as one contiguous chunk of memory.

Also look at the Ragel User Guide (5.9 Maintaining Pointers to Input Data) which has some sample code for dealing with that situation. For strings or tokens that might exceed a fixed buffer size, you could use a variable sized buffer that grows as necessary.


问:
Algorithm finding path in an undirected tree
Suppose I am given a undirected tree and I need to find a path(the only path) between two nodes.

What is the best algorithm to do it.I probably could use a Dijkstra's algorithm but there a probably something better for trees.

C++ example would be helpful but not necessary

Thank you

答: Breadth-first search and depth-first search are more effective then Dijkstra's algorithm.</p>


问:
Can't get http response as a string in Angular 5
Given the source Angular Service code

@Injectable()
export class HomeContentService {

  constructor(private http: HttpClient) { }

  getContent(): Observable<string> {

    let fileURI = '/assets/content/home.md';
    let opt = { responseType: 'text' };
    return this.http.get<string>(
      fileURI,
      opt
    );

  }
```

Calling getContent() should return an Observable<string>. However, when I run ng serve, I get Type 'string' is not assignable to type 'json'.

After a few tries webpack seems to compile fine without me doing any changes, but the problem happens again anytime I close the process and try to ng serve again.

I guess there's something wrong with my setting responseType: 'text', but I don't know what it is. Googling wasn't helpful either.

Any ideas?

答:
Try let opt = { responseType: 'text' as 'text' };

Explanation: https://github.com/angular/angular/issues/18586

Body:
Given the source Angular Service code

@Injectable()
export class HomeContentService {

  constructor(private http: HttpClient) { }

  getContent(): Observable<string> {

    let fileURI = '/assets/content/home.md';
    let opt = { responseType: 'text' };
    return this.http.get<string>(
      fileURI,
      opt
    );

  }

Calling getContent() should return an Observable<string>. However, when I run ng serve, I get Type 'string' is not assignable to type 'json'.

After a few tries webpack seems to compile fine without me doing any changes, but the problem happens again anytime I close the process and try to ng serve again.

I guess there's something wrong with my setting responseType: 'text', but I don't know what it is. Googling wasn't helpful either.

Any ideas?


问:
How to avoid long if else statements using RxJS
I'm trying to use RxJS to replace the next piece of code(jsbin):

```<code>function parseRequestUrl(url) {
  var newUrl;
  if ((newUrl = testThatUrlIsOrigin1(url)) !== url) {
    return doSomething(newUrl);
  }
  if ((newUrl = testThatUrlIsOrigin2(url)) !== url) {
    return doSomething(newUrl);
  }
  if ((newUrl = testThatUrlIsOrigin3(url)) !== url) {
    return doSomething(newUrl);
  }
}
</code>```

Something i was able to achieve using RxJS(jsbin) but in that case i needed to call a function twice for which "filter expression" is true

```<code>function parseRequestUrl(url) {
  var newUrl = url;
  var observer = Rx.Observable.of(testThatUrlIsOrigin1, testThatUrlIsOrigin2, testThatUrlIsOrigin3);
  observer.first(getUrlFunc => getUrlFunc(url) !== url).map(getUrlFunc => getUrlFunc(url)).subscribe(createdUrl => newUrl = createdUrl)

  return doSomething(newUrl);
  // And so on
}
</code>```

Can RxJS suit my requirements ?

答:
I don't think that RxJs is the right tool for the job. It is best suited for processing asynchronous streams of data. I think that a better approach would be to just put all of your test functions in an array and loop over them. Something like this:

const tests = [testThatUrlIsOrigin1, testThatUrlIsOrigin2, testThatUrlIsOrigin3];
function parseRequestUrl(url) {
  for (const test of tests) {
    const newUrl = test(url);
    if (newUrl === url) continue;
    return newUrl;
  }
}

function testThatUrlIsOrigin1(url) {
 console.log("try testThatUrlIsOrigin1");
 if (url === 'origin1') {
      console.log("Pass testThatUrlIsOrigin1");
      return "First If";
  }
  return url;
}

function testThatUrlIsOrigin2(url) {
 console.log("try testThatUrlIsOrigin2");
 if (url === 'origin2') {
      console.log("Pass testThatUrlIsOrigin2");
     return "Second If";
    }
  return url;
}

function testThatUrlIsOrigin3(url) {
 console.log("try testThatUrlIsOrigin3");
 if (url === 'origin3') {
      console.log("Pass testThatUrlIsOrigin3");
      return "Third If";
    }
  return url;
}

parseRequestUrl('origin2')```
</div>
</div>
</p>

<p>You could also implement the Chain of Responsibility design pattern if you wanted to get all OO on it.</p>

<p><strong>EDIT</strong>
Since you want to see how to do it in RxJs, here is a simplified version:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function test(a, b) {
  return a === b ? `${a} test` : b;
}

const tests = [
  test.bind(null, 1),
  test.bind(null, 2),
  test.bind(null, 3),
];

const value = 2;
Rx.Observable.from(tests)
    .map(x => x(value))
    .filter(x => x !== value)
    .take(1)
    .subscribe(
      x => { console.log(x); },
      null,
      () => { console.log('completed'); }
    );</code>```

```

Body:
I'm trying to use RxJS to replace the next piece of code(jsbin):

function parseRequestUrl(url) {
  var newUrl;
  if ((newUrl = testThatUrlIsOrigin1(url)) !== url) {
    return doSomething(newUrl);
  }
  if ((newUrl = testThatUrlIsOrigin2(url)) !== url) {
    return doSomething(newUrl);
  }
  if ((newUrl = testThatUrlIsOrigin3(url)) !== url) {
    return doSomething(newUrl);
  }
}

Something i was able to achieve using RxJS(jsbin) but in that case i needed to call a function twice for which "filter expression" is true

function parseRequestUrl(url) {
  var newUrl = url;
  var observer = Rx.Observable.of(testThatUrlIsOrigin1, testThatUrlIsOrigin2, testThatUrlIsOrigin3);
  observer.first(getUrlFunc => getUrlFunc(url) !== url).map(getUrlFunc => getUrlFunc(url)).subscribe(createdUrl => newUrl = createdUrl)

  return doSomething(newUrl);
  // And so on
}

Can RxJS suit my requirements ?

Body:
I don't think that RxJs is the right tool for the job. It is best suited for processing asynchronous streams of data. I think that a better approach would be to just put all of your test functions in an array and loop over them. Something like this:

const tests = [testThatUrlIsOrigin1, testThatUrlIsOrigin2, testThatUrlIsOrigin3];
function parseRequestUrl(url) {
  for (const test of tests) {
    const newUrl = test(url);
    if (newUrl === url) continue;
    return newUrl;
  }
}

function testThatUrlIsOrigin1(url) {
 console.log("try testThatUrlIsOrigin1");
 if (url === 'origin1') {
      console.log("Pass testThatUrlIsOrigin1");
      return "First If";
  }
  return url;
}

function testThatUrlIsOrigin2(url) {
 console.log("try testThatUrlIsOrigin2");
 if (url === 'origin2') {
      console.log("Pass testThatUrlIsOrigin2");
     return "Second If";
    }
  return url;
}

function testThatUrlIsOrigin3(url) {
 console.log("try testThatUrlIsOrigin3");
 if (url === 'origin3') {
      console.log("Pass testThatUrlIsOrigin3");
      return "Third If";
    }
  return url;
}

parseRequestUrl('origin2')

You could also implement the Chain of Responsibility design pattern if you wanted to get all OO on it.

EDIT
Since you want to see how to do it in RxJs, here is a simplified version:

function test(a, b) {
  return a === b ? `${a} test` : b;
}

const tests = [
  test.bind(null, 1),
  test.bind(null, 2),
  test.bind(null, 3),
];

const value = 2;
Rx.Observable.from(tests)
    .map(x => x(value))
    .filter(x => x !== value)
    .take(1)
    .subscribe(
      x => { console.log(x); },
      null,
      () => { console.log('completed'); }
    );

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>


问:
Android Studio 3.0 not able to import google play service even it is added in build.gradle file
I am trying to fetch device current location but when i am trying to imported Location Service it. But it show can not resolve symbol LocationService

```<code>import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
</code>```

Build.gradle file

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support:design:26.0.0-beta1'
    implementation 'com.google.android.gms:play-services-maps:11.6.0'

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

I have tried with google play services previous version (11.4.2) as well

答:
I have to add play location service dependency as well.</p>

```<code>implementation 'com.google.android.gms:play-services-maps:11.+'
compile 'com.google.android.gms:play-services-location:11.+'
</code>```

Body:
I am trying to fetch device current location but when i am trying to imported Location Service it. But it show can not resolve symbol LocationService

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

Build.gradle file

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support:design:26.0.0-beta1'
    implementation 'com.google.android.gms:play-services-maps:11.6.0'

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

I have tried with google play services previous version (11.4.2) as well

Body:
I have to add play location service dependency as well.

implementation 'com.google.android.gms:play-services-maps:11.+'
compile 'com.google.android.gms:play-services-location:11.+'


问:
Create WCF Data Service for use in service host
I have a service application that host several WCF endpoints through different bindings. I want now to host a WCF Data Service in the same service Host. This post makes me believe it's possible. However, every single example on how to create a WCF Data Service creates it from inside an ASP.NET Web project, not a Class Library or Service Application. In fact, the WCF Data Service doesn't even show up in the Add New Item when selected from one of these project types.

My question is how do I create a WCF Data Service inside a Class Library, that will be called by a service host, that's already hosting several other WCF endpoints? The link I already referenced shows me how to host the Data Service after it's created, but since it doesn't show up as an option of the Add New Item, I'm kinna stuck.

答: One way you may be able to accomplish this is to create an ASP.NET project to contain the WCF Data Service and then define a custom data service host (scroll down to the 'Defining a Custom Data Service Host' section) that acts as a mediator between your existing WCF host and the Data Service.</p>


问:
Cannot install spring-boot-starter-parent no matter what I do
I just setup a new computer -- fully new Java 1.8 installation, new 3.5.2 Maven configuration, and I'm now working on setting up a fresh quickstart Maven project.

When I add the parent spring boot starter and a single dependency, it cannot resolve it no matter what I do.

Here's the trace:

```<code>[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.boot:das-boot:1.0-SNAPSHOT: Failure to find org.springframework.boot:spring-boot-starter-parent:pom:1.5.9-RELEASE in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced and 'parent.relativePath' points at wrong local POM @ line 10, column 11
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.boot:das-boot:1.0-SNAPSHOT (D:\workspace\das-boot\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for com.boot:das-boot:1.0-SNAPSHOT: Failure to find org.springframework.boot:spring-boot-starter-parent:pom:1.5.9-RELEASE in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced and 'parent.relativePath' points at wrong local POM @ line 10, column 11 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

And here's my full pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.boot</groupId>
  <artifactId>das-boot</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9-RELEASE</version>
  </parent>

  <name>das-boot</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
</code>```

Output of mvn -version:

```<code>D:\workspace\das-boot>mvn -version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T00:58:13-07:00)
Maven home: C:\Program Files\apache-maven-3.5.2\bin\..
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_151\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
</code>```

What could possibly be going on? I'm not behind a proxy, it fails in IntelliJ and on CMD, and everything is freshly installed w/ default settings.

答:
It's 1.5.9.RELEASE, according to their website, not 1.5.9-RELEASE.

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
</code>```

Body:
I just setup a new computer -- fully new Java 1.8 installation, new 3.5.2 Maven configuration, and I'm now working on setting up a fresh quickstart Maven project.

When I add the parent spring boot starter and a single dependency, it cannot resolve it no matter what I do.

Here's the trace:

[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.boot:das-boot:1.0-SNAPSHOT: Failure to find org.springframework.boot:spring-boot-starter-parent:pom:1.5.9-RELEASE in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced and 'parent.relativePath' points at wrong local POM @ line 10, column 11
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.boot:das-boot:1.0-SNAPSHOT (D:\workspace\das-boot\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for com.boot:das-boot:1.0-SNAPSHOT: Failure to find org.springframework.boot:spring-boot-starter-parent:pom:1.5.9-RELEASE in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced and 'parent.relativePath' points at wrong local POM @ line 10, column 11 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

And here's my full pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.boot</groupId>
  <artifactId>das-boot</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9-RELEASE</version>
  </parent>

  <name>das-boot</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Output of mvn -version:

D:\workspace\das-boot>mvn -version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T00:58:13-07:00)
Maven home: C:\Program Files\apache-maven-3.5.2\bin\..
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_151\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

What could possibly be going on? I'm not behind a proxy, it fails in IntelliJ and on CMD, and everything is freshly installed w/ default settings.

Body:
It's 1.5.9.RELEASE, according to their website, not 1.5.9-RELEASE.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>


问:
DbFlow Kotlin and List<String> Type Converter
DBFlow Version: 4.0.4
Hi, I'm strugling with List Type converter with dbflow Android ORM and Kotlin. I have a data class defined like this:

```<code>@Table(database = StopsDb::class)
data class FavouriteStop(
        @PrimaryKey @Column var id: String = "",
        @Index @Column var name: String = "",
        @Column(typeConverter = StringListConverter::class) var directions: List<String> = listOf(),
        @Column(typeConverter = StringListConverter::class) var selectedDirections: List<String> = listOf()
) : BaseRXModel()
</code>```

and as I don't want to create a separate table only to store Strings I created a List Type converter like this:

```<code>class StringListConverter : TypeConverter<String, List<String>>() {

    val separator = ","

    override fun getDBValue(model: List<String>?): String {
        if(model==null || model.isEmpty())
            return ""
        else
            return model.joinToString (separator = separator){ it }
    }

    override fun getModelValue(data: String?): List<String> {
        return data?.split(separator) ?: listOf()
    }
}
</code>```

however following error is thrown during build phase:

```<code>Error:error: *==========* :The specified custom TypeConverter's Model Value java.util.List<? extends java.lang.String> from com.kapuscinski.departures.persistence.db.StringListConverter must match the type of the column java.util.List<java.lang.String>.*==========*
</code>```

Am I missing something here, and how to fix this? Thanks in advance for help!

答:
Change everything from "List" to "MutableList"</p>

```<code>@Table(database = StopsDb::class)
data class FavouriteStop(
        @PrimaryKey @Column var id: String = "",
        @Index @Column var name: String = "",
        @Column(typeConverter = StringListConverter::class) var directions: MutableList<String> = mutableListOf(),
        @Column(typeConverter = StringListConverter::class) var selectedDirections: MutableList<String> = mutableListOf()
) : BaseRXModel()

class StringListConverter : TypeConverter<String, MutableList<String>>() {
    val separator = ","

    override fun getDBValue(model: MutableList<String>?): String =
            if (model == null || model.isEmpty())
                ""
            else
                model.joinToString(separator = separator) { it }

    override fun getModelValue(data: String?): MutableList<String> {
        return data?.split(separator)?.toMutableList() ?: mutableListOf()
    }
}
</code>```

Body:
DBFlow Version: 4.0.4
Hi, I'm strugling with List Type converter with dbflow Android ORM and Kotlin. I have a data class defined like this:

@Table(database = StopsDb::class)
data class FavouriteStop(
        @PrimaryKey @Column var id: String = "",
        @Index @Column var name: String = "",
        @Column(typeConverter = StringListConverter::class) var directions: List<String> = listOf(),
        @Column(typeConverter = StringListConverter::class) var selectedDirections: List<String> = listOf()
) : BaseRXModel()

and as I don't want to create a separate table only to store Strings I created a List Type converter like this:

class StringListConverter : TypeConverter<String, List<String>>() {

    val separator = ","

    override fun getDBValue(model: List<String>?): String {
        if(model==null || model.isEmpty())
            return ""
        else
            return model.joinToString (separator = separator){ it }
    }

    override fun getModelValue(data: String?): List<String> {
        return data?.split(separator) ?: listOf()
    }
}

however following error is thrown during build phase:

Error:error: *==========* :The specified custom TypeConverter's Model Value java.util.List<? extends java.lang.String> from com.kapuscinski.departures.persistence.db.StringListConverter must match the type of the column java.util.List<java.lang.String>.*==========*

Am I missing something here, and how to fix this? Thanks in advance for help!

Body:
Change everything from "List" to "MutableList"

@Table(database = StopsDb::class)
data class FavouriteStop(
        @PrimaryKey @Column var id: String = "",
        @Index @Column var name: String = "",
        @Column(typeConverter = StringListConverter::class) var directions: MutableList<String> = mutableListOf(),
        @Column(typeConverter = StringListConverter::class) var selectedDirections: MutableList<String> = mutableListOf()
) : BaseRXModel()

class StringListConverter : TypeConverter<String, MutableList<String>>() {
    val separator = ","

    override fun getDBValue(model: MutableList<String>?): String =
            if (model == null || model.isEmpty())
                ""
            else
                model.joinToString(separator = separator) { it }

    override fun getModelValue(data: String?): MutableList<String> {
        return data?.split(separator)?.toMutableList() ?: mutableListOf()
    }
}


问:
How to run Celery Periodic task at every end of the month
Basically, I have a task to generate Invoice. So I have created a function generate_invoice() in my tasks.py file.

Now, I am using @periodic_task to call the function. But I need my task to run only on the last date of the month around 11:55 pm - 11:57 pm.

I am getting the last date of month using this function:

```<code>def get_last_date():
        today = timezone.now()
        year = today.year
        month = today.month
        last_date = calendar.monthrange(year, month)[1]
        return str(last_date)
</code>```

My code for task looks like this:

```<code>@periodic_task(run_every=(crontab(day_of_month=get_last_date())), name="invoice_simulation", ignore_result=True)
def invoice_simulation():
    generate_invoice()
</code>```

But this is not working!

Or is there any better way to implement this feature then please suggest.

答:
A rather simpler solution would be to run the schedule every day at 11:55 PM, and check inside the task if today is the last day of the month. If so, generate the invoice. If not then simply do nothing.

Something like:

```<code>@periodic_task(run_every=(crontab(hour=23, minute=55)), name="invoice_simulation", ignore_result=True)
def invoice_simulation():
    if timezone.now().day == get_last_date():
        generate_invoice()
</code>```

Just make sure that timezone and crontab do not conflict each other. Both must either be TZ aware (or in UTC), or use naive times for both.

Body:
Basically, I have a task to generate Invoice. So I have created a function generate_invoice() in my tasks.py file.

Now, I am using @periodic_task to call the function. But I need my task to run only on the last date of the month around 11:55 pm - 11:57 pm.

I am getting the last date of month using this function:

def get_last_date():
        today = timezone.now()
        year = today.year
        month = today.month
        last_date = calendar.monthrange(year, month)[1]
        return str(last_date)

My code for task looks like this:

@periodic_task(run_every=(crontab(day_of_month=get_last_date())), name="invoice_simulation", ignore_result=True)
def invoice_simulation():
    generate_invoice()

But this is not working!

Or is there any better way to implement this feature then please suggest.

Body:
A rather simpler solution would be to run the schedule every day at 11:55 PM, and check inside the task if today is the last day of the month. If so, generate the invoice. If not then simply do nothing.

Something like:

@periodic_task(run_every=(crontab(hour=23, minute=55)), name="invoice_simulation", ignore_result=True)
def invoice_simulation():
    if timezone.now().day == get_last_date():
        generate_invoice()

Just make sure that timezone and crontab do not conflict each other. Both must either be TZ aware (or in UTC), or use naive times for both.


问:
variable dosent set new value
I Have created a generic function to handle three simple ajax requests to backend code. I only have one single problem left, and that is if systemName "AD" returns a code 0, then the two following functions should not be fired at all..
But it looks like it runs the function and directly after tests if the condition sADsuccess=1 or not, and dosent wait for the function to set the variable..
So my question is: How can i write this in a better way?

```<code> var sADsuccess=1;
        $("#frmPwdChg").submit(function(e) {
            var formzData =  $("#frmPwdChg").serialize();

            ChangeSystemPwd('UPDATE/AD/USER/PASSWORD/',formzData,'AD',1,0,0)
                if(sADsuccess=1){
                 ChangeSystemPwd('UPDATE/Cosmic/PASSWORD/',formzData,'Cosmic',0,0,0);
                 ChangeSystemPwd('UPDATE/Imprivata/PASSWORD/',formzData,'Imprivata',0,1,1);
                }
                else{
                    $("#btnPwdChg").removeClass("loading");
                    $("#btnPwdRes").addClass("hidden");
                    $("#btnLogout").removeClass("hidden");
                    $("#frmPwdChg")[0].reset();
                }
            e.preventDefault(); // avoid to execute the actual submit of the form.
        });

function ChangeSystemPwd(APIurl,sFormData,sSystemName,loadStart,loadEnd,bEmptyForm){
var url = sUrl + APIurl

$("#btnPwdChg").addClass("loading");
$.getJSON({
       type: "POST",
       url: url,
       data: sFormData,
       success: function(response) //Om Ajax anropet lyckas
       {
           var sMessage=response[0].message;
           var sCode=response[0].code

            if(sCode===1) {
                showGreen(sSystemName,sMessage)
                sessionStorage.setItem(sSystemName, 'success');
        }
            else if(sCode===0) {
                showRed(sSystemName,sMessage);
                sessionStorage.setItem(sSystemName, 'failure');
                if(sSystemName='AD'){
                    alert('AD')
                    sADsuccess=0;
                }
        }
            else if(sCode===-1){
                //anropet kom tillbaka som att det inte fanns någon användare. Visa ingenting
                sessionStorage.setItem(sSystemName, 'no-user');
        }
       },
       error: function(xhr,response){ //Om ajax anropet inte lyckas, hämta status och skriv ut ett meddelande
        showErr(xhr,response,'#errResponse')
        },
       complete: function(xhr,data){
        if (loadEnd==1){
            $("#btnPwdChg").removeClass("loading"),$("#btnPwdRes").addClass("hidden"),$("#btnLogout").removeClass("hidden");
                }
        if (bEmptyForm==1){
            $("#frmPwdChg")[0].reset();
        }
        }

});
</code>```

}

答:
```<code>sADsuccess=1
</code>```

is an assignment, not a comparison. Instead of =, use == or ===.

Title: variable dosent set new value

Body:
I Have created a generic function to handle three simple ajax requests to backend code. I only have one single problem left, and that is if systemName "AD" returns a code 0, then the two following functions should not be fired at all..
But it looks like it runs the function and directly after tests if the condition sADsuccess=1 or not, and dosent wait for the function to set the variable..
So my question is: How can i write this in a better way?

 var sADsuccess=1;
        $("#frmPwdChg").submit(function(e) {
            var formzData =  $("#frmPwdChg").serialize();

            ChangeSystemPwd('UPDATE/AD/USER/PASSWORD/',formzData,'AD',1,0,0)
                if(sADsuccess=1){
                 ChangeSystemPwd('UPDATE/Cosmic/PASSWORD/',formzData,'Cosmic',0,0,0);
                 ChangeSystemPwd('UPDATE/Imprivata/PASSWORD/',formzData,'Imprivata',0,1,1);
                }
                else{
                    $("#btnPwdChg").removeClass("loading");
                    $("#btnPwdRes").addClass("hidden");
                    $("#btnLogout").removeClass("hidden");
                    $("#frmPwdChg")[0].reset();
                }
            e.preventDefault(); // avoid to execute the actual submit of the form.
        });

function ChangeSystemPwd(APIurl,sFormData,sSystemName,loadStart,loadEnd,bEmptyForm){
var url = sUrl + APIurl

$("#btnPwdChg").addClass("loading");
$.getJSON({
       type: "POST",
       url: url,
       data: sFormData,
       success: function(response) //Om Ajax anropet lyckas
       {
           var sMessage=response[0].message;
           var sCode=response[0].code

            if(sCode===1) {
                showGreen(sSystemName,sMessage)
                sessionStorage.setItem(sSystemName, 'success');
        }
            else if(sCode===0) {
                showRed(sSystemName,sMessage);
                sessionStorage.setItem(sSystemName, 'failure');
                if(sSystemName='AD'){
                    alert('AD')
                    sADsuccess=0;
                }
        }
            else if(sCode===-1){
                //anropet kom tillbaka som att det inte fanns någon användare. Visa ingenting
                sessionStorage.setItem(sSystemName, 'no-user');
        }
       },
       error: function(xhr,response){ //Om ajax anropet inte lyckas, hämta status och skriv ut ett meddelande
        showErr(xhr,response,'#errResponse')
        },
       complete: function(xhr,data){
        if (loadEnd==1){
            $("#btnPwdChg").removeClass("loading"),$("#btnPwdRes").addClass("hidden"),$("#btnLogout").removeClass("hidden");
                }
        if (bEmptyForm==1){
            $("#frmPwdChg")[0].reset();
        }
        }

});

}

Body:
sADsuccess=1

is an assignment, not a comparison. Instead of =, use == or ===.


问:
Swagger node is taking URL phrase as parameter
I'm using swagger-node for REST APIs and I've found an absurd issue here.

Here's my one of GET requests:

```<code>GET: /students/{id}/{name}
</code>```

(id is number)

And now I wrote another request:

```<code>GET: /students/routeInfo/{id}
</code>```

But the 2nd request me following error:

Expected type is number, found type string. Which clearly means 2nd request is trying to "mask" 1st request. Which I think shouldn't be.

Am I doing something wrong or is there any other way to handle this?

答:
In your path definitions, changeChange your 'parameters' type: number for type: string

Your path will look like this:

```<code>/students/routeInfo/{id}:
x-swagger-router-controller: yourStudentController
get:
  tags:
    - Student
  description: description
  operationId: yourOperation
  parameters:
    - name: id
      in: path
      description: description id of routeInfo
      required: true
      type: string
</code>```

See more at https://swagger.io/docs/specification/paths-and-operations/

Body:
I'm using swagger-node for REST APIs and I've found an absurd issue here.

Here's my one of GET requests:

GET: /students/{id}/{name}

(id is number)

And now I wrote another request:

GET: /students/routeInfo/{id}

But the 2nd request me following error:

Expected type is number, found type string. Which clearly means 2nd request is trying to "mask" 1st request. Which I think shouldn't be.

Am I doing something wrong or is there any other way to handle this?

Body:
In your path definitions, changeChange your 'parameters' type: number for type: string

Your path will look like this:

/students/routeInfo/{id}:
x-swagger-router-controller: yourStudentController
get:
  tags:
    - Student
  description: description
  operationId: yourOperation
  parameters:
    - name: id
      in: path
      description: description id of routeInfo
      required: true
      type: string

See more at https://swagger.io/docs/specification/paths-and-operations/


问:
Get past row limitation
My report processes millions of records. When the number of rows gets too high, I get this error:

The number of rows or columns is too big. Try limiting the number of unique group values.
  Details: The number of rows or columns exceeds its limit, 65535.

How can I work around (or increase) this limit?

答:
This error is pretty straightforward. 65535 is 0xFFFF in hexadecimal, so once you hit that limit there's no more vacancies and the hotel is closed. Solutions include:

Reduce the number of rows displayed by using grouping in your crosstab or whatever.

Reduce the amount of incoming data to your report with Record Selection. (Parameters)

Perform the dependent calculations in a custom SQL statement, generated as a temporary table in your report. You can then pass the results into your report as fields, rather than having to print millions of lines.

Title: Get past row limitation


问:
Random data from another Model relationship in Laravel
I have 2 Models(Category and Company) with relationship between them. I want to show random Companies. How to use inRandomOrder/shuffle() in subquery.

I tried this. But it shuffle Category, but not Companies. I need opposite.

```<code>$categoriesAll = \App\Category::all()->shuffle();
</code>```

My view looks like this:

```<code>@foreach ($categoriesAll as $categoryAll)
  <div class="header">
    <i class="{{ $categoryAll->icon }} icon-bg-{{ $categoryAll->id }}"></i>
    <h4>{{ $categoryAll->name }}</h4>
  </div>
<ul class="category-list" >
    <?php   $j= 0; ?>
    @foreach ( $categoryAll->companies as $singleCompany)
        <li><a href="category.html">{{ $singleCompany->name}} </a></li>
        <?php if (++$j == 4) break; ?>
    @endforeach
</ul>
<?php if (++$i == 8) break; ?>
</code>```

Thank you for your help.

答:
```<code>@foreach ($categoryAll->companies->shuffle() as $singleCompany)
</code>```

Call shuffle on the collection you want to shuffle.

Side Notes:

We have a $loop var in foreach loops in blade that has iteration count and things like that so you dont have to create increment your own counter.

If you only want a certain amount, only take that many.

```<code>@foreach ($categoriesAll->take(8) as $categoryAll)
...
   @foreach ($categoryAll->companies->shuffle()->take(4) as $singleCompany)
</code>```

Body:
I have 2 Models(Category and Company) with relationship between them. I want to show random Companies. How to use inRandomOrder/shuffle() in subquery.

I tried this. But it shuffle Category, but not Companies. I need opposite.

$categoriesAll = \App\Category::all()->shuffle();

My view looks like this:

@foreach ($categoriesAll as $categoryAll)

    icon }} icon-bg-{{ $categoryAll->id }}">

{{ $categoryAll->name }}

    <?php   $j= 0; ?>
    @foreach ( $categoryAll->companies as $singleCompany)

{{ $singleCompany->name}}

        <?php if (++$j == 4) break; ?>
    @endforeach

<?php if (++$i == 8) break; ?>

Thank you for your help.

Body:
@foreach ($categoryAll->companies->shuffle() as $singleCompany)

Call shuffle on the collection you want to shuffle.

Side Notes:

We have a $loop var in foreach loops in blade that has iteration count and things like that so you dont have to create increment your own counter.

If you only want a certain amount, only take that many.

@foreach ($categoriesAll->take(8) as $categoryAll)
...
   @foreach ($categoryAll->companies->shuffle()->take(4) as $singleCompany)


问:
Query nested object in Firestore REST API
I'm stuck with querying Firestore REST API. I can figure out how to filter by a regular key but I can't figure out how to query by nested object key.

Basically, in the browser client, I can do

```<code>firestore.collection("channels")
   .where("members.[memberID]", "==", true)
   .get()
</code>```

However, when I try to do the same in the REST API, it said Invalid Argument. I was trying to do

```<code>{
 "structuredQuery": {
  "where": {
   "fieldFilter": {
    "field": {
     "fieldPath": "members.[memberID]"
    },
    "op": "EQUAL",
    "value": {
       booleanValue: "true"
    }
   }
  },
  "from": [
   {
    "collectionId": "channels"
   }
  ]
 }
}
</code>```

but it gives me "Invalid Argument" error on fieldPath. Does anybody know how to query Firestore REST API based on nested object?

Thank you!

答:
I asked for Firebase support and they said special characters in fieldPath such as "-" in my case can be escaped using back tick or back slash. It is mentioned in the documentation. In my case, I'll need to do

```<code>members.`[memberID]`
</code>```

I hope this is helpful for you guys.

Body:
I'm stuck with querying Firestore REST API. I can figure out how to filter by a regular key but I can't figure out how to query by nested object key.

Basically, in the browser client, I can do

firestore.collection("channels")
   .where("members.[memberID]", "==", true)
   .get()

However, when I try to do the same in the REST API, it said Invalid Argument. I was trying to do

{
 "structuredQuery": {
  "where": {
   "fieldFilter": {
    "field": {
     "fieldPath": "members.[memberID]"
    },
    "op": "EQUAL",
    "value": {
       booleanValue: "true"
    }
   }
  },
  "from": [
   {
    "collectionId": "channels"
   }
  ]
 }
}

but it gives me "Invalid Argument" error on fieldPath. Does anybody know how to query Firestore REST API based on nested object?

Thank you!

Body:
I asked for Firebase support and they said special characters in fieldPath such as "-" in my case can be escaped using back tick or back slash. It is mentioned in the documentation. In my case, I'll need to do

members.`[memberID]`

I hope this is helpful for you guys.


问:
How to get the content of this html code in selenium
How to get the value "https://connect.facebook.net..." which is present in the li tag. I tried with the below options but it is returning as NULL string in Selenium.

HTML code as below:

```<code> <ul>
   <li>Script</li>
   <li>https://connect.facebook.net/?v=2.8.1:0</li>
 </ul>
</code>```

Tried code:

```<code>driver.findElement(By.xpath("//*/li[2][contains(@text,'')]")).getText()

driver.findElement(By.xpath("//ul/li[2]")).getText()

driver.findElement(By.xpath("//ul/li[2]")).getAttribute("value")
</code>```

All the above is returning value as 0.

答:
I got that using the below code.

```<code>driver.findElement(By.xpath("//ul/li[2]")).getAttribute("innerText")
</code>```

What are the different values which can be expected or used for .getAttribute Method? It would be of great help if any shares me the details.

Body:
How to get the value "https://connect.facebook.net..." which is present in the li tag. I tried with the below options but it is returning as NULL string in Selenium.

HTML code as below:

Script

https://connect.facebook.net/?v=2.8.1:0

Tried code:

driver.findElement(By.xpath("//*/li[2][contains(@text,'')]")).getText()

driver.findElement(By.xpath("//ul/li[2]")).getText()

driver.findElement(By.xpath("//ul/li[2]")).getAttribute("value")

All the above is returning value as 0.

Body:
I got that using the below code.

driver.findElement(By.xpath("//ul/li[2]")).getAttribute("innerText")

What are the different values which can be expected or used for .getAttribute Method? It would be of great help if any shares me the details.


问:
Ceridian Dayforce HRIS API location
Our company is considering connecting Ceridian Dayforce HR management system with our product.

Now I was asked to estimate required time and effort it would require to do so. The problem is, I can't find documentation source for the API. Dayforce seem to provide an API, for example they have this article that seem to state they support API integration, but data sheet itself is one page size and written in purely non-technical way.

I am wondering: is there any public source of such documentation? If there is none, does this mean that there is no API available or that documentation is only provided to developer once they finish approvement process of some kind?

答:
There is indeed an API.  Integration can be performed using SOAP or REST.

You will need to request from Ceridian that they create a test instance for you.  After this, it's a good idea to ask for assistance in creating a user role for the purposes of accessing web services.  I had some serious pitfalls in this process since it is not reasonable to ask your own HR staff (who likely only use the front end) to know how to do this for you.  Ask Ceridian's support team instead.

I have been working on this for about two weeks.  I have successfully performed GET and PATCH requests (both using Postman and in code) but creating a new employee with POST is not as straightforward as the documentation makes it out to be.  There seem to be many snags along the way and Ceridian is not very cooperative in providing clear explanations when problems occur (they don't really provide any support on these things, and they make this fairly clear in their documentation).  Their support staff are not really development people, so their knowledge in this domain is likely limited as can be expected.

With that said, I can say that the documentation may seem to be detailed, but be aware that the detail ends after the 'happy path' cases are outlined.

Title: Ceridian Dayforce HRIS API location


问:
TSQL - Is it possible to define the sort order?
Is it possible to define a sort order for the returned results?

I would like the sort order to be 'orange' 'apple' 'strawberry' not ascending or descending.

I know ORDER BY can do ASC or DESC but is there a DEFINED('orange', 'apple', 'strawberry') type thing?

This will be running on SQL Server 2000.

答:
Add a key to the table (e.g. fruit_id int identity(1,1) primary key) to preserve the order of insert

```<code>create table fruit(fruit_id int identity(1,1) primary key, name varchar(50))
go

insert into fruit(name) values ('orange')
insert into fruit(name) values ('apple')
insert into fruit(name) values ('strawberry')

select name from fruit
</code>```

result:

```<code>orange
apple
strawberry
</code>```

Body:
Add a key to the table (e.g. fruit_id int identity(1,1) primary key) to preserve the order of insert

create table fruit(fruit_id int identity(1,1) primary key, name varchar(50))
go

insert into fruit(name) values ('orange')
insert into fruit(name) values ('apple')
insert into fruit(name) values ('strawberry')

select name from fruit

result:

orange
apple
strawberry


问:
When can we avoid using a constructor to initialize state?

In the example given on the reactnativeexpress website here, state = {count: 0} is used in place of a constructor to initialize the count variable.

In the official Facebook docs here, they've said

In general, you should initialize state in the constructor, and then call setState when you want to change it.

So I created a constructor to initialize count in the same manner:

```<code>constructor(props) {
  super(props);
  this.state = {count: 0}
}
</code>```

The code seems to work the same way (at least on the surface), so what's the difference between creating a constructor and initializing count as in the example?

答:
This has more to do with ES6 Classes.

```<code>getFullName() {
  return this.props.firstName + this.props.lastName;
}
</code>```

The above function will throw an error saying props is not defined.

```<code>getFullName = () => {
  return this.props.firstName + this.props.lastName;
}
</code>```

The above code will pass the context of this into the function and will work good.

Similarly, your

```<code>state = {count: 0}
</code>```

is executed in the context of the class [using appropriate this ].

The same state needs to be called using this.state within the constructor to bind it to appropriate context.

Body:
In the example given on the reactnativeexpress website here, state = {count: 0} is used in place of a constructor to initialize the count variable.

In the official Facebook docs here, they've said

In general, you should initialize state in the constructor, and then call setState when you want to change it.

So I created a constructor to initialize count in the same manner:

constructor(props) {
  super(props);
  this.state = {count: 0}
}

The code seems to work the same way (at least on the surface), so what's the difference between creating a constructor and initializing count as in the example?

Body:
This has more to do with ES6 Classes.

getFullName() {
  return this.props.firstName + this.props.lastName;
}

The above function will throw an error saying props is not defined.

getFullName = () => {
  return this.props.firstName + this.props.lastName;
}

The above code will pass the context of this into the function and will work good.

Similarly, your

state = {count: 0}

is executed in the context of the class [using appropriate this ].

The same state needs to be called using this.state within the constructor to bind it to appropriate context.


问:
Argument of type '{header:Header;}' is not assignable to parameter of type 'RequestOptionsArgs'
Im Getting following error while trying to pass header in HTTP.POST/GET request Argument of type '{header:Header;}' is not assignable to parameter of type 'RequestOptionsArgs'. Property 'null' is missing in the type  '{header:Header;}'

I have try many solutions but no lock on it.

here my code :

```<code>import { Injectable } from '@angular/core';
import { Response, RequestOptions, Headers, Http, URLSearchParams} from '@angular/http';
import { Observable, Subject } from 'rxjs/Rx';
import {Company} from './companyMaster';
import 'rxjs/add/operator/map';
import "rxjs/Rx";
import 'rxjs/add/operator/toPromise';
import {CommonService} from '../../common.service';
@Injectable()
export class CompanyMasterService {
private GetListActionUrl: string;
private AddEditActionUrl: string;
public headers = new Headers({ 'Content-Type': 'application/json' });
public options = new RequestOptions({ headers: this.headers });
commonService: CommonService;
constructor(private _http: Http) {
    this.commonService = new CommonService();
    this.GetListActionUrl = this.commonService.RootURL + 'Company/GetList';
    this.AddEditActionUrl = this.commonService.RootURL + "Company/AddEdit";
}

private RegenerateData = new Subject<number>();
// Observable string streams
RegenerateData$ = this.RegenerateData.asObservable();

GetList(): Promise<Company[]> {
    return this._http.get(this.GetListActionUrl + "?branchId=" + this.commonService.BranchId)
        .toPromise()
        .then(response => this.extractArray(response))
        .catch();
}

AddEdit(company: Company): any {
    let headers = new Headers({ 'content-type': 'application/json' });
    let body = JSON.stringify({
        'BRANCH_ID': company.BRANCH_ID.toString(),
        'COMPANY_ID': company.COMPANY_ID != null ? company.COMPANY_ID.toString() : null, 'COMPANY_NAME': company.COMPANY_NAME
    });
    let options = new RequestOptions({ headers: headers});

   return this._http.post(this.AddEditActionUrl, body, options)
        .toPromise()
        .then(response => this.extractArray(response))
        .catch();
}

protected extractArray(res: Response, showprogress: boolean = true) {
    let data = res.json();

    return data || [];
}

private getHeaders() {
    // I included these headers because otherwise FireFox
    // will request text/html instead of application/json
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
}
</code>```

}

See above code I have passed header in method AddEdit() but it shows above error i have try many solution like :

Update Package

Imported @angular/http

Tried different way to pass header
Tried this solution

i have attached screenshot showing error in Visual studio IDE. See attachement error screenshot
please reply as soon as possible.

package.json

```<code>{
  "name": "sb-admin-angular4-bootstrap4",
  "version": "1.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --ec=true",
    "build": "ng build --prod",
    "gitbuild": "ng build --prod --base='/start-angular/SB-Admin-BS4-Angular-4/master/dist/'",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.25",
    "@ngx-translate/core": "^6.0.1",
    "@ngx-translate/http-loader": "0.0.3",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "ionicons": "^3.0.0",
    "ng2-charts": "^1.5.0",
    "rxjs": "^5.1.0",
    "typing": "^0.1.9",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "^1.1.3",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-phantomjs-launcher": "^1.0.4",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0",
    "webpack": "^3.0.0"
  }
}
</code>```

答:
The issue you have is here:

```<code>private getHeaders() {
    // I included these headers because otherwise FireFox
    // will request text/html instead of application/json
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
}
</code>```

The implementation of HttpHeaders append()  is:

```<code>append(name: string, value: string|string[]): HttpHeaders {
   return this.clone({name, value, op: 'a'});
 }
</code>```

It returns a clone of your HttpHeaders object. To make your append affect, you need to store it in a variable which is:

```<code>headers = headers.append('Accept', 'application/json');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im Getting following error while trying to pass header in HTTP.POST/GET request Argument of type '{header:Header;}' is not assignable to parameter of type 'RequestOptionsArgs'. Property 'null' is missing in the type  '{header:Header;}'

I have try many solutions but no lock on it.

here my code :

import { Injectable } from '@angular/core';
import { Response, RequestOptions, Headers, Http, URLSearchParams} from '@angular/http';
import { Observable, Subject } from 'rxjs/Rx';
import {Company} from './companyMaster';
import 'rxjs/add/operator/map';
import "rxjs/Rx";
import 'rxjs/add/operator/toPromise';
import {CommonService} from '../../common.service';
@Injectable()
export class CompanyMasterService {
private GetListActionUrl: string;
private AddEditActionUrl: string;
public headers = new Headers({ 'Content-Type': 'application/json' });
public options = new RequestOptions({ headers: this.headers });
commonService: CommonService;
constructor(private _http: Http) {
    this.commonService = new CommonService();
    this.GetListActionUrl = this.commonService.RootURL + 'Company/GetList';
    this.AddEditActionUrl = this.commonService.RootURL + "Company/AddEdit";
}

private RegenerateData = new Subject<number>();
// Observable string streams
RegenerateData$ = this.RegenerateData.asObservable();

GetList(): Promise<Company[]> {
    return this._http.get(this.GetListActionUrl + "?branchId=" + this.commonService.BranchId)
        .toPromise()
        .then(response => this.extractArray(response))
        .catch();
}

AddEdit(company: Company): any {
    let headers = new Headers({ 'content-type': 'application/json' });
    let body = JSON.stringify({
        'BRANCH_ID': company.BRANCH_ID.toString(),
        'COMPANY_ID': company.COMPANY_ID != null ? company.COMPANY_ID.toString() : null, 'COMPANY_NAME': company.COMPANY_NAME
    });
    let options = new RequestOptions({ headers: headers});

   return this._http.post(this.AddEditActionUrl, body, options)
        .toPromise()
        .then(response => this.extractArray(response))
        .catch();
}

protected extractArray(res: Response, showprogress: boolean = true) {
    let data = res.json();

    return data || [];
}

private getHeaders() {
    // I included these headers because otherwise FireFox
    // will request text/html instead of application/json
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
}

}

See above code I have passed header in method AddEdit() but it shows above error i have try many solution like :

Update Package

Imported @angular/http

Tried different way to pass header
Tried this solution

i have attached screenshot showing error in Visual studio IDE. See attachement error screenshot
please reply as soon as possible.

package.json

{
  "name": "sb-admin-angular4-bootstrap4",
  "version": "1.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --ec=true",
    "build": "ng build --prod",
    "gitbuild": "ng build --prod --base='/start-angular/SB-Admin-BS4-Angular-4/master/dist/'",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.25",
    "@ngx-translate/core": "^6.0.1",
    "@ngx-translate/http-loader": "0.0.3",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "ionicons": "^3.0.0",
    "ng2-charts": "^1.5.0",
    "rxjs": "^5.1.0",
    "typing": "^0.1.9",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "^1.1.3",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-phantomjs-launcher": "^1.0.4",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0",
    "webpack": "^3.0.0"
  }
}

Body:
The issue you have is here:

private getHeaders() {
    // I included these headers because otherwise FireFox
    // will request text/html instead of application/json
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
}

The implementation of HttpHeaders append()  is:

append(name: string, value: string|string[]): HttpHeaders {
   return this.clone({name, value, op: 'a'});
 }

It returns a clone of your HttpHeaders object. To make your append affect, you need to store it in a variable which is:

headers = headers.append('Accept', 'application/json');


问:
Looping through nested arrays and converting to objects
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

```<code>var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]
</code>```

AFTER:

```<code>[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]
</code>```

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));```

Thanks in advance.

答:
Others have pointed out how the use of the map array function can simplify your task and those are good solutions (much better than counting loops), but they don't address the question you actually asked.

Your code actually works just fine, you just didn't extract all the data that was available to you. You only got the first and last name. By adding two more lines you can get the rest of the data. Also, and the second loop isn't even necessary (it's not hurting you, but it doesn't actually help because you never use the x counter anywhere).

var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {

          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];

            // Now you have to get the next two array elements as well:
            newObject[employeeData[i][y+1][0]] = employeeData[i][y+1][1];
            newObject[employeeData[i][y+2][0]] = employeeData[i][y+2][1];
          }

        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));```

Body:
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

AFTER:

[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));

Thanks in advance.


问:
How can I see the full error or warning in Xcode?
No matter how large I make the window, this is all I can see of warnings:

How can I see the full text of the warning at the place it appears?

I could hover the mouse over the warning as it appears in the left pane and, after waiting long enough, a tooltip appears with the full text, but I find this very awkward... Is this the only way?

答: In Xcode 9.2 (at least), you can single click on the error / warning icon in the tooltip and it will expand.


问:
Linq returns foreign key referenced data
I have a simple db with two tables employee and employeedetails.

employee has foreignkey empdetailsid that points to the table employeedetails

My simple linq query to return employee

```<code>var employeeList = from employee in objectcontext.employees select employee;
return employeeList.ToList();
</code>```

also returns employeedetails and all its contained fields which I do not need.
I am using Entity Framework 4.0. Is there a way to avoid getting all the unnecessary data.
I could go with defining a model class that just has the employee table fields and could load into that but I was wondering if there was a simpler way. I am using a mysql database.

答: I haven't used ef 4, but most orm's tend to use a concept called lazy loading.  The data in the related employee details is only retrieved when a call is made to that object. when you look at the object in your debugger the data for a specific employee details will be retrieved when you click on the object.  To get a better idea of what data is being retrieved you will need to run a profiler against the database to trap the sql queries being made.  I don't know if mysql has a built in profiler like sql server.  If not check out nhprof.  </p>

Body:
I have a simple db with two tables employee and employeedetails.

employee has foreignkey empdetailsid that points to the table employeedetails

My simple linq query to return employee

var employeeList = from employee in objectcontext.employees select employee;
return employeeList.ToList();

also returns employeedetails and all its contained fields which I do not need.
I am using Entity Framework 4.0. Is there a way to avoid getting all the unnecessary data.
I could go with defining a model class that just has the employee table fields and could load into that but I was wondering if there was a simpler way. I am using a mysql database.


问:
SSSD - LDAP group based access - ldap schema rfc2307bis
I'm having trouble setting up access_provider = ldap in SSSD. Problem is with the ldap_access_filter.

LDAP side looks like this:
USER:

```<code># username, users, location, dc1.dc2
dn: uid=username,ou=users,l=location,dc=dc1,dc=dc2
shadowExpire: 17507
shadowLastChange: 17494
shadowMin: 0
shadowMax: 0
shadowInactive: 0
shadowFlag: 0
shadowWarning: 0
loginShell: /bin/bash
homeDirectory: /home/username
gidNumber: 2341
uidNumber: 6432
uid: username
mail: username@company.com
sn: Name
objectClass: organizationalPerson
objectClass: person
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
objectClass: shadowAccount
cn: User Name
title: User Title
mobile: xxxxxxxxx
manager: uid=usermanager,ou=users,l=location,dc=dc1,dc=dc2
</code>```

GROUP:

```<code># allowed-group, groups, location, dc1.dc2
dn: cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc2
cn: allowed-group
objectClass: top
objectClass: groupOfUniqueNames
objectClass: posixGroup
gidNumber: 2140
description: Group description
uniqueMember: uid=username,ou=users,l=location,dc=dc1,dc=dc2
</code>```

I've tried to set ldap_access_filter = uniqueMember=cn=allowed-group but it will always deny access with following message:

```<code>(Tue Dec  5 18:22:44 2017) [sssd[be[LDAP]]] [sdap_get_generic_ext_step] (0x0400): calling ldap_search_ext with [(&(uid=username)(objectclass=posixAccount)(uniqueMember=cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc1))][uid=username,ou=users,l=location,dc=dc1,dc=dc2].
(Tue Dec  5 18:22:44 2017) [sssd[be[LDAP]]] [sdap_access_filter_done] (0x0100): User [username@ldap] was not found with the specified filter. Denying access.
</code>```

sssd.conf

```<code>[sssd]
config_file_version = 2
services = nss, pam
domains = LDAP
[nss]
filter_users = root,ldap,named,avahi,haldaemon,dbus,radiusd,news,nscd,nagios
[pam]
[domain/LDAP]
id_provider = ldap
auth_provider = ldap
access_provider = ldap
ldap_uri = ldap://uri
ldap_schema = rfc2307bis
ldap_search_base = l=location,dc=dc1,dc=dc2
ldap_group_object_class = groupOfUniqueNames
ldap_group_member = uniqueMember
ldap_access_order = filter, expire
ldap_account_expire_policy = shadow
ldap_access_filter = uniqueMember=cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc1
cache_credentials = true
enumerate = true
debug_level = 8
ldap_tls_reqcert = demand
ldap_tls_cacertdir = /etc/openldap/cacerts
ldap_tls_cacert = /etc/pki/tls/cacert.pem
</code>```

is anyone able to point how to create correct ldap_access_filter for that ldap schema ?

答:
You need sssd to be looking at the user's attributes, not the group's list of users, e.g.

```<code>ldap_access_filter = memberOf=cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc1
</code>```

To get that memberOf attribute into your users' records you need to use the memberof overlay (assuming your LDAP server is running OpenLDAP).

Body:
I'm having trouble setting up access_provider = ldap in SSSD. Problem is with the ldap_access_filter.

LDAP side looks like this:
USER:

# username, users, location, dc1.dc2
dn: uid=username,ou=users,l=location,dc=dc1,dc=dc2
shadowExpire: 17507
shadowLastChange: 17494
shadowMin: 0
shadowMax: 0
shadowInactive: 0
shadowFlag: 0
shadowWarning: 0
loginShell: /bin/bash
homeDirectory: /home/username
gidNumber: 2341
uidNumber: 6432
uid: username
mail: username@company.com
sn: Name
objectClass: organizationalPerson
objectClass: person
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
objectClass: shadowAccount
cn: User Name
title: User Title
mobile: xxxxxxxxx
manager: uid=usermanager,ou=users,l=location,dc=dc1,dc=dc2

GROUP:

# allowed-group, groups, location, dc1.dc2
dn: cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc2
cn: allowed-group
objectClass: top
objectClass: groupOfUniqueNames
objectClass: posixGroup
gidNumber: 2140
description: Group description
uniqueMember: uid=username,ou=users,l=location,dc=dc1,dc=dc2

I've tried to set ldap_access_filter = uniqueMember=cn=allowed-group but it will always deny access with following message:

(Tue Dec  5 18:22:44 2017) [sssd[be[LDAP]]] [sdap_get_generic_ext_step] (0x0400): calling ldap_search_ext with [(&(uid=username)(objectclass=posixAccount)(uniqueMember=cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc1))][uid=username,ou=users,l=location,dc=dc1,dc=dc2].
(Tue Dec  5 18:22:44 2017) [sssd[be[LDAP]]] [sdap_access_filter_done] (0x0100): User [username@ldap] was not found with the specified filter. Denying access.

sssd.conf

[sssd]
config_file_version = 2
services = nss, pam
domains = LDAP
[nss]
filter_users = root,ldap,named,avahi,haldaemon,dbus,radiusd,news,nscd,nagios
[pam]
[domain/LDAP]
id_provider = ldap
auth_provider = ldap
access_provider = ldap
ldap_uri = ldap://uri
ldap_schema = rfc2307bis
ldap_search_base = l=location,dc=dc1,dc=dc2
ldap_group_object_class = groupOfUniqueNames
ldap_group_member = uniqueMember
ldap_access_order = filter, expire
ldap_account_expire_policy = shadow
ldap_access_filter = uniqueMember=cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc1
cache_credentials = true
enumerate = true
debug_level = 8
ldap_tls_reqcert = demand
ldap_tls_cacertdir = /etc/openldap/cacerts
ldap_tls_cacert = /etc/pki/tls/cacert.pem

is anyone able to point how to create correct ldap_access_filter for that ldap schema ?

Body:
You need sssd to be looking at the user's attributes, not the group's list of users, e.g.

ldap_access_filter = memberOf=cn=allowed-group,ou=groups,l=location,dc=dc1,dc=dc1

To get that memberOf attribute into your users' records you need to use the memberof overlay (assuming your LDAP server is running OpenLDAP).


问:
How can I convert a stack trace to a string?
What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

答:
Warning: This may be a bit off topic, but oh well... ;)

I don't know what the original posters reason was for wanting the stack trace as string in the first place. When the stack trace should end up in an SLF4J/Logback LOG, but no exception was or should be thrown here's what I do:

```<code>public void remove(List<String> ids) {
    if(ids == null || ids.isEmpty()) {
        LOG.warn(
            "An empty list (or null) was passed to {}.remove(List). " +
            "Clearly, this call is unneccessary, the caller should " +
            "avoid making it. A stacktrace follows.",
            getClass().getName(),
            new Throwable ("Stacktrace")
        );

        return;
    }

    // actual work, remove stuff
}
</code>```

I like it because it does not require an external library (other than your logging backend, which will be in place most of the time anyway, of course).

Body:
Warning: This may be a bit off topic, but oh well... ;)

I don't know what the original posters reason was for wanting the stack trace as string in the first place. When the stack trace should end up in an SLF4J/Logback LOG, but no exception was or should be thrown here's what I do:

public void remove(List<String> ids) {
    if(ids == null || ids.isEmpty()) {
        LOG.warn(
            "An empty list (or null) was passed to {}.remove(List). " +
            "Clearly, this call is unneccessary, the caller should " +
            "avoid making it. A stacktrace follows.",
            getClass().getName(),
            new Throwable ("Stacktrace")
        );

        return;
    }

    // actual work, remove stuff
}

I like it because it does not require an external library (other than your logging backend, which will be in place most of the time anyway, of course).


问:
jquery dialog buttons different functions based on class
I have a table row that when clicked opens a dialog.  The class of the table row is either "associated" or "unassociated".  I am trying to create the buttons for the dialog, but they will be different based on the class of clicked row.

```<code>  $('#opps tr').click(function(){
         var thisClass = $(this).attr('class');
         $('#oppData').dialog({
                            width: dWidth,
                            height:dHeight,
                            modal:true,
                            buttons: {
         //if thisClass == unassociated
                     "Submit":function(){ //do stuff }

         // if thisClass == associated
                     "Do Other stuff":function(){}
                           }
    });
 });
</code>```

how can i achieve this?

答:
You can do this with a little code refactoring.  At the heart of the answer is the jQuery function hasClass which will help you determine your buttons properties.  I'm also using the idea that every JSON object is just a property bag and building out myButtons using the property bag syntax.

```<code>$('#opps tr').click(function(){
         var myButtons= {};

         if ($(this).hasClass("associated")) {
            myButtons["Submit"] = function () { ... };
         } else {
            myButtons["Do Other stuff"] = function(){ ... };
         }

         $('#oppData').dialog({
                            width: dWidth,
                            height:dHeight,
                            modal:true,
                            buttons: myButtons
         });
 });
</code>```

Body:
I have a table row that when clicked opens a dialog.  The class of the table row is either "associated" or "unassociated".  I am trying to create the buttons for the dialog, but they will be different based on the class of clicked row.

  $('#opps tr').click(function(){
         var thisClass = $(this).attr('class');
         $('#oppData').dialog({
                            width: dWidth,
                            height:dHeight,
                            modal:true,
                            buttons: {
         //if thisClass == unassociated
                     "Submit":function(){ //do stuff }

         // if thisClass == associated
                     "Do Other stuff":function(){}
                           }
    });
 });

how can i achieve this?

Body:
You can do this with a little code refactoring.  At the heart of the answer is the jQuery function hasClass which will help you determine your buttons properties.  I'm also using the idea that every JSON object is just a property bag and building out myButtons using the property bag syntax.

$('#opps tr').click(function(){
         var myButtons= {};

         if ($(this).hasClass("associated")) {
            myButtons["Submit"] = function () { ... };
         } else {
            myButtons["Do Other stuff"] = function(){ ... };
         }

         $('#oppData').dialog({
                            width: dWidth,
                            height:dHeight,
                            modal:true,
                            buttons: myButtons
         });
 });


问:
How to add a custom querystring to a single WordPress nav menu item?
I'm trying to add a querystring into a specific menu item in a WordPress menu.  I need to read a cookie, let's say sessionID, and pass that key/value pair in a query string on a single link in my nav menu. I could try this via JS/jQuery but would need to do it via PHP. I've search but found nothing int he forums that would help.

Using WordPress 3.5

答:
Try this:</p>

```<code>function wpse_14405784( $items, $menu = 'your_menu_slug', $args ) {

    foreach( $items as $item ) {

        if ( $item->post_title == 'your_link_title'  {

            $item->url = add_query_arg( 'your_key', 'your_value', $item->url );
        }
    }
    return $items;
}
add_filter( 'wp_get_nav_menu_items','wpse_14405784', 11, 3 );
</code>```

Body:
Try this:

function wpse_14405784( $items, $menu = 'your_menu_slug', $args ) {

    foreach( $items as $item ) {

        if ( $item->post_title == 'your_link_title'  {

            $item->url = add_query_arg( 'your_key', 'your_value', $item->url );
        }
    }
    return $items;
}
add_filter( 'wp_get_nav_menu_items','wpse_14405784', 11, 3 );