问:
How to filter feature using OpenLayer and WFS?
I'm able to extract data from geojson file (produced from GeoServer WFS layer type) and display it on browser using OpenLayer. But I'm facing problem when I only want to display the data with certain features aka filtering.

My JSON filename -> gpr.geojson

GeoServer layername -> visualization:GPR

Attribute filter -> branchCode = N01821 and routeCode = 0650

I followed filtering tutorial from https://www.giserdqy.com/wp-content/guids/ol-v4.6.5/examples/vector-wfs-getfeature.html and I also have tried using CQL_FILTER but no luck at all

Below is my code and the filtering doesn't work

```<code>var mymap = new ol.Map({
    target: 'mapid',
    layers: [
          new ol.layer.Tile({
            source: new ol.source.XYZ({
                //Vworld Tile 변경
                url: 'http://xdworld.vworld.kr:8080/2d/Base/201802/{z}/{x}/{y}.png'
            })
          })
    ],
    view: new ol.View({
        center: ol.proj.transform([128.1591, 36.4109], 'EPSG:4326', 'EPSG:3857'),
        zoom: 8,
        minZoom: 6,
        maxZoom: 19
    }),
    logo:false
});

var vectorSource = new ol.source.Vector({
    url: './data/GPR.geojson,
    format: new ol.format.GeoJSON()
})

var layer = new ol.layer.VectorImage({
    source: vectorSource,
    visible: true,
})

// generate a GetFeature request
var featureRequest = new ol.format.WFS().writeGetFeature({
    srsName: 'EPSG:3857',
    featureNS: 'visualization',
    featurePrefix: 'osm',
    featureTypes: ['GPR'],
    outputFormat: 'application/json',
    filter: ol.format.filter.and(
        ol.format.filter.like('branchCode', 'N01821'),
        ol.format.filter.equalTo('routeCode', '0650')
    )
});

// then post the request and add the received features to a layer
fetch('http://localhost:8080/geoserver/visualization/wfs', {
    method: 'POST',
    body: new XMLSerializer().serializeToString(featureRequest)
}).then(function (response) {
    return response.json();
}).then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(json);
    vectorSource.addFeatures(features);
    mymap.getView().fit(vectorSource.getExtent());
});
</code>```

Using Leaflet, WMS and CQL Filter is very simple as below. How to do it using OpenLayer and WFS?

```<code>var wmsLayer= L.tileLayer.wms("http://localhost:8080/geoserver/visualization/wms", {
layers: 'visualization:GPR',
format: 'image/png',
transparent: true,
CQL_FILTER:  "branchCode='N01821'"
</code>```

答:
You can still use a request and CQL_FILTER in OL just like your leaflet example, something like this,

```<code>$.ajax({
    method: 'POST',
    url: 'http://localhost:8080/geoserver/visualization/wfs',
    data: {
        "service": "WFS",
        "request": "GetFeature",
        "typename": "visualization:GPR",
        "outputFormat": "application/json",
        "srsname": "EPSG:3857",
        "maxFeatures": 50,
        "CQL_FILTER": "branchCode='N01821'"
    },
    success: function (response) {
        var features = new ol.format.GeoJSON().readFeatures(response);
        vectorSource.addFeatures(features);
        mymap.getView().fit(vectorSource.getExtent());
    },
    fail: function (jqXHR, textStatus) {
        console.log("Request failed: " + textStatus);
    }
});
</code>```

If you prefer to use fetch, I think this should work,

```<code>let featureRequest  = {
    "service": "WFS",
    "request": "GetFeature",
    "typename": "visualization:GPR",
    "outputFormat": "application/json",
    "srsname": "EPSG:3857",
    "maxFeatures": 50,
    "CQL_FILTER": "branchCode='N01821'"
};
fetch('http://localhost:8080/geoserver/visualization/wfs', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(featureRequest)
}).then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(reponse);
    vectorSource.addFeatures(features);
    mymap.getView().fit(vectorSource.getExtent());
});
</code>```

Body:
I'm able to extract data from geojson file (produced from GeoServer WFS layer type) and display it on browser using OpenLayer. But I'm facing problem when I only want to display the data with certain features aka filtering.

My JSON filename -> gpr.geojson

GeoServer layername -> visualization:GPR

Attribute filter -> branchCode = N01821 and routeCode = 0650

I followed filtering tutorial from https://www.giserdqy.com/wp-content/guids/ol-v4.6.5/examples/vector-wfs-getfeature.html and I also have tried using CQL_FILTER but no luck at all

Below is my code and the filtering doesn't work

var mymap = new ol.Map({
    target: 'mapid',
    layers: [
          new ol.layer.Tile({
            source: new ol.source.XYZ({
                //Vworld Tile 변경
                url: 'http://xdworld.vworld.kr:8080/2d/Base/201802/{z}/{x}/{y}.png'
            })
          })
    ],
    view: new ol.View({
        center: ol.proj.transform([128.1591, 36.4109], 'EPSG:4326', 'EPSG:3857'),
        zoom: 8,
        minZoom: 6,
        maxZoom: 19
    }),
    logo:false
});

var vectorSource = new ol.source.Vector({
    url: './data/GPR.geojson,
    format: new ol.format.GeoJSON()
})

var layer = new ol.layer.VectorImage({
    source: vectorSource,
    visible: true,
})

// generate a GetFeature request
var featureRequest = new ol.format.WFS().writeGetFeature({
    srsName: 'EPSG:3857',
    featureNS: 'visualization',
    featurePrefix: 'osm',
    featureTypes: ['GPR'],
    outputFormat: 'application/json',
    filter: ol.format.filter.and(
        ol.format.filter.like('branchCode', 'N01821'),
        ol.format.filter.equalTo('routeCode', '0650')
    )
});

// then post the request and add the received features to a layer
fetch('http://localhost:8080/geoserver/visualization/wfs', {
    method: 'POST',
    body: new XMLSerializer().serializeToString(featureRequest)
}).then(function (response) {
    return response.json();
}).then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(json);
    vectorSource.addFeatures(features);
    mymap.getView().fit(vectorSource.getExtent());
});

Using Leaflet, WMS and CQL Filter is very simple as below. How to do it using OpenLayer and WFS?

var wmsLayer= L.tileLayer.wms("http://localhost:8080/geoserver/visualization/wms", {
layers: 'visualization:GPR',
format: 'image/png',
transparent: true,
CQL_FILTER:  "branchCode='N01821'"

Body:
You can still use a request and CQL_FILTER in OL just like your leaflet example, something like this,

$.ajax({
    method: 'POST',
    url: 'http://localhost:8080/geoserver/visualization/wfs',
    data: {
        "service": "WFS",
        "request": "GetFeature",
        "typename": "visualization:GPR",
        "outputFormat": "application/json",
        "srsname": "EPSG:3857",
        "maxFeatures": 50,
        "CQL_FILTER": "branchCode='N01821'"
    },
    success: function (response) {
        var features = new ol.format.GeoJSON().readFeatures(response);
        vectorSource.addFeatures(features);
        mymap.getView().fit(vectorSource.getExtent());
    },
    fail: function (jqXHR, textStatus) {
        console.log("Request failed: " + textStatus);
    }
});

If you prefer to use fetch, I think this should work,

let featureRequest  = {
    "service": "WFS",
    "request": "GetFeature",
    "typename": "visualization:GPR",
    "outputFormat": "application/json",
    "srsname": "EPSG:3857",
    "maxFeatures": 50,
    "CQL_FILTER": "branchCode='N01821'"
};
fetch('http://localhost:8080/geoserver/visualization/wfs', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(featureRequest)
}).then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(reponse);
    vectorSource.addFeatures(features);
    mymap.getView().fit(vectorSource.getExtent());
});


来源: stackexchange

问:
Since what Android version do I need to activate GPS to know WiFi SSID?
I'm developing and App that must connect to an specific SSID but some new phones needs to have the GPS active in order to let the App read the WiFI SSID.

API 27 maybe?

答: Since Android 8 - api level 26 - (https://developer.android.com/guide/topics/connectivity/wifi-scan)</p>

ContentLicense: CC BY-SA 4.0


问:
How to get a total number of occurrences in an IF statement
After looking at a bunch of the other questions similar to mine, I found one that partially works but not exactly as I need it to. I am trying to get a total for the number of times an occurrence is found in my IF statement. The code I have tried is below:

```<code>for i in data['resources']:
    url = server+ "/api/3/assets/" +str(i)
    response = requests.request("GET", url, headers=headers, verify=False)
    data = response.json()
    Total = 0
    if data['red'] and data['blue'] > 0:
        Total += 1
        print('Total:', Total)
</code>```

Rather than giving me an output like:

```<code>Total: 3
</code>```

I get this:

```<code>Total: 1
Total: 1
Total: 1
</code>```

答:
Total=0 inside the for loop and getting reset for each iteration. So you have to put Total=0 outside the for loop. And also if you want it to print only once then put the Print statement outside and at the end of the for loop

I am sure this should solve your problem

Body:
After looking at a bunch of the other questions similar to mine, I found one that partially works but not exactly as I need it to. I am trying to get a total for the number of times an occurrence is found in my IF statement. The code I have tried is below:

for i in data['resources']:
    url = server+ "/api/3/assets/" +str(i)
    response = requests.request("GET", url, headers=headers, verify=False)
    data = response.json()
    Total = 0
    if data['red'] and data['blue'] > 0:
        Total += 1
        print('Total:', Total)

Rather than giving me an output like:

Total: 3

I get this:

Total: 1
Total: 1
Total: 1


问:
Loading content into Blazor TabControl
I've created a TabControl following this and similar guides:

https://blazor-university.com/templating-components-with-renderfragements/creating-a-tabcontrol/

The relevant code on my test Tabs.razor page is:

```<code><TabControl>
  <TabPage Text="Tab 1">
    <h1>The first tab</h1>
  </TabPage>
  <TabPage Text="Tab 2">
    <h1>The second tab</h1>
  </TabPage>
  <TabPage Text="Tab 3">
    <h1>The third tab</h1>
  </TabPage>
</TabControl>
</code>```

The pages inside the tabs themselves will have a lot more content than just one sentence. All the tabbed examples I've found just have the tab contents like this, flat on the page. Is there some way to make the tab content more modular, possibly having it live in separate files? I'd want it all to load on the page initialization, I'd just like to not have a big monster .razor page with the contents of all the tabs.

I'm not sure if I need nested layouts here or what, or how the rendering would work (I'll need the tab contents to behave like top-level razor pages with functions and submit actions, etc...).

Pretty new to this, obviously, and haven't been able to find an answer. Thanks in advance.

答:
```<code> <TabPage Text="Tab 1">
    <MyFirstTabbedComponent />
  </TabPage>
</code>```

and then develop MyFirstTabbedComponent.razor as a page/component.

enfin, you have already done something similar.

Title: Loading content into Blazor TabControl

Body:
I've created a TabControl following this and similar guides:

https://blazor-university.com/templating-components-with-renderfragements/creating-a-tabcontrol/

The relevant code on my test Tabs.razor page is:

<TabControl>
  <TabPage Text="Tab 1">

The first tab

  </TabPage>
  <TabPage Text="Tab 2">

The second tab

  </TabPage>
  <TabPage Text="Tab 3">

The third tab

  </TabPage>
</TabControl>

The pages inside the tabs themselves will have a lot more content than just one sentence. All the tabbed examples I've found just have the tab contents like this, flat on the page. Is there some way to make the tab content more modular, possibly having it live in separate files? I'd want it all to load on the page initialization, I'd just like to not have a big monster .razor page with the contents of all the tabs.

I'm not sure if I need nested layouts here or what, or how the rendering would work (I'll need the tab contents to behave like top-level razor pages with functions and submit actions, etc...).

Pretty new to this, obviously, and haven't been able to find an answer. Thanks in advance.

Body:
 <TabPage Text="Tab 1">
    <MyFirstTabbedComponent />
  </TabPage>

and then develop MyFirstTabbedComponent.razor as a page/component.

enfin, you have already done something similar.


问:
Using Nodejs to Serve an MP4 Video File
I am trying to serve a ~52MB mp4 video file from a nodejs server. Attached below is a screenshot of the code used to serve the file.
I have an object of mime types for static file calls which contains the mime type for mp4.

var mimeTypes = {
  html: 'text/html; charset=utf-8',
  jpeg: 'image/jpeg',
  jpg: 'image/jpeg',
  png: 'image/png',
  js: 'text/javascript',
  css: 'text/css',
  mp4: 'video/mp4'
};

However, when I try to navigate to the page in chrome, I get the error:

GET http://localhost:8888/videos/movie.mp4 net::ERR_INCOMPLETE_CHUNKED_ENCODING

Now this same logic (screenshotted above) is used to serve images and css just fine, however it fails miserably when trying to serve the mp4. Looking at the network requests panel in Chrome, I can see that the server responded with a 200 OK status, and served a zero byte file as the video. The range of bytes in the network request also looks suspicious but I don't know enough about HTTP requests to know for sure.

Looking at the stats object (shown below, gotten from fs.lstat), It appears that the file 'knows' how to be split into chunks of 4096 bytes, however I keep getting the incomplete chunked encoding error. I have no antivirus, and tried turning off various settings in Chrome/using another browser but I can't see the video.

{"dev":16777220,"mode":33188,"nlink":1,"uid":501,"gid":20,"rdev":0,"blksize":4096,"ino":1070608,"size":51246445,"blocks":100096,"atime":"2016-06-15T23:06:27.000Z","mtime":"2016-06-15T21:41:00.000Z","ctime":"2016-06-15T21:45:56.000Z"}

Is there a header I am missing? Am I somehow ending the response too early? I'm clueless right now.

答:
This was enough with me. MP4 has native support for strimming (pseudo streaming). It worked very well for watching videos in the browser via streaming.</p>

```<code>res.setHeader('Content-Type', 'video/mp4');

res.status(200).sendFile(full_path, function (err) {
    if (err) { ... } else { ... }
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using Nodejs to Serve an MP4 Video File

Body:
This was enough with me. MP4 has native support for strimming (pseudo streaming). It worked very well for watching videos in the browser via streaming.

res.setHeader('Content-Type', 'video/mp4');

res.status(200).sendFile(full_path, function (err) {
    if (err) { ... } else { ... }
});


问:
How to annotate symbols that they are shared among other projects?
Suppose I have a Go project which act as shared library in another Go project. How do I markup Go symbols (consts, structs, vars) that they are used outside this project?

I guess the underlying problem is that I have a hard time knowing which code uses said symbols.

Please note: This is not about semantic versioning, of which I am very well aware and which I use. I know Semver can help to identify breaking changes.

Instead, this is about finding out if I actually break one of my own projects (compared to: This symbol should be unexported or used outside the package). I am thinking of some sort of annotation which don't exist in Go.

As an aside, IntelliJ doesn't know either and marks those symbols as "Unnecessarily exported". Maybe an IntelliJ-centric solution could suffice.

To illustrate my problem:

package sharedlib

import "time"

// MyFavoriteTimeFormat is a blablabla...
const MyFavoriteTimeFormat = Time.RFC3339
```

<pre class="lang-golang prettyprint-override"><code>package dependingproject

import "github.com/thething/sharedlib"
import "time"

func convertToString(timestamp time.Time) string {
    return timestamp.Format(sharedlib.MyFavoriteTimeFormat)
}
</code>```

When I happily rename MyFavoriteTimeFormate and release it, the code will break in the depending project when it updates the dependency.

答:
Don't export anything until some other package needs it. If another package needs something, then do export, and then you'll know that if something is exported, it is because it is used outside of the package. And do not do breaking changes on exported identifiers. If you really must, then increment major version. Using go modules, that won't break existing other packages, they will continue to use the old version.

If your module is broken down into multiple packages (because it is "big"), and you wish to export something solely for the other packages of your module, then use the internal package concept, so it will still be "unexported" (unimportable) to other modules. For details, see Can I develop a go package in multiple source directories?

Body:
Suppose I have a Go project which act as shared library in another Go project. How do I markup Go symbols (consts, structs, vars) that they are used outside this project?

I guess the underlying problem is that I have a hard time knowing which code uses said symbols.

Please note: This is not about semantic versioning, of which I am very well aware and which I use. I know Semver can help to identify breaking changes.

Instead, this is about finding out if I actually break one of my own projects (compared to: This symbol should be unexported or used outside the package). I am thinking of some sort of annotation which don't exist in Go.

As an aside, IntelliJ doesn't know either and marks those symbols as "Unnecessarily exported". Maybe an IntelliJ-centric solution could suffice.

To illustrate my problem:

package sharedlib

import "time"

// MyFavoriteTimeFormat is a blablabla...
const MyFavoriteTimeFormat = Time.RFC3339

package dependingproject

import "github.com/thething/sharedlib"
import "time"

func convertToString(timestamp time.Time) string {
    return timestamp.Format(sharedlib.MyFavoriteTimeFormat)
}

When I happily rename MyFavoriteTimeFormate and release it, the code will break in the depending project when it updates the dependency.


问:
Action-Reducer Mapping has type error with multiple action types
I asked a question earlier today, based on my attempts to create a mapping between redux-action-types and reducers to handle each of those types, with the requirement that each action type is handled explicitly.

I received a great answer on how to do that, and I can now create such a mapping, but I'm getting an error when I try and use it to create a reducer.

If I have the following code (sorry, it's rather long, but I believe it is a minimal example):

export type IActionReducerMapping<S, A extends IReduxAction<string>> = {
    [K in A['type']]: IReducer<S, Extract>
};

interface IUser {
    id: number;
    name: string;
    age: number;
}

interface IUserState {
    [id: number]: IUser;
}

interface IAddUserAction {
    type: 'ADD_USER';
    payload: IUser;
}

interface ISetUserNameAction {
    type: 'SET_USER_NAME';
    payload: {
        id: IUser['id'];
        name: IUser['name'];
    }
}

type UserAction = IAddUserAction | ISetUserNameAction;

const mapping: IActionReducerMapping<IUserState, UserAction> = {
    'ADD_USER': (state, action) => ({
        ...state,
        [action.payload.id]: action.payload,
    }),

    'SET_USER_NAME': (state, action) => ({
        ...state,
        [action.payload.id]: {
            ...state[action.payload.id],
            name: action.payload.name,
        }
    }),
};

const userReducer = (state: IUserState, action: UserAction) => mapping[action.type](state, action);
```

<p>I get the following error:</p>

<blockquote>
  <p>Argument of type 'UserAction' is not assignable to parameter of type 'IAddUserAction & ISetUserNameAction'.
    Type 'IAddUserAction' is not assignable to type 'IAddUserAction & ISetUserNameAction'.
      Type 'IAddUserAction' is not assignable to type 'ISetUserNameAction'.
        Types of property 'type' are incompatible.
          Type '"ADD_USER"' is not assignable to type '"SET_USER_NAME"'.ts(2345)</p>
</blockquote>

<p>I can't see where I'm going wrong with the typing of these, could anyone point out where I've gone wrong?</p>

<p>Here's the playground link.</p>

<hr>

<p>Edit:</p>

<p>The following works:</p>

<pre class="lang-js prettyprint-override"><code>const userReducer = (state: IUserState, action: ISetUserNameAction | IAddUserAction) =>  {
    switch (action.type) {
        case 'ADD_USER':
            return mapping[action.type](state, action);
        case 'SET_USER_NAME':
            return mapping[action.type](state, action);
    }
}
</code>```

Presumably because at this point the compiler is confident that it can know that the type of action and reducer will work nicely together. Still a mystery how I infer this automatically.

答:
I was able to solve this by creating a separate function to transform a mapping to a reducer:

export const reducerOf = <S, A extends IReduxAction<string>>(mapping: IActionReducerMapping<S, A>) =>
    (state: S, action: A): S =>
        mapping[action.type](state, action);
```

<p>Now I can simply call it as:</p>

<pre class="lang-js prettyprint-override"><code>const userReducer = reducerOf(mapping);
</code>```

Body:
I asked a question earlier today, based on my attempts to create a mapping between redux-action-types and reducers to handle each of those types, with the requirement that each action type is handled explicitly.

I received a great answer on how to do that, and I can now create such a mapping, but I'm getting an error when I try and use it to create a reducer.

If I have the following code (sorry, it's rather long, but I believe it is a minimal example):

export type IActionReducerMapping<S, A extends IReduxAction<string>> = {
    [K in A['type']]: IReducer<S, Extract>
};

interface IUser {
    id: number;
    name: string;
    age: number;
}

interface IUserState {
    [id: number]: IUser;
}

interface IAddUserAction {
    type: 'ADD_USER';
    payload: IUser;
}

interface ISetUserNameAction {
    type: 'SET_USER_NAME';
    payload: {
        id: IUser['id'];
        name: IUser['name'];
    }
}

type UserAction = IAddUserAction | ISetUserNameAction;

const mapping: IActionReducerMapping<IUserState, UserAction> = {
    'ADD_USER': (state, action) => ({
        ...state,
        [action.payload.id]: action.payload,
    }),

    'SET_USER_NAME': (state, action) => ({
        ...state,
        [action.payload.id]: {
            ...state[action.payload.id],
            name: action.payload.name,
        }
    }),
};

const userReducer = (state: IUserState, action: UserAction) => mapping[action.type](state, action);

I get the following error:

Argument of type 'UserAction' is not assignable to parameter of type 'IAddUserAction & ISetUserNameAction'.
    Type 'IAddUserAction' is not assignable to type 'IAddUserAction & ISetUserNameAction'.
      Type 'IAddUserAction' is not assignable to type 'ISetUserNameAction'.
        Types of property 'type' are incompatible.
          Type '"ADD_USER"' is not assignable to type '"SET_USER_NAME"'.ts(2345)

I can't see where I'm going wrong with the typing of these, could anyone point out where I've gone wrong?

<a href="https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgSQCVgATAVxAEFsYEIkAeAFQD44BvAKDh7hgE8wwAFxwmAbk4BfTp2SoMOPEVJlcUBgGUANHEpsuvOAAoAzjEypROuDlr1RlAJTXJMzqEiw+g5dXtIxOTqALKYYGDIAOZaupRwoKhIJKYEQRT+dIzmUNEsbAC8HNy8ANoA0ohIeqUA5AJCtQC6TaIqwWixcACiIDBQdgyUuuw+QqKVUvnSkrLyaFi4BACqpmjFRggkokhkALYARmiSRkiYeyJwOdEnvJhRl7uHx9JzKAtKK2tQmhaoG2Utjt9kcoK0vi93PNFEt8JQSCRVmhMvQATwGpdapQACLYgD6y003UItVuPDAmH4ABsIJhthCoG43gpFspNMAYEioAA5c7AFHVQy8DGiWpEpgEomEPHcyghbqkkrkyk0umiIVGHhAhl1LbNMmas4XNpcupG4D6pVwGTuDFwLkCuBFOEIh00LJwAA+BHZnO+vIuAtm2Ho5jge3CkSQUTaAvSoUj0QY+C5v0swF0boChTRcCxuMlxNqojMfwztnd9CcTrYxg1moAdE3zOntFajKU7FkGxTqbSSA2tuCu-Qeyr+22jFInG2rWLuhLCcSZXKFSWW6hdCOkNWCrX60Ymw2Nxn22Vt2O+3TByRwQfNTwjyfO5WkJfVQOh5OH4a+aIL72H4Nua34PjIU4zjMsghkgYZkN88brEUpbpia3xppuFYBKIWZZLubARhE0QvgEDYYk0KGYduTjiEAA" rel="nofollow noreferrer">Here's the playground link.

Edit:

The following works:

const userReducer = (state: IUserState, action: ISetUserNameAction | IAddUserAction) =>  {
    switch (action.type) {
        case 'ADD_USER':
            return mapping[action.type](state, action);
        case 'SET_USER_NAME':
            return mapping[action.type](state, action);
    }
}

Presumably because at this point the compiler is confident that it can know that the type of action and reducer will work nicely together. Still a mystery how I infer this automatically.

Body:
I was able to solve this by creating a separate function to transform a mapping to a reducer:

export const reducerOf = <S, A extends IReduxAction<string>>(mapping: IActionReducerMapping<S, A>) =>
    (state: S, action: A): S =>
        mapping[action.type](state, action);

Now I can simply call it as:

const userReducer = reducerOf(mapping);


问:
regex : match dot with no space after
I would like to search for all punctuations in a string except /, #, $ and dot with no space after (.net for example)

I have done this so far.

```<code>?!['\/#$])\p{P}
</code>```

Now I need to handle the dot with no space after.

If anyone has an idea...

I am using Java.

For example I need to replace all punctuations by "" (empty character)  except for dot with no space after:

.net, asp.net hello. world, c#

becomes

.net asp.net hello world c#

答:
You may add an alternative into your negative lookahead:

```<code>(?![/#$]|\.(?!\s))\p{P}
        ^^^^^^^^^
</code>```

See the regex demo.

Details

(?![/#$]|\.(?!\s)) - fail the match if immediately to the right, there is /, # or $, or a . not followed with a whitespace char

\p{P} - any punctuation proper char

Title: regex : match dot with no space after

Body:
I would like to search for all punctuations in a string except /, #, $ and dot with no space after (.net for example)

I have done this so far.

?!['\/#$])\p{P}

Now I need to handle the dot with no space after.

If anyone has an idea...

I am using Java.

For example I need to replace all punctuations by "" (empty character)  except for dot with no space after:

.net, asp.net hello. world, c#

becomes

.net asp.net hello world c#

Body:
You may add an alternative into your negative lookahead:

(?![/#$]|\.(?!\s))\p{P}
        ^^^^^^^^^

See the regex demo.

Details

(?![/#$]|\.(?!\s)) - fail the match if immediately to the right, there is /, # or $, or a . not followed with a whitespace char

\p{P} - any punctuation proper char


问:
Unable to connect PostgreSQL to remote database using pgAdmin
I installed PostgreSQL on my local server (Ubuntu) with IP 192.168.1.10.  Now, I'm trying to access the database from my client machine (Ubuntu) with IP 192.168.1.11 with pgAdmin.

I know I have to make changes in postgresql.conf and pg_hba.conf to allow the client to connect.  Could you please guide me?

答:
It is actually a 3 step process to connect to a PostgreSQL server remotely through pgAdmin3.

Note: I use Ubuntu 11.04 and PostgreSQL 8.4.

You have to make PostgreSQL listening for remote incoming TCP connections because the default settings allow to listen only for connections on the loopback interface. To be able to reach the server remotely you have to add the following line into the file /etc/postgresql/8.4/main/postgresql.conf:

listen_addresses = '*'

PostgreSQL by default refuses all connections it receives from any remote address, you have to relax these rules by adding this line to /etc/postgresql/8.4/main/pg_hba.conf:

host all all  0.0.0.0/0 md5

This is an access control rule that let anybody login in from any address if he can provide a valid password (the md5 keyword). You can use needed network/mask instead of 0.0.0.0/0 .

When you have applied these modifications to your configuration files you need to restart PostgreSQL server. Now it is possible to login to your server remotely, using the username and password.


问:
replacing nested for loop with lapply()
I have sen this example to explain how to replace an nested for loop with the lapply() function. However i do not fully understand what is happening in the nested for loop?

according to my understanding, the for loop creates for every country for all years two new variables called tempX and tempY, but what happens in the last line of the argument in the for loop?

what is the purpose of variable1 and variable2 ?

```<code># Generate random data:
allCountries <- LETTERS[1:10]
allYears <- 1990:2012

myData <- expand.grid(allCountries, allYears)  # create a dataframe with all possible combinations
colnames(myData) <- c("Country", "Year")
myData$variable1 <- rnorm(nrow(myData))
myData$variable2 <- rnorm(nrow(myData))

# Silly function to perform
myFunction <- function(x, y){
  x * y - x / y
}

### Doubly-nested loop ###
myData$computedFigure <- NA  # Make an "empty" variable in my data.frame

for(ii in allCountries){
  for(jj in allYears){
    tempX <- myData[myData$Country == ii & myData$Year == jj, c("variable1")]
    tempY <- myData[myData$Country == ii & myData$Year == jj, c("variable2")]
    # "Save" results into appropriate location in my data.frame
    myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
  }
}

### Simple lapply() approach ###
computedFigureList <- lapply(1:nrow(myData), function(x){
  tempX <- myData[x, c("variable1")]
  tempY <- myData[x, c("variable2")]
  # "Save" results into appropriate location in my data.frame
  myFunction(tempX, tempY)
})

myData$computedFigure2 <- unlist(computedFigureList)
with(myData, plot(computedFigure, computedFigure2))
</code>```

答:
Actually you don't need nested *apply functions, you can actually use outer + diag to compute computedFigure, which can achieve the same results as you did via nested for loop.

```<code>myData$computedFigure <- diag(with(myData,outer(variable1,variable2,myFunction)))
</code>```

Title: replacing nested for loop with lapply()

Body:
I have sen this example to explain how to replace an nested for loop with the lapply() function. However i do not fully understand what is happening in the nested for loop?

according to my understanding, the for loop creates for every country for all years two new variables called tempX and tempY, but what happens in the last line of the argument in the for loop?

what is the purpose of variable1 and variable2 ?

# Generate random data:
allCountries <- LETTERS[1:10]
allYears <- 1990:2012

myData <- expand.grid(allCountries, allYears)  # create a dataframe with all possible combinations
colnames(myData) <- c("Country", "Year")
myData$variable1 <- rnorm(nrow(myData))
myData$variable2 <- rnorm(nrow(myData))

# Silly function to perform
myFunction <- function(x, y){
  x * y - x / y
}

### Doubly-nested loop ###
myData$computedFigure <- NA  # Make an "empty" variable in my data.frame

for(ii in allCountries){
  for(jj in allYears){
    tempX <- myData[myData$Country == ii & myData$Year == jj, c("variable1")]
    tempY <- myData[myData$Country == ii & myData$Year == jj, c("variable2")]
    # "Save" results into appropriate location in my data.frame
    myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
  }
}

### Simple lapply() approach ###
computedFigureList <- lapply(1:nrow(myData), function(x){
  tempX <- myData[x, c("variable1")]
  tempY <- myData[x, c("variable2")]
  # "Save" results into appropriate location in my data.frame
  myFunction(tempX, tempY)
})

myData$computedFigure2 <- unlist(computedFigureList)
with(myData, plot(computedFigure, computedFigure2))

Body:
Actually you don't need nested *apply functions, you can actually use outer + diag to compute computedFigure, which can achieve the same results as you did via nested for loop.

myData$computedFigure <- diag(with(myData,outer(variable1,variable2,myFunction)))


问:
Key Évents on textbox ,button and progressbar?
I have a textbox, a button, and a progressbar. I would like the keydown event of the textbox therefore the entry, is found using a button in the progressbar, in fact I would like the number entered in the textbox to become the value of the progressbar and that in this case the progressbar value increases. If you could put me a sample code, that would be nice, thank you.

    public void button1_Click(object
    sender,EventArgs e)
    {
    //I don't know.
    }

    public void textbox2_KeyDown(object
    sender,KeyEventArgs e)
    {
    if(e.KeyCode <= Keys.NumPad0 ||
    e.KeyCode >= Keys.NumPad9)
    {
     // I don't know !
    }
```

答:
On KeyDown capture the keyValue

```<code>int keyValue { get; set; }

private void textbox2_KeyDown(object sender, KeyEventArgs e)
{

  int keyVal = (int)e.KeyValue; keyValue = -1;

  if ((keyVal >= (int)Keys.D0 && keyVal <= (int)Keys.D9))
  {
      keyValue = (int)e.KeyValue - (int)Keys.D0;
  }
  else if (keyVal >= (int)Keys.NumPad0 && keyVal <= (int)Keys.NumPad9)
  {
      keyValue = (int)e.KeyValue - (int)Keys.NumPad0;
  }
}
</code>```

On Button Click Increase the ProgessBar value

```<code>public void button1_Click(object sender,EventArgs e)
{
   //Here Increment the progress bar by keyValue
    progressBar1.Value += keyValue;
}
</code>```

KeyValues and KeyCodes

Body:
On KeyDown capture the keyValue

int keyValue { get; set; }

private void textbox2_KeyDown(object sender, KeyEventArgs e)
{

  int keyVal = (int)e.KeyValue; keyValue = -1;

  if ((keyVal >= (int)Keys.D0 && keyVal <= (int)Keys.D9))
  {
      keyValue = (int)e.KeyValue - (int)Keys.D0;
  }
  else if (keyVal >= (int)Keys.NumPad0 && keyVal <= (int)Keys.NumPad9)
  {
      keyValue = (int)e.KeyValue - (int)Keys.NumPad0;
  }
}

On Button Click Increase the ProgessBar value

public void button1_Click(object sender,EventArgs e)
{
   //Here Increment the progress bar by keyValue
    progressBar1.Value += keyValue;
}

KeyValues and KeyCodes


问:
Precheck box in Angular Material Tree
I have an Angular Material Tree I'm displaying. The tree works fine by itself, but I also have a list of names/ids that are already selected values. The data is given to me separately. I haven't been able to figure out how to precheck boxes inside the tree on load.

I've created a Stackblitz here to show my issue: https://stackblitz.com/edit/angular-ukaq9u

My initial thought was to try and look through my selected list and manually toggle the selected in ngInit like so (this doesn't work though):

```<code>    for (const pg of selectedBoxes) {
      let leaf = new TodoItemFlatNode();
      leaf.item = pg.Product_Group_ID.toString();
      leaf.level = 1;
      leaf.expandable = false;
      this.todoLeafItemSelectionToggle(leaf);
    }
</code>```

Does anyone have any other suggestions? I haven't been able to find any examples online.

答:
Finally found a similar example of what I was looking for here.

By looping through my existing nodes and comparing them to my existing list of selected data; I can use the existing node, instead of creating a new copy, to toggle the check.

Like so:

```<code>    for (let i = 0; i < this.treeControl.dataNodes.length; i++) {
      for (const pg of selectedBoxes) {
        if (this.treeControl.dataNodes[i].item == pg.Product_Group_Name) {
          this.todoItemSelectionToggle(this.treeControl.dataNodes[i]);
          this.treeControl.expand(this.treeControl.dataNodes[i])
        }
      }
    }
</code>```

Title: Precheck box in Angular Material Tree

Body:
I have an Angular Material Tree I'm displaying. The tree works fine by itself, but I also have a list of names/ids that are already selected values. The data is given to me separately. I haven't been able to figure out how to precheck boxes inside the tree on load.

I've created a Stackblitz here to show my issue: https://stackblitz.com/edit/angular-ukaq9u

My initial thought was to try and look through my selected list and manually toggle the selected in ngInit like so (this doesn't work though):

    for (const pg of selectedBoxes) {
      let leaf = new TodoItemFlatNode();
      leaf.item = pg.Product_Group_ID.toString();
      leaf.level = 1;
      leaf.expandable = false;
      this.todoLeafItemSelectionToggle(leaf);
    }

Does anyone have any other suggestions? I haven't been able to find any examples online.

Body:
Finally found a similar example of what I was looking for here.

By looping through my existing nodes and comparing them to my existing list of selected data; I can use the existing node, instead of creating a new copy, to toggle the check.

Like so:

    for (let i = 0; i < this.treeControl.dataNodes.length; i++) {
      for (const pg of selectedBoxes) {
        if (this.treeControl.dataNodes[i].item == pg.Product_Group_Name) {
          this.todoItemSelectionToggle(this.treeControl.dataNodes[i]);
          this.treeControl.expand(this.treeControl.dataNodes[i])
        }
      }
    }


问:
Typescript, map one object into another?
I have two objects, and my custom map function to map props of one object into values of another, e.g:

const obj1 = {
  host: 'clientNameHost',
  pass: 'clientNamePass',
};

const obj2 = {
  clientNamePass: '12345',
  clientNameHost: 'http://localhost:3000',
};

const mapParams = <T, K>(source: T, params: K) => Object.entries(params)
.reduce((acc, [param, sourceProp]) => ({ ...acc, [param]: source[sourceProp] }), {});

mapParams(obj2, obj1) //{host: "http://localhost:3000", pass: "12345"}
```

I'm having a hard time, trying to type this function. Is there some way to type properly mapParams function?

答:
When typing functions what I care about the most is argument and return types.

You could type the arguments like this:

```<code><InputProps, TargetProps extends Record<keyof TargetProps, keyof InputProps>>(
  source: InputProps,
  params: TargetProps
) => ...
</code>```

Typescript will complain if the second object doesn't match the first one.

For the return value you can define a utility type as follows:

```<code>type MapFrom<A, B> = Record<keyof A, B[keyof B]>;
</code>```

By using the Object.proptotype.entries type argument we avoid having to cast sourceProp.

To keep the function signature we need to assert the type of initialValue in the reduce.

I also use const assertions to give object literals readonly properties

This is the complete result:

```<code>type MapFrom<A, B> = Record<keyof A, B[keyof B]>;

const obj1 = {
  host: "clientNameHost",
  pass: "clientNamePass"
} as const;

const obj2 = {
  clientNamePass: "12345",
  clientNameHost: "http://localhost:3000"
} as const;

const mapParams = <InputProps, TargetProps extends Record<keyof TargetProps, keyof InputProps>>(
  source: InputProps,
  params: TargetProps
) =>
  Object.entries<keyof InputProps>(params).reduce(
    (acc, [param, sourceProp]) => ({
      ...acc,
      [param]: source[sourceProp]
    }),
    {} as MapFrom<TargetProps, InputProps>
  );

const obj3 = mapParams(obj2, obj1);
</code>```

Here you can try it out.

Body:
I have two objects, and my custom map function to map props of one object into values of another, e.g:

const obj1 = {
  host: 'clientNameHost',
  pass: 'clientNamePass',
};

const obj2 = {
  clientNamePass: '12345',
  clientNameHost: 'http://localhost:3000',
};

const mapParams = <T, K>(source: T, params: K) => Object.entries(params)
.reduce((acc, [param, sourceProp]) => ({ ...acc, [param]: source[sourceProp] }), {});

mapParams(obj2, obj1) //{host: "http://localhost:3000", pass: "12345"}

I'm having a hard time, trying to type this function. Is there some way to type properly mapParams function?

Body:
When typing functions what I care about the most is argument and return types.

You could type the arguments like this:

<InputProps, TargetProps extends Record<keyof TargetProps, keyof InputProps>>(
  source: InputProps,
  params: TargetProps
) => ...

Typescript will complain if the second object doesn't match the first one.

For the return value you can define a utility type as follows:

type MapFrom<A, B> = Record<keyof A, B[keyof B]>;

By using the Object.proptotype.entries type argument we avoid having to cast sourceProp.

To keep the function signature we need to assert the type of initialValue in the reduce.

I also use const assertions to give object literals readonly properties

This is the complete result:

type MapFrom<A, B> = Record<keyof A, B[keyof B]>;

const obj1 = {
  host: "clientNameHost",
  pass: "clientNamePass"
} as const;

const obj2 = {
  clientNamePass: "12345",
  clientNameHost: "http://localhost:3000"
} as const;

const mapParams = <InputProps, TargetProps extends Record<keyof TargetProps, keyof InputProps>>(
  source: InputProps,
  params: TargetProps
) =>
  Object.entries<keyof InputProps>(params).reduce(
    (acc, [param, sourceProp]) => ({
      ...acc,
      [param]: source[sourceProp]
    }),
    {} as MapFrom<TargetProps, InputProps>
  );

const obj3 = mapParams(obj2, obj1);

Here you can try it out.


问:
How can I catch programmer error with malloc?
I'm trying to find a way to catch a programmer error in the argument for malloc in an automated code tester.

For example:

```<code>struct Pepe* p = malloc(sizeof(struct Pepe*));
</code>```

This, of course, compiles without any problems. The thing is that struct Pepe has another struct of the same size inside it, therefore no problem appears during execution (nor with free).

The correct code should be:

```<code>struct Pepe* p = malloc(sizeof(struct Pepe));
</code>```

Can we get a warning or something to catch this problem?

I tried -Wall and -Wextra but there was no warning.

答:
Don't know of any warning or so, but you can use a macro to get around the problem

```<code>#define ALLOC(p, n)  ((p) = malloc((n) * sizeof *(p)))
</code>```

Use it like this:

```<code>struct Pepe *p;
ALLOC(p, 1);
</code>```

Body:
I'm trying to find a way to catch a programmer error in the argument for malloc in an automated code tester.

For example:

struct Pepe* p = malloc(sizeof(struct Pepe*));

This, of course, compiles without any problems. The thing is that struct Pepe has another struct of the same size inside it, therefore no problem appears during execution (nor with free).

The correct code should be:

struct Pepe* p = malloc(sizeof(struct Pepe));

Can we get a warning or something to catch this problem?

I tried -Wall and -Wextra but there was no warning.

Body:
Don't know of any warning or so, but you can use a macro to get around the problem

#define ALLOC(p, n)  ((p) = malloc((n) * sizeof *(p)))

Use it like this:

struct Pepe *p;
ALLOC(p, 1);


问:
Slack url to an image
Ive created a simple slack command that calls a rest api. The api simply returns some json with an image url.

This all works great in slack, but Ive noticed each time you view the image in slack it re-calls the image url.
This image is a live screenshot of one of our servers, if someone in slack views an old image (from a previous day) the screenshot is from now and not then.

Can this be stopped ?  or am I better using webhooks ?

答:
This is normal behavior for images URLs. Slack might cache it for some time, but it will ultimately always retrieve the newest version assuming it is the same image.

However, your image is changing over time. So while it has the same URL the content is changing.

To freeze the image at the time of the request you need to make time based snapshots and give them individual names / URLs. You can do this by creating a copy of that image each time the slash command is called and return a link to that copy. e.g. by uploading it to imgur.com or any other image server. You can also use Slack for this by the way (see this answer)

Title: Slack url to an image


问:
Lazy Loading results in ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:
I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

Go to https://stackblitz.com/edit/angular-sxmpj8

Click on orders tab

Click Test

Expected: It opens Test component
Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

```<code>    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];
</code>```

The routes at app-routing.module.ts are defined as below.

```<code>const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];
</code>```

In orders.component.ts file I have an entry

```<code><button routerLink="/test">Test</button>
</code>```

Clicking this result into error

ERROR
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'

答:
There are two problems:

Because your test component is setup as a child route, you need a module-level <router-outlet> so that the Angular router knows where to render your test component.

On your "test" button, you need to specify the entire route (including /orders).

I forked your stackblitz so you can see it working here => https://stackblitz.com/edit/angular-sxmpj8-q9xzzv

Body:
I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

Go to https://stackblitz.com/edit/angular-sxmpj8

Click on orders tab

Click Test

Expected: It opens Test component
Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];

The routes at app-routing.module.ts are defined as below.

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

In orders.component.ts file I have an entry

<button routerLink="/test">Test</button>

Clicking this result into error

ERROR
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'


问:
Laravel create model outside app namespace
I want to use the command php artisan make:model User for creating an user inside the domain folder. Nevertheless it will end up in the App folder.

I've already tried this:

php artisan make:model Domain\User

php artisan make:model Domain\\User

php artisan make:model \\Domain\\User

php artisan make:model Domain/User

app folder:

```<code>app
 |
 +-- App
 |
 |
 +-- Domain
 |
 |
 +-- Http
</code>```

composer file:

```<code>"autoload": {
    "psr-4": {
      "App\\": "app/App/",
      "Domain\\": "app/Domain/",
      "Http\\": "app/Http/",
      "Support\\": "app/Support/"
    },
</code>```

UPDATE

php artisan make:model ../Domain/User solved the problem for model. I have stil the problem with a controller php artisan make:controller ../Http/UserController

答:
In Laravel 5.4 or later. You can create as below

```<code>  php artisan make:model "Domain\User"
</code>```

Use " (double quotes) or ' (single quotes) to create model

See here

artisan make:model specify the directory and namespace?

Body:
I want to use the command php artisan make:model User for creating an user inside the domain folder. Nevertheless it will end up in the App folder.

I've already tried this:

php artisan make:model Domain\User

php artisan make:model Domain\\User

php artisan make:model \\Domain\\User

php artisan make:model Domain/User

app folder:

app
 |
 +-- App
 |
 |
 +-- Domain
 |
 |
 +-- Http

composer file:

"autoload": {
    "psr-4": {
      "App\\": "app/App/",
      "Domain\\": "app/Domain/",
      "Http\\": "app/Http/",
      "Support\\": "app/Support/"
    },

UPDATE

php artisan make:model ../Domain/User solved the problem for model. I have stil the problem with a controller php artisan make:controller ../Http/UserController

Body:
In Laravel 5.4 or later. You can create as below

  php artisan make:model "Domain\User"

Use " (double quotes) or ' (single quotes) to create model

See here

artisan make:model specify the directory and namespace?


问:
Folder Browser Dialog Inital Folder
I was looking for and Open Folder Dialog (wpf).  I get the Ookii dialogs for wpf and I use VistaFolderBrowserDialog. (I don't like the FolderBrowserDialog of Windows Forms).

I save the "last open folder". So the next time the user open this VistaFolderBrowserDialog the Initial Folder is the "last one" I saved.

```<code>...
//Save the new actual folder
MyProject.ProgramConfigurationFile.Instance.OpenFolderPath = System.IO.Path.GetDirectoryName(folderDialog.SelectedPath);
</code>```

VistaFolderBrowserDialog has the property => RootFolder:

public Environment..::..SpecialFolder RootFolder { get; set; }
But it is a SpecialFolder type.

So I am looking for a way to set my String OpenFolderPath to the RootFolder property.

```<code>VistaFolderBrowserDialog folderDialog = new VistaFolderBrowserDialog();
folderDialog.Description = "Please select the folder";
folderDialog.UseDescriptionForTitle = true;
if ((bool)folderDialog.ShowDialog(this))
{
     //Get the last open folder saved (if exist).
     if(!String.IsNullOrEmpty(MyProject.ProgramConfigurationFile.Instance.OpenFolderPath))
     {
         folderDialog.RootFolder = Environment.SpecialFolder. //I would like to set OpenFolderPath
     }
}
</code>```

Other Folder Browsers are also welcome.

Thank you very much.

答:
I did not know before now Ookii dialogs, but after a little search and knowing how common Open Folder Dialog works i suggest that you set your lastOpenFolder to the SelectedPath property

```<code>folderDialog.SelectedPath = MyProject.ProgramConfigurationFile.Instance.OpenFolderPath;
</code>```

But this must be done before folderDialog.ShowDialog(this) showing the dialog.

So it should look something like

```<code>VistaFolderBrowserDialog folderDialog = new VistaFolderBrowserDialog();
folderDialog.Description = "Please select the folder";
folderDialog.UseDescriptionForTitle = true;

if(!string.IsNullOrEmpty(MyProject.ProgramConfigurationFile.Instance.OpenFolderPath))
    folderDialog.SelectedPath = myProject.ProgramConfigurationFile.Instance.OpenFolderPath;

if ((bool)folderDialog.ShowDialog(this))
{
    string newSelectedFolderPath = folderDialog.SelectedPath;
    // Use new folderPath
}
</code>```

Let me know if this solves it.

I hope I was usefull.

Title: Folder Browser Dialog Inital Folder

Body:
I was looking for and Open Folder Dialog (wpf).  I get the Ookii dialogs for wpf and I use VistaFolderBrowserDialog. (I don't like the FolderBrowserDialog of Windows Forms).

I save the "last open folder". So the next time the user open this VistaFolderBrowserDialog the Initial Folder is the "last one" I saved.

...
//Save the new actual folder
MyProject.ProgramConfigurationFile.Instance.OpenFolderPath = System.IO.Path.GetDirectoryName(folderDialog.SelectedPath);

VistaFolderBrowserDialog has the property => RootFolder:

public Environment..::..SpecialFolder RootFolder { get; set; }
But it is a SpecialFolder type.

So I am looking for a way to set my String OpenFolderPath to the RootFolder property.

VistaFolderBrowserDialog folderDialog = new VistaFolderBrowserDialog();
folderDialog.Description = "Please select the folder";
folderDialog.UseDescriptionForTitle = true;
if ((bool)folderDialog.ShowDialog(this))
{
     //Get the last open folder saved (if exist).
     if(!String.IsNullOrEmpty(MyProject.ProgramConfigurationFile.Instance.OpenFolderPath))
     {
         folderDialog.RootFolder = Environment.SpecialFolder. //I would like to set OpenFolderPath
     }
}

Other Folder Browsers are also welcome.

Thank you very much.

Body:
I did not know before now Ookii dialogs, but after a little search and knowing how common Open Folder Dialog works i suggest that you set your lastOpenFolder to the SelectedPath property

folderDialog.SelectedPath = MyProject.ProgramConfigurationFile.Instance.OpenFolderPath;

But this must be done before folderDialog.ShowDialog(this) showing the dialog.

So it should look something like

VistaFolderBrowserDialog folderDialog = new VistaFolderBrowserDialog();
folderDialog.Description = "Please select the folder";
folderDialog.UseDescriptionForTitle = true;

if(!string.IsNullOrEmpty(MyProject.ProgramConfigurationFile.Instance.OpenFolderPath))
    folderDialog.SelectedPath = myProject.ProgramConfigurationFile.Instance.OpenFolderPath;

if ((bool)folderDialog.ShowDialog(this))
{
    string newSelectedFolderPath = folderDialog.SelectedPath;
    // Use new folderPath
}

Let me know if this solves it.

I hope I was usefull.


问:
Python or Java for text processing (text mining, information retrieval, natural language processing)
I'm soon to start on a new project where I am going to do lots of text processing tasks like searching, categorization/classifying, clustering, and so on.

There's going to be a huge amount of documents that need to be processed; probably millions of documents. After the initial processing, it also has to be able to be updated daily with multiple new documents.

Can I use Python to do this, or is Python too slow? Is it best to use Java?

If possible, I would prefer Python since that's what I have been using lately. Plus, I would finish the coding part much faster. But it all depends on Python's speed. I have used Python for some small scale text processing tasks with only a couple of thousand documents, but I am not sure how well it scales up.

答:
it's not language you have to evaluate, but frameworks and app servers for clustering, data storage/retrieval etc available for the language.

you can use jython and use all the java enterprise technologies for high load system and do text parsing with python.


问:
I want to upload two image files to two separate folders using codeigniter
in my html form i have two file input fields

```<code><div style="width: 125px; height: 35px; float: left; font-weight: bold; font-size: 16px;">
                    Image Large
                </div>
                <div style="width: 125px; height: 35px; float: left; margin-top: 15px;">
                    <input  type="file" name="large_image" id="large_image"/>
                </div>
                <div style="clear: both;"></div>

                <div style="width: 125px; height: 35px; float: left; font-weight: bold; font-size: 16px;">
                    Image Small
                </div>
                <div style="width: 125px; height: 35px; float: left; margin-top: 15px;">
                    <input  type="file" name="small_image" id="small_image"/>
                </div>
</code>```

in my controller file I have two functions to upload small and large image. this two functions are executed by one single function like

```<code>private function insert_products() {
$this->upload_prodct_img_small();
        $this->upload_prodct_img_large();
}
</code>```

the two uploading functions are like this.

```<code>private function upload_prodct_img_large() {
        $image_name = $this->get_image_name_uploade();
        $config['upload_path'] = 'uploaded/large/';
        $config['file_name'] = $image_name;
        $config['overwrite'] = 'FALSE';
        $config['allowed_types'] = 'png|PNG';
        //$config['max_size'] = '1000';
        //$config['max_width'] = '720';
        //$config['max_height'] = '960';
        $config['remove_spaces'] = TRUE;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('large_image')) {
            $error = array('error' => $this->upload->display_errors());
            $this->session->set_flashdata('error', $error);
        } else {
            $error = 'Successfully Uploaded';
            $this->session->set_flashdata('error', $error);
        }
    }

    private function upload_prodct_img_small() {
        $image_name_small = $this->get_image_name_uploade();
        $config['upload_path'] = 'uploaded/';
        $config['file_name'] = $image_name_small ;
        $config['overwrite'] = 'FALSE';
        $config['allowed_types'] = 'png|PNG';
        //$config['max_size'] = '1000';
        //$config['max_width'] = '180';
        //$config['max_height'] = '240';
        $config['remove_spaces'] = TRUE;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('small_image')) {
            $error = array('error' => $this->upload->display_errors());
            $this->session->set_flashdata('error', $error);
        } else {
            $error = 'Successfully Uploaded';
            $this->session->set_flashdata('error', $error);
        }
    }
</code>```

in both cases I rename the file in to a single file name in the $config array.

The problem is this. when I'm trying to upload both files only "small_image" is uploading and always the other one is missing.
you can see that i had commented out that width height and sizes . because if I didn't do that it is giving me an error saying "the file you uploaded is exceeding the allowed height or width" (something like that).

 I have double checked that file size i'm uploading is exactly same as the allowed.

and the other case is I did something like this.

```<code> private function insert_products() {
    //$this->upload_prodct_img_small();
      $this->upload_prodct_img_large();
    }
</code>```

then the large image is uploading without giving any error.

can't find what I'm doing wrong?

答:
Here is working example...
fore more more then two images

public function add($ids1 = null) {

```<code>   $data['page_title']='ADD';
           if ($this->input->post()) {

               $this->form_validation->set_rules('name', 'Name', 'required');
               if ($this->form_validation->run() == FALSE) {

               } else {
                   $cat_file = '';
                   $banner_file = '';
                   if (!empty($_FILES['image']['name'])) {
                       try {
                           $cat_file = $this->fileuploadmain($_FILES);
                       } catch (Exception $e) {
                           log_message('category images', $e->getMessage());
                       }
                   }
                   if (!empty($_FILES['banner_image']['name'])) {
                       try {
                           $banner_file = $this->fileuploadmainbanner($_FILES);
                       } catch (Exception $e) {
                           log_message('banner image category error', $e->getMessage());
                       }
                   }
               }
           }

           $this->maintheme('add', $data);
       }

       public function fileuploadmain($filpost) {
           $path = FCPATH . 'assets/category';
           if (!file_exists($path)) {
               mkdir($path, 0777, true);
           }
           $config['upload_path'] = $path;
           $config['allowed_types'] = 'jpg|png|jpeg|JPG';
           $config['max_size'] = 5000;
           $config['min_width'] = 400;
           $config['min_height'] = 300;

           $this->load->library('upload', $config);
           if (!$this->upload->do_upload('image')) {
               $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
               $error = array('error' => $this->upload->display_errors());
               $this->session->set_flashdata('error', $this->upload->display_errors());
               $this->form_validation->set_rules('file', 'File', 'required');
               return false;
           } else {
               $upload_data = $this->upload->data();
               $file_name = $upload_data['file_name'];
               $thumrest = $this->image_thumb($config['upload_path'], $file_name);
               if ($thumrest) {
                   return $file_name;
               } else {
                   return FALSE;
               }
           }
       }

       public function fileuploadmainbanner($filpost) {
           $path = FCPATH . 'assets/category/banner';
           if (!file_exists($path)) {
               mkdir($path, 0777, true);
           }
           $config1['upload_path'] = $path;
           $config1['allowed_types'] = 'jpg|png|jpeg|JPG';
           $config1['max_size'] = 5000;

           $this->load->library('upload', $config1);
           // here is the most important line
           $this->upload->initialize($config1);
           if (!$this->upload->do_upload('banner_image')) {
               $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
               $error = array('error' => $this->upload->display_errors());
               $this->session->set_flashdata('error', $this->upload->display_errors());
               $this->form_validation->set_rules('banner_image', 'File', 'required');
               return false;
           } else {
               $upload_data1 = $this->upload->data();
               $file_name1 = $upload_data1['file_name'];
               $thumrest1 = $this->image_thumb($config1['upload_path'], $file_name1);
               if ($thumrest1) {
                   return $file_name1;
               } else {
                   return FALSE;
               }
           }
       }

       public function image_thumb($folder_name, $image_name) {
           $origin_folder = $folder_name;
           $width = 200;
           $height = 200;
           $folder_name = $folder_name . '/thumbs';
           if (file_exists($folder_name) == false) {
               mkdir($folder_name, 0777);
           }
           // Path to image thumbnail
           $image_thumb = dirname($folder_name . '/' . $image_name) . '/' . $image_name;
           if (!file_exists($image_thumb)) {
               // LOAD LIBRARY
               $this->load->library('image_lib');
               // CONFIGURE IMAGE LIBRARY
               $config['image_library'] = 'gd2';
               $config['source_image'] = $origin_folder . '/' . $image_name;
               $config['new_image'] = $image_thumb;
               $config['maintain_ratio'] = TRUE;
               $config['height'] = $height;
               $config['width'] = $width;
               $this->image_lib->initialize($config);
               $this->image_lib->resize();
               $this->image_lib->clear();
               return true;
           }
       }

   }
</code>```

Body:
in my html form i have two file input fields

                    Image Large

                    <input  type="file" name="large_image" id="large_image"/>

                    Image Small

                    <input  type="file" name="small_image" id="small_image"/>

in my controller file I have two functions to upload small and large image. this two functions are executed by one single function like

private function insert_products() {
$this->upload_prodct_img_small();
        $this->upload_prodct_img_large();
}

the two uploading functions are like this.

private function upload_prodct_img_large() {
        $image_name = $this->get_image_name_uploade();
        $config['upload_path'] = 'uploaded/large/';
        $config['file_name'] = $image_name;
        $config['overwrite'] = 'FALSE';
        $config['allowed_types'] = 'png|PNG';
        //$config['max_size'] = '1000';
        //$config['max_width'] = '720';
        //$config['max_height'] = '960';
        $config['remove_spaces'] = TRUE;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('large_image')) {
            $error = array('error' => $this->upload->display_errors());
            $this->session->set_flashdata('error', $error);
        } else {
            $error = 'Successfully Uploaded';
            $this->session->set_flashdata('error', $error);
        }
    }

    private function upload_prodct_img_small() {
        $image_name_small = $this->get_image_name_uploade();
        $config['upload_path'] = 'uploaded/';
        $config['file_name'] = $image_name_small ;
        $config['overwrite'] = 'FALSE';
        $config['allowed_types'] = 'png|PNG';
        //$config['max_size'] = '1000';
        //$config['max_width'] = '180';
        //$config['max_height'] = '240';
        $config['remove_spaces'] = TRUE;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('small_image')) {
            $error = array('error' => $this->upload->display_errors());
            $this->session->set_flashdata('error', $error);
        } else {
            $error = 'Successfully Uploaded';
            $this->session->set_flashdata('error', $error);
        }
    }

in both cases I rename the file in to a single file name in the $config array.

The problem is this. when I'm trying to upload both files only "small_image" is uploading and always the other one is missing.
you can see that i had commented out that width height and sizes . because if I didn't do that it is giving me an error saying "the file you uploaded is exceeding the allowed height or width" (something like that).

 I have double checked that file size i'm uploading is exactly same as the allowed.

and the other case is I did something like this.

 private function insert_products() {
    //$this->upload_prodct_img_small();
      $this->upload_prodct_img_large();
    }

then the large image is uploading without giving any error.

can't find what I'm doing wrong?

Body:
Here is working example...
fore more more then two images

public function add($ids1 = null) {

   $data['page_title']='ADD';
           if ($this->input->post()) {

               $this->form_validation->set_rules('name', 'Name', 'required');
               if ($this->form_validation->run() == FALSE) {

               } else {
                   $cat_file = '';
                   $banner_file = '';
                   if (!empty($_FILES['image']['name'])) {
                       try {
                           $cat_file = $this->fileuploadmain($_FILES);
                       } catch (Exception $e) {
                           log_message('category images', $e->getMessage());
                       }
                   }
                   if (!empty($_FILES['banner_image']['name'])) {
                       try {
                           $banner_file = $this->fileuploadmainbanner($_FILES);
                       } catch (Exception $e) {
                           log_message('banner image category error', $e->getMessage());
                       }
                   }
               }
           }

           $this->maintheme('add', $data);
       }

       public function fileuploadmain($filpost) {
           $path = FCPATH . 'assets/category';
           if (!file_exists($path)) {
               mkdir($path, 0777, true);
           }
           $config['upload_path'] = $path;
           $config['allowed_types'] = 'jpg|png|jpeg|JPG';
           $config['max_size'] = 5000;
           $config['min_width'] = 400;
           $config['min_height'] = 300;

           $this->load->library('upload', $config);
           if (!$this->upload->do_upload('image')) {
               $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
               $error = array('error' => $this->upload->display_errors());
               $this->session->set_flashdata('error', $this->upload->display_errors());
               $this->form_validation->set_rules('file', 'File', 'required');
               return false;
           } else {
               $upload_data = $this->upload->data();
               $file_name = $upload_data['file_name'];
               $thumrest = $this->image_thumb($config['upload_path'], $file_name);
               if ($thumrest) {
                   return $file_name;
               } else {
                   return FALSE;
               }
           }
       }

       public function fileuploadmainbanner($filpost) {
           $path = FCPATH . 'assets/category/banner';
           if (!file_exists($path)) {
               mkdir($path, 0777, true);
           }
           $config1['upload_path'] = $path;
           $config1['allowed_types'] = 'jpg|png|jpeg|JPG';
           $config1['max_size'] = 5000;

           $this->load->library('upload', $config1);
           // here is the most important line
           $this->upload->initialize($config1);
           if (!$this->upload->do_upload('banner_image')) {
               $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
               $error = array('error' => $this->upload->display_errors());
               $this->session->set_flashdata('error', $this->upload->display_errors());
               $this->form_validation->set_rules('banner_image', 'File', 'required');
               return false;
           } else {
               $upload_data1 = $this->upload->data();
               $file_name1 = $upload_data1['file_name'];
               $thumrest1 = $this->image_thumb($config1['upload_path'], $file_name1);
               if ($thumrest1) {
                   return $file_name1;
               } else {
                   return FALSE;
               }
           }
       }

       public function image_thumb($folder_name, $image_name) {
           $origin_folder = $folder_name;
           $width = 200;
           $height = 200;
           $folder_name = $folder_name . '/thumbs';
           if (file_exists($folder_name) == false) {
               mkdir($folder_name, 0777);
           }
           // Path to image thumbnail
           $image_thumb = dirname($folder_name . '/' . $image_name) . '/' . $image_name;
           if (!file_exists($image_thumb)) {
               // LOAD LIBRARY
               $this->load->library('image_lib');
               // CONFIGURE IMAGE LIBRARY
               $config['image_library'] = 'gd2';
               $config['source_image'] = $origin_folder . '/' . $image_name;
               $config['new_image'] = $image_thumb;
               $config['maintain_ratio'] = TRUE;
               $config['height'] = $height;
               $config['width'] = $width;
               $this->image_lib->initialize($config);
               $this->image_lib->resize();
               $this->image_lib->clear();
               return true;
           }
       }

   }


答:
You can't really resolve the warning this way if you're naming the types.

An easier solution would be to use the variable to find its size. This also alleviates any possible issues with the type of the variable changing:

```<code>struct Pepe *p = malloc(sizeof(*p));
</code>```

Now if I make p an int *...

```<code>int *p = malloc(sizeof(*p));
</code>```

it still works!

If you want to do it at execution time, you can build your code with the -fsanitize=address flag (assuming GCC or Clang) or you can use the Valgrind tool.

Title: How can I catch programmer error with malloc?

Body:
You can't really resolve the warning this way if you're naming the types.

An easier solution would be to use the variable to find its size. This also alleviates any possible issues with the type of the variable changing:

struct Pepe *p = malloc(sizeof(*p));

Now if I make p an int *...

int *p = malloc(sizeof(*p));

it still works!

If you want to do it at execution time, you can build your code with the -fsanitize=address flag (assuming GCC or Clang) or you can use the Valgrind tool.


问:
how to setup “Get started” button in facebook messenger bot
I m trying to use postman
link:https://graph.facebook.com/v6.0/me/messages?access_token=my_token

```<code>{
  "get_started":{
    "payload": "Hi, I am bot"
  }
}
</code>```

in raw JSON body

but getting this response

```<code>{
    "error": {
        "message": "(#100) Tried accessing nonexisting field (messages) on node type (Page)",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "AtFh2_fJ2sxkeU8k-2aNJGl"
    }
}
</code>```

答:
Here is the little rundown how to put get started button , I hope its help:
Using postman:

Start by changing the type by choosing a POST request: (one of the
problems that solve my issue thanks to @misorude

Define a Post request to this URL:

```<code>https://graph.facebook.com/v6.0/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>
</code>```

As @misorude notice my another problem check endpoint from here https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api

In the BODY section:

.
Paste this code:

```<code>{
  "get_started":{
    "payload": "Hi, I am bot"
  }
}
</code>```

P.S.
Thank you again

Body:
I m trying to use postman
link:https://graph.facebook.com/v6.0/me/messages?access_token=my_token

{
  "get_started":{
    "payload": "Hi, I am bot"
  }
}

in raw JSON body

but getting this response

{
    "error": {
        "message": "(#100) Tried accessing nonexisting field (messages) on node type (Page)",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "AtFh2_fJ2sxkeU8k-2aNJGl"
    }
}

Body:
Here is the little rundown how to put get started button , I hope its help:
Using postman:

Start by changing the type by choosing a POST request: (one of the
problems that solve my issue thanks to @misorude

Define a Post request to this URL:

https://graph.facebook.com/v6.0/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>

As @misorude notice my another problem check endpoint from here https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api

In the BODY section:

.
Paste this code:

{
  "get_started":{
    "payload": "Hi, I am bot"
  }
}

P.S.
Thank you again


问:
How do I get the html of a webpage using urllib?
I'm trying to get the href tags using BeautifulSoup and urllib for https://www.reddit.com/. This is my code;

```<code>ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

searchurl = https://www.reddit.com/
html = urllib.request.urlopen(searchurl,context = ctx).read()
</code>```

The above gives me the html in some instances however at other times it results in the following error;

```<code>urllib.error.HTTPError: HTTP Error 401: Unauthorized
</code>```

How do I get the html in a consistent manner?

答:
```<code>from urllib import request
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

searchurl = 'https://www.reddit.com'
html = request.urlopen(searchurl, context=ctx).read()

print(html)
</code>```

This worked for me.
Try removing the trailing '/' from the url and be sure to surround the url with quotes

Body:
I'm trying to get the href tags using BeautifulSoup and urllib for https://www.reddit.com/. This is my code;

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

searchurl = https://www.reddit.com/
html = urllib.request.urlopen(searchurl,context = ctx).read()

The above gives me the html in some instances however at other times it results in the following error;

urllib.error.HTTPError: HTTP Error 401: Unauthorized

How do I get the html in a consistent manner?

Body:
from urllib import request
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

searchurl = 'https://www.reddit.com'
html = request.urlopen(searchurl, context=ctx).read()

print(html)

This worked for me.
Try removing the trailing '/' from the url and be sure to surround the url with quotes


问:
ACF Link in Repeater doesn't work correctly
```<code>    <div class="section3">
    <?php if( have_rows('section3') ): ?>

    <?php while( have_rows('section3') ): the_row();

        // vars
        $image = get_sub_field('image');
        $title = get_sub_field('title');
        $caption = get_sub_field('caption');
        $link_text = get_sub_field('link_text');
        $link = get_sub_field('link');

        ?>
            <div class="container">
                    <div data-aos="fade-left">
                        <div class="section3-top">
                            <div class="rotatey">
                                <img src="<?php echo $image; ?>" alt="">
                            </div>
                            <div class="top__right">
                                <h6><?php echo $title; ?></h6>
                                <div class="desc">
                                    <?php echo $caption; ?>
                                </div>
                                <div class="click">

                                <?php if( $link ): ?>

                                    <a href="<?php $link; ?>" class="click__a">
                                        <img src="<?php bloginfo('template_directory');?>/assets/img/icons/right-arrow-grey.svg" alt=""
                                            class="click__right-arrow">
                                        <h6>View</h6>
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

    <?php endwhile; ?>
<?php endif; ?>
</code>```

All the Variables are working correctly except the link does the PHP inside the Html link tag not correct, the link is URL in the configuration.
By the way, I'm new on PHP and Wordpress, Thanks.

答:
You are missing a print/echo.

href="<?php $link; ?>" class="click__a">
```

<p>Should be </p>

<pre class="lang-php prettyprint-override"><code>href="<?php echo $link; ?>" class="click__a">
</code>```

Body:
    <?php if( have_rows('section3') ): ?>

    <?php while( have_rows('section3') ): the_row();

        // vars
        $image = get_sub_field('image');
        $title = get_sub_field('title');
        $caption = get_sub_field('caption');
        $link_text = get_sub_field('link_text');
        $link = get_sub_field('link');

        ?>

                                <img src="<?php echo $image; ?>" alt="">

<?php echo $title; ?>

                                    <?php echo $caption; ?>

                                <?php if( $link ): ?>

                                    <a href="<?php $link; ?>" class="click__a">
                                        <img src="<?php bloginfo('template_directory');?>/assets/img/icons/right-arrow-grey.svg" alt=""
                                            class="click__right-arrow">

View

                                    <?php endif; ?>

    <?php endwhile; ?>
<?php endif; ?>

All the Variables are working correctly except the link does the PHP inside the Html link tag not correct, the link is URL in the configuration.
By the way, I'm new on PHP and Wordpress, Thanks.

Body:
You are missing a print/echo.

<a href="<?php $link; ?>" class="click__a">

Should be

<a href="<?php echo $link; ?>" class="click__a">


问:
OpenFeign Builder default client
What is the default Client used by Openfeign Builder.

OkHttp client

```<code>Feign.builder().client(new feign.okhttp.OkHttpClient()).target(SomeData.class,"http://test.com");
</code>```

What is the default client?

```<code>Feign.builder().target(SomeData.class,"http://test.com");
</code>```

答:
If it's still relevant for you:

If you look at the source code of Feign.Builder, you'd see that it uses Client.Default unless otherwise specified.

Client.Default is actually a good old Java HTTP Client from java.net package.

If you're not familiar with it, you can read about it in docs.

Title: OpenFeign Builder default client

Body:
What is the default Client used by Openfeign Builder.

OkHttp client

Feign.builder().client(new feign.okhttp.OkHttpClient()).target(SomeData.class,"http://test.com");

What is the default client?

Feign.builder().target(SomeData.class,"http://test.com");


问:
NoClassDefFoundError: Failed resolution of: Lkotlinx/coroutines/Dispatchers
I have a library that uses Kotlin Coroutines and uses the CoroutineScope as

```<code>private val coroutineScope by lazy(mode = LazyThreadSafetyMode.NONE) {
        CoroutineScope(Dispatchers.Main)
    }
</code>```

When I use the library in other projects I am getting error:

```<code>com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "kotlinx.coroutines.Dispatchers" on path: DexPathList[[zip file "/data/app/com.ssss.ssss-X44QPiLhKdl-D6eyVAYkOA==/base.apk"],nativeLibraryDirectories=[/data/app/com.ssss.testauthenticater-X44QPiLhKdl-D6eyVAYkOA==/lib/x86, /system/lib, /system/product/lib]]
</code>```

I have added -keepnames class kotlinx.** { *; }
 in my consumer pro guard file as well.

Does anyone have similar issue? I am using coroutine 1.3.3 in android.

答:
After sometime with help of link posted by @orest-herdil above, I figured out the issue was the dependency of my library module were not added in the POM file generated while bundling the AAR file. So I updated my maven publish code as:

```<code>publishing {
    publications {
        aar(MavenPublication) {
            groupId "com.mylibrary"
            version "1.1.1"
            artifactId "awesome"

            artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")

            pom.withXml {
                def dependenciesNode = asNode().appendNode('dependencies')
                configurations.implementation.allDependencies.each { dependency ->
                    final dependencyNode = dependenciesNode.appendNode('dependency')
                    dependencyNode.appendNode('groupId', dependency.group)
                    dependencyNode.appendNode('artifactId', dependency.name)
                    dependencyNode.appendNode('version', dependency.version)
                }
            }
        }
    }
}
</code>```

The part pom.withXml { .... } will go through all the dependency in my library module and add them in generating POM file one by one. As of now the compile is already deprecated, I am going through implementation dependency only.

Body:
I have a library that uses Kotlin Coroutines and uses the CoroutineScope as

private val coroutineScope by lazy(mode = LazyThreadSafetyMode.NONE) {
        CoroutineScope(Dispatchers.Main)
    }

When I use the library in other projects I am getting error:

com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "kotlinx.coroutines.Dispatchers" on path: DexPathList[[zip file "/data/app/com.ssss.ssss-X44QPiLhKdl-D6eyVAYkOA==/base.apk"],nativeLibraryDirectories=[/data/app/com.ssss.testauthenticater-X44QPiLhKdl-D6eyVAYkOA==/lib/x86, /system/lib, /system/product/lib]]

I have added -keepnames class kotlinx.** { *; }
 in my consumer pro guard file as well.

Does anyone have similar issue? I am using coroutine 1.3.3 in android.

Body:
After sometime with help of link posted by @orest-herdil above, I figured out the issue was the dependency of my library module were not added in the POM file generated while bundling the AAR file. So I updated my maven publish code as:

publishing {
    publications {
        aar(MavenPublication) {
            groupId "com.mylibrary"
            version "1.1.1"
            artifactId "awesome"

            artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")

            pom.withXml {
                def dependenciesNode = asNode().appendNode('dependencies')
                configurations.implementation.allDependencies.each { dependency ->
                    final dependencyNode = dependenciesNode.appendNode('dependency')
                    dependencyNode.appendNode('groupId', dependency.group)
                    dependencyNode.appendNode('artifactId', dependency.name)
                    dependencyNode.appendNode('version', dependency.version)
                }
            }
        }
    }
}

The part pom.withXml { .... } will go through all the dependency in my library module and add them in generating POM file one by one. As of now the compile is already deprecated, I am going through implementation dependency only.


问:
MassTransit Publisher no exception thrown
I have a MassTransit Producer / Publisher developed in Asp.Net Web API.

The producer simply sends message to the Exchange -> Queue.

```<code>public async Task<bool> AddToQueue(int msgId, Message message)
{
     var endpoint = await _bus.GetSendEndpoint(new Uri("exchange:testExchange?bind=true&queue=MessageQueue"));
     await endpoint.Send(new Message()
     {
         Id = msgId,
         Text = message.Text
     });
     return true;
}
</code>```

However, the above would not return any exception (even if I had some sort of handling in place) if for instance queue was not found or there was an issue with binding etc. Message will simply get lost with no sign of it creating an error queue?

I understand it will create a queue if one was not found but am sure if there was an issue between with the Message broker and producer how would you handle that?

答:
To get an exception from task operation you need to assign result of your method execution to Task variable, like this:

```<code>Task<bool> myTask = AddToQueue(42, "Some message");
</code>```

And than you can get your exception from Exception property of Task:

```<code>if (myTask.Exception != null)
    Console.WriteLine(myTask.Exception.InnerException.Message);
</code>```

Body:
I have a MassTransit Producer / Publisher developed in Asp.Net Web API.

The producer simply sends message to the Exchange -> Queue.

public async Task<bool> AddToQueue(int msgId, Message message)
{
     var endpoint = await _bus.GetSendEndpoint(new Uri("exchange:testExchange?bind=true&queue=MessageQueue"));
     await endpoint.Send(new Message()
     {
         Id = msgId,
         Text = message.Text
     });
     return true;
}

However, the above would not return any exception (even if I had some sort of handling in place) if for instance queue was not found or there was an issue with binding etc. Message will simply get lost with no sign of it creating an error queue?

I understand it will create a queue if one was not found but am sure if there was an issue between with the Message broker and producer how would you handle that?

Body:
To get an exception from task operation you need to assign result of your method execution to Task variable, like this:

Task<bool> myTask = AddToQueue(42, "Some message");

And than you can get your exception from Exception property of Task:

if (myTask.Exception != null)
    Console.WriteLine(myTask.Exception.InnerException.Message);


问:
.libPaths(blah) does nothing
Apologies if someone has asked this before.  I've tried Googling and Googling, but no one seems to have reported quite this.  I'm trying to add a path to my .libPaths, but .libPaths(new=blah) doesn't seem to alter anything.  Here is my code:

```<code>packagedir = paste0(getwd(),'/extraRPackages/')
newLibPaths = c(packagedir,.libPaths())
print(newLibPaths)
.libPaths(newLibPaths)
print(.libPaths())
</code>```

...here is the output from the first print (what I'm passing into .libPaths):

```<code>[1] "C:/Users/GCW/Dropbox/Mash share/Phil/R/mashdb/database/extraRPackages/"
[2] "C:/Users/GCW/Documents/R/win-library/3.3"
[3] "C:/Program Files/R/R-3.3.1/library"
</code>```

... and the second print:

```<code>[1] "C:/Users/GCW/Documents/R/win-library/3.3" "C:/Program Files/R/R-3.3.1/library"
</code>```

Why might my call to .libPaths(new=blah) do absolutely nothing??  I'm stumped!  I've tried it in RStudio and RPortable, but both give me the same output...  Any help v much appreciated...

(I know from reading other answers that there are "proper" ways to change the paths permanently, but this is something I want to be able to do dynamically in a rather unusual setup, and if .libPaths just did what I thought it would, I'd be done...)

EDIT: It was suggested that this might be a duplicate of this question Changing R default library path using .libPaths in Rprofile.site fails to work -- but I don't think it is.  I read this question before posting my own -- but in this question, it says at the end that "if I start RStudio the .libPaths() command seems to work as it is supposed to" -- but it is precisely in RStudio that the command doesn't do anything for me (and this is where I want to use it, not in the RProfile.site file and not in any permanent way)....

答: This can also happen if the directory you're trying to add to .libPaths doesn't exist yet.</p>

Title: .libPaths(blah) does nothing

Body:
Apologies if someone has asked this before.  I've tried Googling and Googling, but no one seems to have reported quite this.  I'm trying to add a path to my .libPaths, but .libPaths(new=blah) doesn't seem to alter anything.  Here is my code:

packagedir = paste0(getwd(),'/extraRPackages/')
newLibPaths = c(packagedir,.libPaths())
print(newLibPaths)
.libPaths(newLibPaths)
print(.libPaths())

...here is the output from the first print (what I'm passing into .libPaths):

[1] "C:/Users/GCW/Dropbox/Mash share/Phil/R/mashdb/database/extraRPackages/"
[2] "C:/Users/GCW/Documents/R/win-library/3.3"
[3] "C:/Program Files/R/R-3.3.1/library"

... and the second print:

[1] "C:/Users/GCW/Documents/R/win-library/3.3" "C:/Program Files/R/R-3.3.1/library"

Why might my call to .libPaths(new=blah) do absolutely nothing??  I'm stumped!  I've tried it in RStudio and RPortable, but both give me the same output...  Any help v much appreciated...

(I know from reading other answers that there are "proper" ways to change the paths permanently, but this is something I want to be able to do dynamically in a rather unusual setup, and if .libPaths just did what I thought it would, I'd be done...)

EDIT: It was suggested that this might be a duplicate of this question Changing R default library path using .libPaths in Rprofile.site fails to work -- but I don't think it is.  I read this question before posting my own -- but in this question, it says at the end that "if I start RStudio the .libPaths() command seems to work as it is supposed to" -- but it is precisely in RStudio that the command doesn't do anything for me (and this is where I want to use it, not in the RProfile.site file and not in any permanent way)....


问:
Is Laravel blade '@include()' case-sensitive?
I'm getting a "blade not found shop.cart.favorites" error when running in Docker on Ubuntu.  (Therefore: "case-sensitive file system.")

I suspect that the culprit is case-sensitivity.  The path to the blade file is:

```<code> resources/views/Shop/Cart/favorites.blade.php
                 ^    ^
</code>```

Did I guess correctly?

答:
Okay, thanks folks. Indeed, that's the [ANSWER] I was expecting:  the underlying filesystem is case-sensitive, and therefore so is PHP (file_exists() et al ...), and therefore so is Laravel.  Blade file and folder names are case-sensitive.

Now ... here's a follow-on question:  is there a handy-dandy plugin for Laravel that might enable me to "skate around" this issue?  (Yeah, I think I know what that answer will be, too.  But it doesn't hurt to ask ...)

Body:
I'm getting a "blade not found shop.cart.favorites" error when running in Docker on Ubuntu.  (Therefore: "case-sensitive file system.")

I suspect that the culprit is case-sensitivity.  The path to the blade file is:

 resources/views/Shop/Cart/favorites.blade.php
                 ^    ^

Did I guess correctly?


问:
pg_escape_string not working
I want to use pg_escape_string in my password can anyone sugest me hows it is used? in my postgresql insert table

```<code>$query = "insert into vmobjects (guid,ipaddress,username,password,hostid,vmname,guestostype) values('".$guid."','".$ip."','".$username."','".$password."','".$hostid."','".$name."','".strtolower($os)."')";
</code>```

I m using $escaped = pg_escape_string($password);

```<code>$query = "insert into vmobjects (guid,ipaddress,username,password,hostid,vmname,guestostype) values('".$guid."','".$ip."','".$username."','".$escaped ."','".$hostid."','".$name."','".strtolower($os)."')";
</code>```

but it is not working
it wil not take my & and + string ... like if i insert @#&$%&^* as a password then after @# it shows nul values .... pg_escape_string not working

It wil takes '~!@#$%^*()_=-{}|][:"';<>?/.,'except& and +` string.

my backend table row insert & string as a null value and after & string all values are null
and In the case of + string this is only null

Plz Don't refer me the sites manual

Ya I'm POSTing the contents of a form field via AJAX to a PHP script and using this code

```<code>if(!http)
            http = CreateObject();

        nocache = Math.random();

        http.open('post', 'addvm.php');
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", params.length);
        http.setRequestHeader("Connection", "close");
        http.onreadystatechange = SaveReply;

        http.send(params);
</code>```

答:
The best thing to do here would be to encode the password and then enter it into the database. This way, you won't get any escaping problems.

A way to do this would be:

```<code>$escaped = md5($password);
</code>```

And when you check if the password matches, do:

```<code>if (md5($user_entered_password) == $password)...
</code>```

Title: pg_escape_string not working

Body:
I want to use pg_escape_string in my password can anyone sugest me hows it is used? in my postgresql insert table

$query = "insert into vmobjects (guid,ipaddress,username,password,hostid,vmname,guestostype) values('".$guid."','".$ip."','".$username."','".$password."','".$hostid."','".$name."','".strtolower($os)."')";

I m using $escaped = pg_escape_string($password);

$query = "insert into vmobjects (guid,ipaddress,username,password,hostid,vmname,guestostype) values('".$guid."','".$ip."','".$username."','".$escaped ."','".$hostid."','".$name."','".strtolower($os)."')";

but it is not working
it wil not take my & and + string ... like if i insert @#&$%&^* as a password then after @# it shows nul values .... pg_escape_string not working

It wil takes '~!@#$%^*()_=-{}|][:"';<>?/.,'except& and +` string.

my backend table row insert & string as a null value and after & string all values are null
and In the case of + string this is only null

Plz Don't refer me the sites manual

Ya I'm POSTing the contents of a form field via AJAX to a PHP script and using this code

if(!http)
            http = CreateObject();

        nocache = Math.random();

        http.open('post', 'addvm.php');
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", params.length);
        http.setRequestHeader("Connection", "close");
        http.onreadystatechange = SaveReply;

        http.send(params);

Body:
The best thing to do here would be to encode the password and then enter it into the database. This way, you won't get any escaping problems.

A way to do this would be:

$escaped = md5($password);

And when you check if the password matches, do:

if (md5($user_entered_password) == $password)...