问:
How to Get Public Data or Tags from Instagram Using the New API?
Is there any way to get Instagram public profile data as per new API?

According to Instagram, these are the steps that I need to follow:

Create an application by providing site url and redirect url.

Redirect your user using oAuth and generate access token.

Now using the proper url and access token we can get user data.

I did each step and generate access token properly now I am using ajax to hit the url

```<code>https://api.instagram.com/v1/users/searchq='+inst.instagramId+'&access_token='+inst.accessToken
</code>```

where inst.instagramId is user id and inst.accessToken is access token.
Response contain code 200 that is ok but data is empty.

Thanks for any help.

答:
I wrote a proxy API for this exact purpose: https://github.com/whizzzkid/instagram-proxy-api

Let's take an example of #nyc:
Instagram's tag explorer: https://www.instagram.com/explore/tags/nyc

Getting the same results as JSON: https://igpi.ga/explore/tags/nyc/media

You can find more examples in the repo. Here is the code that does all this: https://github.com/whizzzkid/instagram-reverse-proxy/blob/master/app.js

A demo application using jquery will be:

```<code>$.ajax({
  url: "https://igpi.ga/explore/tags/yyc/media",
  dataType: "jsonp",
  data: { count: 3 },
  success: function (json){
    for(var i in json.posts) {
      var img = document.createElement("IMG");
      img.src = json.posts[i].display_url;
      document.body.appendChild(img);
    }
  }
});
</code>```

Demo: http://plnkr.co/edit/4oCwpbMm6p9cyJb1UWld?p=preview

hope this helps.

Body:
Is there any way to get Instagram public profile data as per new API?

According to Instagram, these are the steps that I need to follow:

Create an application by providing site url and redirect url.

Redirect your user using oAuth and generate access token.

Now using the proper url and access token we can get user data.

I did each step and generate access token properly now I am using ajax to hit the url

https://api.instagram.com/v1/users/searchq='+inst.instagramId+'&access_token='+inst.accessToken

where inst.instagramId is user id and inst.accessToken is access token.
Response contain code 200 that is ok but data is empty.

Thanks for any help.

Body:
I wrote a proxy API for this exact purpose: https://github.com/whizzzkid/instagram-proxy-api

Let's take an example of #nyc:
Instagram's tag explorer: https://www.instagram.com/explore/tags/nyc

Getting the same results as JSON: https://igpi.ga/explore/tags/nyc/media

You can find more examples in the repo. Here is the code that does all this: https://github.com/whizzzkid/instagram-reverse-proxy/blob/master/app.js

A demo application using jquery will be:

$.ajax({
  url: "https://igpi.ga/explore/tags/yyc/media",
  dataType: "jsonp",
  data: { count: 3 },
  success: function (json){
    for(var i in json.posts) {
      var img = document.createElement("IMG");
      img.src = json.posts[i].display_url;
      document.body.appendChild(img);
    }
  }
});

Demo: http://plnkr.co/edit/4oCwpbMm6p9cyJb1UWld?p=preview

hope this helps.


来源: stackexchange

问:
How to add key value pair as last entry in OrderedMap..?
Possible duplicate:
Add an Item in OrderedMap with Immutable.js

Working with redux store and Immutable js OrderedMap.

Redux store structure:

```<code>   {
     "app": {
        "name": "Test app",
        "dataPack":{
          "chemID": "aaaa",
          "item": {
            "yp57m359": {
            "solid": 33,
            "liquid": 45,
            "gas": 65
           },
           "h58wme1y": {
             "solid": 87,
             "liquid": 9,
             "gas": 30
           },
           "dff56fhh": {
             "solid": 76,
             "liquid": 43,
             "gas": 77
           }
         }
       }
     }
  }
</code>```

Reducer code:

```<code>return state.setIn(["app","dataPack","item",action.item_id],
  fromJS({
    "solid": action.soildVal,
    "liquid": action.liquidVal,
    "gas": action.gasVal
}));
</code>```

where action.item_id is the random id (key for every item).

Above code works perfectly for adding items.

Problem is: Items stored in a random position. I need to keep the order I am adding. Need to add every item as last entry inside item. Adding one by one item is not in same order.

Help me to get a clear solution for this.

答:
An OrderedMap will remember the order you put things in it. Every time you call .set(key, value) with a new key on an OrderedMap, it will get added to the end.

let state = Immutable.Map({
  "app": Immutable.Map({
    "name": "Test App",
    "dataPack": Immutable.Map({
      "chemId": "aaaa",
      "items": Immutable.OrderedMap({}) // this is the thing we want ordered
    })
  })
});

state = state.setIn(['app', 'dataPack', 'items', 'yp57m359'], Immutable.Map({
  'first': 'item'
}));
state = state.setIn(['app', 'dataPack', 'items', 'h58wme1y'], Immutable.Map({
  'second': 'item'
}));
state = state.setIn(['app', 'dataPack', 'items', 'dff56fhh'], Immutable.Map({
  'third': 'item'
}));

console.log(state.toJS()); // notice things are in order```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script></code>```

It's hard to tell exactly where your problem is because we can't see how you created your store, but my guess would be that "item" is pointing to a regular old Map instead of an OrderedMap. If you're just using fromJS(data) to create your state, it will default to using a Map instead of an OrderedMap.

ContentLicense: CC BY-SA 3.0

Body:
Possible duplicate:
Add an Item in OrderedMap with Immutable.js

Working with redux store and Immutable js OrderedMap.

Redux store structure:

   {
     "app": {
        "name": "Test app",
        "dataPack":{
          "chemID": "aaaa",
          "item": {
            "yp57m359": {
            "solid": 33,
            "liquid": 45,
            "gas": 65
           },
           "h58wme1y": {
             "solid": 87,
             "liquid": 9,
             "gas": 30
           },
           "dff56fhh": {
             "solid": 76,
             "liquid": 43,
             "gas": 77
           }
         }
       }
     }
  }

Reducer code:

return state.setIn(["app","dataPack","item",action.item_id],
  fromJS({
    "solid": action.soildVal,
    "liquid": action.liquidVal,
    "gas": action.gasVal
}));

where action.item_id is the random id (key for every item).

Above code works perfectly for adding items.

Problem is: Items stored in a random position. I need to keep the order I am adding. Need to add every item as last entry inside item. Adding one by one item is not in same order.

Help me to get a clear solution for this.

Body:
An OrderedMap will remember the order you put things in it. Every time you call .set(key, value) with a new key on an OrderedMap, it will get added to the end.

let state = Immutable.Map({
  "app": Immutable.Map({
    "name": "Test App",
    "dataPack": Immutable.Map({
      "chemId": "aaaa",
      "items": Immutable.OrderedMap({}) // this is the thing we want ordered
    })
  })
});

state = state.setIn(['app', 'dataPack', 'items', 'yp57m359'], Immutable.Map({
  'first': 'item'
}));
state = state.setIn(['app', 'dataPack', 'items', 'h58wme1y'], Immutable.Map({
  'second': 'item'
}));
state = state.setIn(['app', 'dataPack', 'items', 'dff56fhh'], Immutable.Map({
  'third': 'item'
}));

console.log(state.toJS()); // notice things are in order

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>

It's hard to tell exactly where your problem is because we can't see how you created your store, but my guess would be that "item" is pointing to a regular old Map instead of an OrderedMap. If you're just using fromJS(data) to create your state, it will default to using a Map instead of an OrderedMap.


问:
How to disable swiping a ViewPager from its edges?
I have an activity containing a Navigation Drawer and a AutoScrollViewPager. When I **swipe from the left edge of my phone's screen to open the Navigation Drawer, the AutoScrollViewPager's page changes instead of Navigation Drawer coming out. How can I disable the swiping of AutoScrollViewPager from its edges?

P.S. I tried adding margin to the AutoScrollViewPager but it looks ugly and does not work if the margin isn't large enough.

答:
Use Edge Flags

Here is the Documentation

Try using below code:

```<code>final View pagerView = findViewById(R.id.Pager);
pagerView.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
       if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() == MotionEvent.EDGE_LEFT) {
            return true;   //disable swipe
        }
    }
 });
</code>```

Body:
Use Edge Flags

Here is the Documentation

Try using below code:

final View pagerView = findViewById(R.id.Pager);
pagerView.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
       if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() == MotionEvent.EDGE_LEFT) {
            return true;   //disable swipe
        }
    }
 });


问:
MyIsam MRG -- best practices managing uniqueness
The MRG table contains 1B+ rows, spread over several smaller tables. Additional observations are added to the MRG table, which adds them to the last underlying table.

For some reason, there appears to be a couple of duplicate rows sharing the same primary key. I know that this is a limitation of the MRG tables and it is not really problematic in our case (it simply means useless redundancy). We believe that the duplicates were inserted following a system crash, such that the reprocessing wasn't properly handled by the application's code that deletes duplicates from a temporary table prior to insertion in the archive.

This being said, is there a set of best practices to maintain uniqueness that will not require too much processing time?

答:
You will always be at risk of duplicates.

https://dev.mysql.com/doc/refman/5.7/en/merge-storage-engine.html says:

...a MERGE table cannot enforce uniqueness over the set of underlying tables.

Don't use MERGE tables. MERGE only works with MyISAM, and you shouldn't be using MyISAM.

Instead, use PARTITIONING. You can enforce uniqueness across all partitions for a given table.


问:
Interactive beautiful slider line/ribbon plots of Pandas dataframe without putting data online (Maybe with IPython widgets?)
Consider the beautiful graph [code first, image not showing because I have no upvotes yet]:

```<code>import pandas as np
from plotnine import *

df = pd.DataFrame([
        {'Year': 2000, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2000, 'X':2, 'Y': 2, 'err': .2},
        {'Year': 2000, 'X':3, 'Y': 3, 'err': .3},
        {'Year': 2001, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2001, 'X':2, 'Y': 4, 'err': .3},
        {'Year': 2001, 'X':3, 'Y': 9, 'err': .5},
        {'Year': 2002, 'X':1, 'Y': 1, 'err': .2},
        {'Year': 2002, 'X':2, 'Y': 8, 'err': .6},
        {'Year': 2002, 'X':3, 'Y': 27, 'err': .9},
    ])
df.set_index('Year')
df['ymin'] = df['Y'] - df['err']
df['ymax'] = df['Y'] + df['err']

(ggplot(df, aes(x='X', y='Y', group='Year', color='Year', ymin='ymin', ymax='ymax'))
+ geom_line()
+ geom_ribbon(alpha=.2)
)
</code>```

Beautiful graph

How can I make an interactive version of this plot where one can use a slider to change the year being graphed? In my real data set I have 20 years of data and I would like to see how the distribution of this line, and its error bar, changes over time simply by sliding from 1997-2017. Importantly, I cannot upload the data to a server, so that rules out Plotly.

I spent several hours trying to make this work with Bokeh, but could not figure out how to make it play nice with Pandas dataframes. This seems like something that should be easy to do! And yet so many of the tutorials seem incredibly dense and hard to follow.

Is it?

Edit: Can this be done with IPython widgets?

答:
check this code. Save it as 'script.py' and run it with bokeh serve --show script.py

It may not be the most simple way of doing it. I usually use the low-mid level api of bokeh to make my plots.

```<code>from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, LinearColorMapper, ColorBar, Slider, Button
from bokeh.palettes import Viridis256
from bokeh.layouts import gridplot, widgetbox

import pandas as pd
import numpy as np

df = pd.DataFrame([
        {'Year': 2000, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2000, 'X':2, 'Y': 2, 'err': .2},
        {'Year': 2000, 'X':3, 'Y': 3, 'err': .3},
        {'Year': 2001, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2001, 'X':2, 'Y': 4, 'err': .3},
        {'Year': 2001, 'X':3, 'Y': 9, 'err': .5},
        {'Year': 2002, 'X':1, 'Y': 1, 'err': .2},
        {'Year': 2002, 'X':2, 'Y': 8, 'err': .6},
        {'Year': 2002, 'X':3, 'Y': 27, 'err': .9},
    ])
grouped = df.groupby('Year')

max_year = max(df['Year'])
min_year = min(df['Year'])

def ID_map(year,mini=min_year,maxi=max_year,palette=Viridis256):
    return int(round((year-mini)*(len(palette)-1)/(maxi-mini),1))

mapper = LinearColorMapper(palette=Viridis256, low=min(df['Year']), high=max(df['Year'])) # linearly map the "Viridis256" list to the [low,high] range
color_bar = ColorBar(color_mapper=mapper,location=(0,0),label_standoff=15,title='Year') # define the color bar with the linear color mapper

fig = figure(name='fig')
fig.xaxis.axis_label = 'X'
fig.yaxis.axis_label = 'Y'

for year, group in grouped:

    colo = Viridis256[ID_map(year)]
    y_lower = group['Y'] - group['err']
    y_upper = group['Y'] + group['err']

    y_band = np.append(y_lower,y_upper[::-1])
    x_band = np.append(group['X'],group['X'][::-1])

    fig.line(x='X',y='Y',color=colo,source=ColumnDataSource(group),name=str(year))
    fig.patch(x_band,y_band,color=colo,line_alpha=1,fill_alpha=0.2,name=str(year)+' band')

fig.add_layout(color_bar,'right')

def update(attr,old,new):
    fig = curdoc().select_one({"name":"fig"})

    for rend in fig.renderers:
        try:
            rend.data_source
        except AttributeError:
            pass
        else:
            if str(new) in rend.name:
                rend.visible = True
            else:
                rend.visible = False

slider = Slider(start=min_year,end=max_year,step=1,title='Year',value=min_year,width=200)
slider.on_change('value',update)

def show_all():
    fig = curdoc().select_one({"name":"fig"})

    for rend in fig.renderers:
        try:
            rend.data_source
        except AttributeError:
            pass
        else:
            rend.visible = True

button = Button(label='Show all')
button.on_click(show_all)

grid = gridplot([[fig,widgetbox(slider,button)]],toolbar_location='left')

curdoc().add_root(grid)
</code>```

I couldn't remember how to use the mapper directly to get the color while using fig.line() so I just wrote a small function that should give the same colors as the mapper used for the color bar.

Body:
Consider the beautiful graph [code first, image not showing because I have no upvotes yet]:

import pandas as np
from plotnine import *

df = pd.DataFrame([
        {'Year': 2000, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2000, 'X':2, 'Y': 2, 'err': .2},
        {'Year': 2000, 'X':3, 'Y': 3, 'err': .3},
        {'Year': 2001, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2001, 'X':2, 'Y': 4, 'err': .3},
        {'Year': 2001, 'X':3, 'Y': 9, 'err': .5},
        {'Year': 2002, 'X':1, 'Y': 1, 'err': .2},
        {'Year': 2002, 'X':2, 'Y': 8, 'err': .6},
        {'Year': 2002, 'X':3, 'Y': 27, 'err': .9},
    ])
df.set_index('Year')
df['ymin'] = df['Y'] - df['err']
df['ymax'] = df['Y'] + df['err']

(ggplot(df, aes(x='X', y='Y', group='Year', color='Year', ymin='ymin', ymax='ymax'))
+ geom_line()
+ geom_ribbon(alpha=.2)
)

Beautiful graph

How can I make an interactive version of this plot where one can use a slider to change the year being graphed? In my real data set I have 20 years of data and I would like to see how the distribution of this line, and its error bar, changes over time simply by sliding from 1997-2017. Importantly, I cannot upload the data to a server, so that rules out Plotly.

I spent several hours trying to make this work with Bokeh, but could not figure out how to make it play nice with Pandas dataframes. This seems like something that should be easy to do! And yet so many of the tutorials seem incredibly dense and hard to follow.

Is it?

Edit: Can this be done with IPython widgets?

Body:
check this code. Save it as 'script.py' and run it with bokeh serve --show script.py

It may not be the most simple way of doing it. I usually use the low-mid level api of bokeh to make my plots.

from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, LinearColorMapper, ColorBar, Slider, Button
from bokeh.palettes import Viridis256
from bokeh.layouts import gridplot, widgetbox

import pandas as pd
import numpy as np

df = pd.DataFrame([
        {'Year': 2000, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2000, 'X':2, 'Y': 2, 'err': .2},
        {'Year': 2000, 'X':3, 'Y': 3, 'err': .3},
        {'Year': 2001, 'X':1, 'Y': 1, 'err': .1},
        {'Year': 2001, 'X':2, 'Y': 4, 'err': .3},
        {'Year': 2001, 'X':3, 'Y': 9, 'err': .5},
        {'Year': 2002, 'X':1, 'Y': 1, 'err': .2},
        {'Year': 2002, 'X':2, 'Y': 8, 'err': .6},
        {'Year': 2002, 'X':3, 'Y': 27, 'err': .9},
    ])
grouped = df.groupby('Year')

max_year = max(df['Year'])
min_year = min(df['Year'])

def ID_map(year,mini=min_year,maxi=max_year,palette=Viridis256):
    return int(round((year-mini)*(len(palette)-1)/(maxi-mini),1))

mapper = LinearColorMapper(palette=Viridis256, low=min(df['Year']), high=max(df['Year'])) # linearly map the "Viridis256" list to the [low,high] range
color_bar = ColorBar(color_mapper=mapper,location=(0,0),label_standoff=15,title='Year') # define the color bar with the linear color mapper

fig = figure(name='fig')
fig.xaxis.axis_label = 'X'
fig.yaxis.axis_label = 'Y'

for year, group in grouped:

    colo = Viridis256[ID_map(year)]
    y_lower = group['Y'] - group['err']
    y_upper = group['Y'] + group['err']

    y_band = np.append(y_lower,y_upper[::-1])
    x_band = np.append(group['X'],group['X'][::-1])

    fig.line(x='X',y='Y',color=colo,source=ColumnDataSource(group),name=str(year))
    fig.patch(x_band,y_band,color=colo,line_alpha=1,fill_alpha=0.2,name=str(year)+' band')

fig.add_layout(color_bar,'right')

def update(attr,old,new):
    fig = curdoc().select_one({"name":"fig"})

    for rend in fig.renderers:
        try:
            rend.data_source
        except AttributeError:
            pass
        else:
            if str(new) in rend.name:
                rend.visible = True
            else:
                rend.visible = False

slider = Slider(start=min_year,end=max_year,step=1,title='Year',value=min_year,width=200)
slider.on_change('value',update)

def show_all():
    fig = curdoc().select_one({"name":"fig"})

    for rend in fig.renderers:
        try:
            rend.data_source
        except AttributeError:
            pass
        else:
            rend.visible = True

button = Button(label='Show all')
button.on_click(show_all)

grid = gridplot([[fig,widgetbox(slider,button)]],toolbar_location='left')

curdoc().add_root(grid)

I couldn't remember how to use the mapper directly to get the color while using fig.line() so I just wrote a small function that should give the same colors as the mapper used for the color bar.


问:
Why is my SVG path unexpectedly clipped in Chrome, Edge, and Firefox?
Consider the following SVG image code:

```<code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
    <title>Clipped Path Problem Demo</title>
    <g id="group:image">
        <defs>
            <mask id="mask">
                <rect id="rectangle:inset" x="250" y="134" width="500" height="732" fill="white"/>
            </mask>
        </defs>
        <g id="group:curves" mask="url('#mask')">
            <!-- <rect id="rectangle:filler.shape" width="1" height="1" fill="transparent"/> -->
            <path id="path:curves" d="
                M 441 327
                c -85 88 -85 175 -85 175
                c 0 88 85 175 85 175
                s 90 103 90 103
                c 85 88 85 175 85 175" fill="transparent" stroke="black" stroke-width="73"/>
        </g>
    </g>
    <g id="group:guides">
        <rect id="rectangle:guide.area:inset" x="250" y="134" width="500" height="732" fill="transparent" stroke="black" stroke-dasharray="20 10" stroke-width="1"/>
    </g>
</svg>
</code>```

(CodePen: https://codepen.io/patrickdark/full/zPEVVg/. (I added a height="500px" attribute to the pen to make it more likely to fit on screen.))

The left side of the curved path is clipped to a vertical line even though the mask is well over the size needed to contain that portion of the image.

If I insert a shape of any size with non-zero dimensions into the masked g element—such as the 1×1 transparent rectangle in the XML comment—the clipped edge is magically unclipped.

I would think this is a bug except that it’s happening in Chrome (62), Edge (41), and Firefox Developer Edition (58 Beta 4). What I would like to know is why this seemingly nonsensical clipping is occurring.

(Note: Clipping at the bottom of the curved path is intentional.)

答:
Since a mask works on color and alpha channel values (a potentially costly operation), it doesn't stretch to infinity, but rendering is clipped of by default at the object bounding box of the masked element plus 10% in every direction (defined by the attributes x, y, width, height in bounding box units).

The object bounding box although is defined not to include stroke widths. You are surpassing these limits and need to make adjustments at least to the x and width attribute of the mask.

Since this seems to be not intuitive, the general algorithm for applying a mask goes like this:

Identify the region the mask is applied to. This is always the rectangle given by the x, y, width, height attributes of the <mask> element. If, as is the default, the maskUnits attribute is given as objectBoundingBox, the coordinates are determined by the object bounding box of the element the mask is applied to. The contents of the mask are not taken into account. 0 and 1 in that coordinate system are the minimum and maximum of the joined bounding box of the masked element and all its descendants.

Superimpose the content of the mask element with the element it is applied to. As a default, the coordinate system used for placing these elements is given as maskContentUnits="userSpaceOnUse", which means the same coordinate system the masked element is drawn into.

For every point within the region defined above, multiply the opacity of the masked content with the luminance of the masking content to compute a resulting opacity of the masked element.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
    <title>Clipped Path Problem Resoved</title>
    <g id="group:image">
        <defs>
            <mask id="mask" x="-20%" width="140%">
                <rect id="rectangle:inset" x="250" y="134" width="500" height="732" fill="white"/>
            </mask>
        </defs>
        <g id="group:curves"mask="url('#mask')">

            <path id="path:curves" d="
                M 441 327
                c -85 88 -85 175 -85 175
                c 0 88 85 175 85 175
                s 90 103 90 103
                c 85 88 85 175 85 175" fill="transparent" stroke="black" stroke-width="73"/>
        </g>
    </g>
    <g id="group:guides">
        <rect id="rectangle:guide.area:inset" x="250" y="134" width="500" height="732" fill="transparent" stroke="black" stroke-dasharray="20 10" stroke-width="1"/>
    </g>
</svg>```

Body:
Consider the following SVG image code:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
    <title>Clipped Path Problem Demo</title>
    <g id="group:image">
        <defs>
            <mask id="mask">
                <rect id="rectangle:inset" x="250" y="134" width="500" height="732" fill="white"/>
            </mask>
        </defs>
        <g id="group:curves" mask="url('#mask')">

            <path id="path:curves" d="
                M 441 327
                c -85 88 -85 175 -85 175
                c 0 88 85 175 85 175
                s 90 103 90 103
                c 85 88 85 175 85 175" fill="transparent" stroke="black" stroke-width="73"/>
        </g>
    </g>
    <g id="group:guides">
        <rect id="rectangle:guide.area:inset" x="250" y="134" width="500" height="732" fill="transparent" stroke="black" stroke-dasharray="20 10" stroke-width="1"/>
    </g>
</svg>

(CodePen: https://codepen.io/patrickdark/full/zPEVVg/. (I added a height="500px" attribute to the pen to make it more likely to fit on screen.))

The left side of the curved path is clipped to a vertical line even though the mask is well over the size needed to contain that portion of the image.

If I insert a shape of any size with non-zero dimensions into the masked g element—such as the 1×1 transparent rectangle in the XML comment—the clipped edge is magically unclipped.

I would think this is a bug except that it’s happening in Chrome (62), Edge (41), and Firefox Developer Edition (58 Beta 4). What I would like to know is why this seemingly nonsensical clipping is occurring.

(Note: Clipping at the bottom of the curved path is intentional.)

Body:
Since a mask works on color and alpha channel values (a potentially costly operation), it doesn't stretch to infinity, but rendering is clipped of by default at the object bounding box of the masked element plus 10% in every direction (defined by the attributes x, y, width, height in bounding box units).

The object bounding box although is defined not to include stroke widths. You are surpassing these limits and need to make adjustments at least to the x and width attribute of the mask.

Since this seems to be not intuitive, the general algorithm for applying a mask goes like this:

Identify the region the mask is applied to. This is always the rectangle given by the x, y, width, height attributes of the <mask> element. If, as is the default, the maskUnits attribute is given as objectBoundingBox, the coordinates are determined by the object bounding box of the element the mask is applied to. The contents of the mask are not taken into account. 0 and 1 in that coordinate system are the minimum and maximum of the joined bounding box of the masked element and all its descendants.

Superimpose the content of the mask element with the element it is applied to. As a default, the coordinate system used for placing these elements is given as maskContentUnits="userSpaceOnUse", which means the same coordinate system the masked element is drawn into.

For every point within the region defined above, multiply the opacity of the masked content with the luminance of the masking content to compute a resulting opacity of the masked element.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
    <title>Clipped Path Problem Resoved</title>
    <g id="group:image">
        <defs>
            <mask id="mask" x="-20%" width="140%">
                <rect id="rectangle:inset" x="250" y="134" width="500" height="732" fill="white"/>
            </mask>
        </defs>
        <g id="group:curves"mask="url('#mask')">
            <!-- <rect id="rectangle:filler.shape" width="1" height="1" fill="transparent"/> -->
            <path id="path:curves" d="
                M 441 327
                c -85 88 -85 175 -85 175
                c 0 88 85 175 85 175
                s 90 103 90 103
                c 85 88 85 175 85 175" fill="transparent" stroke="black" stroke-width="73"/>
        </g>
    </g>
    <g id="group:guides">
        <rect id="rectangle:guide.area:inset" x="250" y="134" width="500" height="732" fill="transparent" stroke="black" stroke-dasharray="20 10" stroke-width="1"/>
    </g>
</svg>


问:
Converting struct with embedded interface into JSON
I have a struct that I want to marshal to JSON. It has a defined field called Foo (exported as foo) and a data interface field to which I want to pass a dynamic struct with additional JSON fields.

However when the data field is an interface instead of the specific struct it never gets exported as JSON. How can I make this work?

```<code>package main

import (
    "encoding/json"
    "fmt"
)

type data interface{}

type foo struct {
    Foo string `json:"foo,omitempty"`
    data
}

type bar struct {
    Bar string `json:"bar,omitempty"`
}

func main() {
    b := bar{"bar"}
    f := foo{"foo", b}

    byt, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(byt))
}
</code>```

I need to output to look like this (it needs to be flat, not nested):

```<code>{"foo": "foo", "bar": "bar"}
</code>```

答:
You could do this with a custom json.Marshaler implementation and a little bit of byte slicing.

```<code>func (f foo) MarshalJSON() ([]byte, error) {
    type goo foo
    g := goo(f)

    b1, err := json.Marshal(g)
    if err != nil {
        return nil, err
    }

    b2, err := json.Marshal(g.data)
    if err != nil {
        return nil, err
    }

    s1 := string(b1[:len(b1)-1])
    s2 := string(b2[1:])

    return []byte(s1 + ", " + s2), nil
}
</code>```

https://play.golang.org/p/NYTNWIL-xu

Please note that this is not checking whether the bytes can actually be sliced and it does also not consider the possible case of the data field being a slice or an array, which i'm unsure how you would want that flattened anyway.

Body:
I have a struct that I want to marshal to JSON. It has a defined field called Foo (exported as foo) and a data interface field to which I want to pass a dynamic struct with additional JSON fields.

However when the data field is an interface instead of the specific struct it never gets exported as JSON. How can I make this work?

package main

import (
    "encoding/json"
    "fmt"
)

type data interface{}

type foo struct {
    Foo string `json:"foo,omitempty"`
    data
}

type bar struct {
    Bar string `json:"bar,omitempty"`
}

func main() {
    b := bar{"bar"}
    f := foo{"foo", b}

    byt, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(byt))
}

I need to output to look like this (it needs to be flat, not nested):

{"foo": "foo", "bar": "bar"}

Body:
You could do this with a custom json.Marshaler implementation and a little bit of byte slicing.

func (f foo) MarshalJSON() ([]byte, error) {
    type goo foo
    g := goo(f)

    b1, err := json.Marshal(g)
    if err != nil {
        return nil, err
    }

    b2, err := json.Marshal(g.data)
    if err != nil {
        return nil, err
    }

    s1 := string(b1[:len(b1)-1])
    s2 := string(b2[1:])

    return []byte(s1 + ", " + s2), nil
}

https://play.golang.org/p/NYTNWIL-xu

Please note that this is not checking whether the bytes can actually be sliced and it does also not consider the possible case of the data field being a slice or an array, which i'm unsure how you would want that flattened anyway.


问:
Google DataStudio: Reuse existing connectors inside a new connector which I'm currently developing
I need pull data from "Google Sheets" and "Analytics", for which I'm creating a connector, and I would like to know if it's possible re-use existing "Google Analytics" & "Google Sheets" provided by DataStudio.</p>

答:
Re-using native connectors inside a Community Connector is not possible at the moment.

However, you can achieve the same result by using Apps Script Advanced Services. Most of the native connectors in Data Studio have a corresponding Advanced Service in Apps Script.

For your specific use case, you can use the Analytics Services and the Sheets Service. Before using them in your code, make sure that you follow the instructions to enable the advanced services. The Fusion Table Community Connector is an Open Source example that shows how to use an advanced service in a Community Connector.

ContentLicense: CC BY-SA 4.0


问:
No password for psExec works, but empty string to password flag does not
I'm using a program called psExec to remotely connect to a machine and start an interactive program.

The machine I'm connecting to, does not have a password.

So if I run this:

```<code>psExec \\Computer_Name -u User -i -d calc.exe
</code>```

It prompts me for a password:

```<code>Password:
</code>```

I just hit enter(since the computer doesn't have a password), and it works.

I don't want to have to hit enter every time, because I am writing a script.

So I tried this:

```<code>psExec \\Computer_Name -u User -p -i -d calc.exe
</code>```

and this:

```<code>psExec \\Computer_Name -u User -p"" -i -d calc.exe
</code>```

and this:

```<code>psExec \\Computer_Name -u User -p'' -i -d calc.exe
</code>```

and this:

```<code>psExec \\Computer_Name -u User -p "" -i -d calc.exe
</code>```

and this:

```<code>psExec \\Computer_Name -u User -p '' -i -d calc.exe
</code>```

but no matter what, specifying the p flag results in a "Wrong Username or Password error."

How can I tell my script to either press enter automatically, or automate psExec to connect automatically without a password?

I'm in PowerShell if that is relevant.

答:
It seems to work if you put a ~ for the password in powershell.

```<code>./psexec -i -u domain\gmsa$ -p ~ notepad.exe
</code>```

My use case was getting it to skip the enter keypress when using psexec to run something as a group managed service account (gMSA).

Body:
I'm using a program called psExec to remotely connect to a machine and start an interactive program.

The machine I'm connecting to, does not have a password.

So if I run this:

psExec \\Computer_Name -u User -i -d calc.exe

It prompts me for a password:

Password:

I just hit enter(since the computer doesn't have a password), and it works.

I don't want to have to hit enter every time, because I am writing a script.

So I tried this:

psExec \\Computer_Name -u User -p -i -d calc.exe

and this:

psExec \\Computer_Name -u User -p"" -i -d calc.exe

and this:

psExec \\Computer_Name -u User -p'' -i -d calc.exe

and this:

psExec \\Computer_Name -u User -p "" -i -d calc.exe

and this:

psExec \\Computer_Name -u User -p '' -i -d calc.exe

but no matter what, specifying the p flag results in a "Wrong Username or Password error."

How can I tell my script to either press enter automatically, or automate psExec to connect automatically without a password?

I'm in PowerShell if that is relevant.

Body:
It seems to work if you put a ~ for the password in powershell.

./psexec -i -u domain\gmsa$ -p ~ notepad.exe

My use case was getting it to skip the enter keypress when using psexec to run something as a group managed service account (gMSA).


问:
must capture output of a function that has no return statement
I'm using the NLTK package and it has a function that tells me whether a given sentence is positive, negative, or neutral:

```<code>from nltk.sentiment.util import demo_liu_hu_lexicon

demo_liu_hu_lexicon('Today is a an awesome, happy day')
>>> Positive
</code>```

Problem is, that function doesn't have a return statement - it just prints "Positive", "Negative", or "Neutral" to stdout. All it returns - implicitly - is a NoneType object. (Here's the function's source code.)

Is there any way I can capture this output (other than messing with the NLTK source code on my machine)?

答:
```<code>import sys
from io import StringIO

class capt_stdout:
    def __init__(self):
        self._stdout = None
        self._string_io = None

    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._string_io = StringIO()
        return self

    def __exit__(self, type, value, traceback):
        sys.stdout = self._stdout

    @property
    def string(self):
        return self._string_io.getvalue()
</code>```

use like this:

```<code>with capt_stdout() as out:
    demo_liu_hu_lexicon('Today is a an awesome, happy day')
    demo_liu_hu_lexicon_output = out.string
</code>```

Body:
I'm using the NLTK package and it has a function that tells me whether a given sentence is positive, negative, or neutral:

from nltk.sentiment.util import demo_liu_hu_lexicon

demo_liu_hu_lexicon('Today is a an awesome, happy day')
>>> Positive

Problem is, that function doesn't have a return statement - it just prints "Positive", "Negative", or "Neutral" to stdout. All it returns - implicitly - is a NoneType object. (Here's the function's source code.)

Is there any way I can capture this output (other than messing with the NLTK source code on my machine)?

Body:
import sys
from io import StringIO

class capt_stdout:
    def __init__(self):
        self._stdout = None
        self._string_io = None

    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._string_io = StringIO()
        return self

    def __exit__(self, type, value, traceback):
        sys.stdout = self._stdout

    @property
    def string(self):
        return self._string_io.getvalue()

use like this:

with capt_stdout() as out:
    demo_liu_hu_lexicon('Today is a an awesome, happy day')
    demo_liu_hu_lexicon_output = out.string


问:
Camel with XA, execute a route or process only after all retries exhausted
I would like to know if there is a way to tell camel to execute either/preferably a route or some processing that allows me to send to a route only once all the retries are exhausted. I need to be able to send out alerts when things fail but I dont want to send out 5 alerts just because a route retries 5 times and fails.

thanks
Paul

答:
You can use an ErrorHandler configured with a RedeliveryPolicy. The way it works is that you refer to the ErrorHandler in either your route or your CamelContext. If you use the Dead Letter Channel you can retry, say, five times and then send the message to a different route which stores the message in a JMS queue.

```<code><bean id="redeliveryPolicyConfig" class="org.apache.camel.processor.RedeliveryPolicy">
    <property name="maximumRedeliveries" value="5"/>
</bean>

<bean id="errorHandler" class="org.apache.camel.builder.DeadLetterChannelBuilder">
   <property name="deadLetterUri" value="direct:myErrorRoute"/>
   <property name="redeliveryPolicy" ref="redeliveryPolicyConfig"/>
</bean>

<camelContext errorHandlerRef="errorHandler">
    ...
</camelContext>
</code>```

The above example would retry all routes in the context five times before sending the message to the direct:myErrorRoute route where you could, for instance, log the failed message along with the exception and stack trace and/or send it to a DeadLetterQueue.

Body:
You can use an ErrorHandler configured with a RedeliveryPolicy. The way it works is that you refer to the ErrorHandler in either your route or your CamelContext. If you use the Dead Letter Channel you can retry, say, five times and then send the message to a different route which stores the message in a JMS queue.

<bean id="redeliveryPolicyConfig" class="org.apache.camel.processor.RedeliveryPolicy">
    <property name="maximumRedeliveries" value="5"/>
</bean>

<bean id="errorHandler" class="org.apache.camel.builder.DeadLetterChannelBuilder">
   <property name="deadLetterUri" value="direct:myErrorRoute"/>
   <property name="redeliveryPolicy" ref="redeliveryPolicyConfig"/>
</bean>

<camelContext errorHandlerRef="errorHandler">
    ...
</camelContext>

The above example would retry all routes in the context five times before sending the message to the direct:myErrorRoute route where you could, for instance, log the failed message along with the exception and stack trace and/or send it to a DeadLetterQueue.


问:
If network speed is less than 1kb/s then why SFTP connection fails more frequently
If network speed is less than 1kb/s then why SFTP connection fails more frequently.

If i increase network speed then no sftp connection fails.

答:
This sounds like a timeout problem. Your slower connection probably causes the SSH connection to reset. Try adding

```<code>ServerAliveInterval 60
</code>```

in your ssh_config.

ContentLicense: CC BY-SA 2.5

Body:
This sounds like a timeout problem. Your slower connection probably causes the SSH connection to reset. Try adding

ServerAliveInterval 60

in your ssh_config.


问:
Webpack: Cannot destructure property `curry` of 'undefined' or 'null'
After compiling my application using webpack & babel-loader for the browser, the following error appears right off the bat before the main function starts:

```<code>Uncaught TypeError: Cannot destructure property `curry` of 'undefined' or 'null'.
    at Object../node_modules/@qzdio/f/lib/combinators/sync.js (index-c1596672f4.js:formatted:268)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/combinators/index.js (index-c1596672f4.js:formatted:251)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/index.js (index-c1596672f4.js:formatted:723)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../dist/graph/visualizer/src/index.js (index-c1596672f4.js:formatted:9)
    at n (runtime-74c3f0da77.js:formatted:10)
    at window.webpackJsonp (runtime-74c3f0da77.js:formatted:26)
    at index-c1596672f4.js:formatted:1
</code>```

The faulty code is the ES5 transpilation of the following:

```<code>import R from 'ramda';
const { curry } = R;

// I :: a -> a
const I = (x) => x;
...
</code>```

Where the said code is from a private functional library that relies on ramda and bluebird. The library is used and working under Node.js 8.9.1.

The webpack config used is straight up from philipwalton's webpack-esnext-boilerplate (great to start with :D)

Versions:

babel-cli: ^6.26.0,

babel-loader: ^7.1.2,

webpack: ^3.8.1,

Browser: Google Chrome Version 62.0.3202.89 (Official Build) (64-bit),

Node.js: 8.9.1,

npm: 5.5.1

What is the source of the error and how can it be resolved?

Cheers ✨

答:
If you really want all the exported values in one object, you can do the following</p>

```<code>import * as R from 'ramda';
const { curry } = R;
</code>```

Body:
After compiling my application using webpack & babel-loader for the browser, the following error appears right off the bat before the main function starts:

Uncaught TypeError: Cannot destructure property `curry` of 'undefined' or 'null'.
    at Object../node_modules/@qzdio/f/lib/combinators/sync.js (index-c1596672f4.js:formatted:268)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/combinators/index.js (index-c1596672f4.js:formatted:251)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/index.js (index-c1596672f4.js:formatted:723)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../dist/graph/visualizer/src/index.js (index-c1596672f4.js:formatted:9)
    at n (runtime-74c3f0da77.js:formatted:10)
    at window.webpackJsonp (runtime-74c3f0da77.js:formatted:26)
    at index-c1596672f4.js:formatted:1

The faulty code is the ES5 transpilation of the following:

import R from 'ramda';
const { curry } = R;

// I :: a -> a
const I = (x) => x;
...

Where the said code is from a private functional library that relies on ramda and bluebird. The library is used and working under Node.js 8.9.1.

The webpack config used is straight up from philipwalton's webpack-esnext-boilerplate (great to start with :D)

Versions:

babel-cli: ^6.26.0,

babel-loader: ^7.1.2,

webpack: ^3.8.1,

Browser: Google Chrome Version 62.0.3202.89 (Official Build) (64-bit),

Node.js: 8.9.1,

npm: 5.5.1

What is the source of the error and how can it be resolved?

Cheers ✨

Body:
If you really want all the exported values in one object, you can do the following

import * as R from 'ramda';
const { curry } = R;


问:
update_attributes validation fails though values are correct
I have in my model

```<code>class Account < ActiveRecord::Base
 validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
 validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?

end
</code>```

when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false
in my controller I have

```<code>@account.update_attributes({:name => "king", :amount => "1223"}
</code>```

the save fails and when I check errors I get

```<code>@account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}
</code>```

Strong Params are not an issue because I have
     def self.params
          params.require(:account).permit!
     end

I have no idea why it fails though the value are present and correct.

答:
The issue that was happening was for one reason. The code was inheriting  from a class that had:

```<code>slef.reload
</code>```

in one of the function that were being called during validations.

so every time we try to update the update failed because once that validation was hit it reloaded the original values from database and ignored new values which if old values are empty is just a head scratcher.

Thanks everyone for the help

Body:
I have in my model

class Account < ActiveRecord::Base
 validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
 validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?

end

when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false
in my controller I have

@account.update_attributes({:name => "king", :amount => "1223"}

the save fails and when I check errors I get

@account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}

Strong Params are not an issue because I have
     def self.params
          params.require(:account).permit!
     end

I have no idea why it fails though the value are present and correct.

Body:
The issue that was happening was for one reason. The code was inheriting  from a class that had:

slef.reload

in one of the function that were being called during validations.

so every time we try to update the update failed because once that validation was hit it reloaded the original values from database and ignored new values which if old values are empty is just a head scratcher.

Thanks everyone for the help


问:
How to apply multiple arguments within find_all function?
Is it possible to use multiple arguments in a single soup.find_all function to find any particular item from certain elements? The process I wanna know about can easily be applied if i go for soup.select option. To be more specific: look at the below example:

```<code>from bs4 import BeautifulSoup

html_element='''
<div class="browse-movie-bottom">
    <a href="https://yts.ag/movie/logan-lucky-2017" class="browse-movie-title">Logan Lucky</a>
    <div class="browse-movie-year">2017</div>
    <div class="browse-movie-tags">
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>
    </div>
</div>
'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.find_all(class_='browse-movie-bottom')[0].find_all(class_='browse-movie-tags')[0].find_all("a"):
# for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)
</code>```

On the one hand, I parsed movie tags using soup.select() which you know can be used in such a way so that all the arguments can fit together in a single brace.

On the other hand, I did the same using soup.find_all() which required three different arguments in three different braces. The results are same though.

My question is: whether it is possible to create any expression using soup.find_all() function which will include multiple arguments in a single brace as i did with soup.select(). Something like below:

This is a faulty one but it will give you an idea as to what type of expression i'm after:

```<code>soup.find_all({'class':'browse-movie-bottom'},{'class':'browse-movie-tags'},"a")[0]
</code>```

However, the valid search results were:

```<code>Logan Lucky 720p
Logan Lucky 1080p
</code>```

答:
You could pass a list to class_ atribute, this way you save one call to find_all, but you need to call it again with "a", and allways you can just call like soup("a") using the shortcut to find_all:

```<code>from bs4 import BeautifulSoup
html_element='''
<div class="browse-movie-bottom">
    <a href="https://yts.ag/movie/logan-lucky-2017" class="browse-movie-title">Logan Lucky</a>
    <div class="browse-movie-year">2017</div>
    <div class="browse-movie-tags">
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>
    </div>
</div>
'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.findAll(class_=['browse-movie-bottom', 'browse-movie-tags'])[1]('a'):
#for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)
</code>```

Body:
Is it possible to use multiple arguments in a single soup.find_all function to find any particular item from certain elements? The process I wanna know about can easily be applied if i go for soup.select option. To be more specific: look at the below example:

from bs4 import BeautifulSoup

html_element='''

    Logan Lucky

2017

        Logan Lucky 720p
        Logan Lucky 1080p

'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.find_all(class_='browse-movie-bottom')[0].find_all(class_='browse-movie-tags')[0].find_all("a"):
# for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)

On the one hand, I parsed movie tags using soup.select() which you know can be used in such a way so that all the arguments can fit together in a single brace.

On the other hand, I did the same using soup.find_all() which required three different arguments in three different braces. The results are same though.

My question is: whether it is possible to create any expression using soup.find_all() function which will include multiple arguments in a single brace as i did with soup.select(). Something like below:

This is a faulty one but it will give you an idea as to what type of expression i'm after:

soup.find_all({'class':'browse-movie-bottom'},{'class':'browse-movie-tags'},"a")[0]

However, the valid search results were:

Logan Lucky 720p
Logan Lucky 1080p

Body:
You could pass a list to class_ atribute, this way you save one call to find_all, but you need to call it again with "a", and allways you can just call like soup("a") using the shortcut to find_all:

from bs4 import BeautifulSoup
html_element='''
<div class="browse-movie-bottom">
    <a href="https://yts.ag/movie/logan-lucky-2017" class="browse-movie-title">Logan Lucky</a>
    <div class="browse-movie-year">2017</div>
    <div class="browse-movie-tags">
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>
    </div>
</div>
'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.findAll(class_=['browse-movie-bottom', 'browse-movie-tags'])[1]('a'):
#for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)


问:
Rounding To Nearest Bin
I have a list of revenue charges that I need to round up or down to the nearest bin.

For example, if the only products sold cost the following:

```<code>import numpy as np
bins = np.array([9.95,19.95,79.95])
</code>```

and I have a few charges like this:

```<code>x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])
</code>```

I followed this example, which is definitely the closest solution:

```<code>y = np.take(bins,np.digitize(x,bins))
</code>```

I thought leaving the right= parameter to the default for np.digitize  would accomplish what I needed, but the results are still rounded up:

```<code>In [10]: y
Out[10]: array([  9.95,   9.95,  19.95,  19.95,  79.95])
</code>```

In my particular case, I need to round up or down to the nearest bin. For example, the $12.50 charge is only $2.55 away from $9.95, but the chosen option, $19.95, is $7.45 away.

EDIT

While one answer in the solution I linked to can round both up/down, it appears that method can return inconsistent results, hence this new post.

答:
If you want to round to certain values you need to split at their midpoints. Like so:

```<code>import numpy as np

bins = np.array([9.95,19.95,79.95])
centers = (bins[1:]+bins[:-1])/2

x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])
res = bins[np.digitize(x, centers)]
</code>```

Gives

```<code>array([  9.95,   9.95,   9.95,  19.95,  19.95])
</code>```

Title: Rounding To Nearest Bin

Body:
I have a list of revenue charges that I need to round up or down to the nearest bin.

For example, if the only products sold cost the following:

import numpy as np
bins = np.array([9.95,19.95,79.95])

and I have a few charges like this:

x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])

I followed this example, which is definitely the closest solution:

y = np.take(bins,np.digitize(x,bins))

I thought leaving the right= parameter to the default for np.digitize  would accomplish what I needed, but the results are still rounded up:

In [10]: y
Out[10]: array([  9.95,   9.95,  19.95,  19.95,  79.95])

In my particular case, I need to round up or down to the nearest bin. For example, the $12.50 charge is only $2.55 away from $9.95, but the chosen option, $19.95, is $7.45 away.

EDIT

While one answer in the solution I linked to can round both up/down, it appears that method can return inconsistent results, hence this new post.

Body:
If you want to round to certain values you need to split at their midpoints. Like so:

import numpy as np

bins = np.array([9.95,19.95,79.95])
centers = (bins[1:]+bins[:-1])/2

x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])
res = bins[np.digitize(x, centers)]

Gives

array([  9.95,   9.95,   9.95,  19.95,  19.95])


问:
C# multiple increments
I have, code who do for me "x + y = z"

```<code>if (command.Contains("+")) // string polecenie = "";'
{
    polecenie = "{" + command + ")";
    polecenie = polecenie.Replace("+", "}(");
    double a = Convert.ToDouble(Between(polecenie, "{", "}"));
    double b = Convert.ToDouble(Between(polecenie, "(", ")"));
    double wyn = a + b;
    richTextBox1.Text += a + " + " + b + " is " + wyn + "\r\n";
}
</code>```

And when 'command' is "4+5","3 + 4" or something like this code works, but when i try to do "4 + 3 + 23" it don't work. Final string with starting 'command' "4+5+6", polecenie is: "{4}(5}(6)"... The Between Method:

```<code>public string Between(string content, string First, string Last)
{
    string end = "";
    int Plc1 = content.IndexOf(First) + First.Length;
    int Plc2 = content.IndexOf(Last);
    end = content.Substring(Plc1, Plc2 - Plc1);
    return end;
}
</code>```

How can I do that? (I want it to work with all possible additions ("4+4","34+5+54","43+4+65+54"...)

答:
You could use the DataTable object to not re-invent the wheel.

```<code>richTextBox1.Text = string.Format("{0} is {1}\r\n", command,
    (new System.Data.DataTable()).Compute(command, string.Empty));
</code>```

This would support +, -, *, / and % (mod) operators. For more: https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx

Title: C# multiple increments

Body:
I have, code who do for me "x + y = z"

if (command.Contains("+")) // string polecenie = "";'
{
    polecenie = "{" + command + ")";
    polecenie = polecenie.Replace("+", "}(");
    double a = Convert.ToDouble(Between(polecenie, "{", "}"));
    double b = Convert.ToDouble(Between(polecenie, "(", ")"));
    double wyn = a + b;
    richTextBox1.Text += a + " + " + b + " is " + wyn + "\r\n";
}

And when 'command' is "4+5","3 + 4" or something like this code works, but when i try to do "4 + 3 + 23" it don't work. Final string with starting 'command' "4+5+6", polecenie is: "{4}(5}(6)"... The Between Method:

public string Between(string content, string First, string Last)
{
    string end = "";
    int Plc1 = content.IndexOf(First) + First.Length;
    int Plc2 = content.IndexOf(Last);
    end = content.Substring(Plc1, Plc2 - Plc1);
    return end;
}

How can I do that? (I want it to work with all possible additions ("4+4","34+5+54","43+4+65+54"...)

Body:
You could use the DataTable object to not re-invent the wheel.

richTextBox1.Text = string.Format("{0} is {1}\r\n", command,
    (new System.Data.DataTable()).Compute(command, string.Empty));

This would support +, -, *, / and % (mod) operators. For more: https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx


问:
Shutting down daemon thread properly
I've created my own thread class that will be used in a threadpool as follows:

```<code>class SendFilesThread(threading.Thread):
    execute = True

    def __init__(self, port, rate, fileQueue):
        self.daemon = True
        self.fileQueue = fileQueue
        #Other initialization

    def run(self):
        while SendFilesThread.execute == True or not self.fileQueue.empty():
            self.filename = self.fileQueue.get()
            #some file processing
            self.fileQueue.task_done()

    @staticmethod
    def terminate():
        SendFilesThread.execute = False
</code>```

In the main thread of the program, after I have processed all of my files, I try and shut down the threadpool as follows:

```<code>SendFilesThread.terminate()
for t in threadPool:
    if t.is_alive():
        t.join()
exit()
</code>```

My understanding is that if I call join() it will block the calling thread, in this case the main thread, from continuing until the joined thread finishes processing. My issue is that despite the thread completing, it never returns to the main thread and the program just hangs. Am I doing anything wrong when shutting down my threadpool?

答:
if fileQueue is a multiprocessing.Queue or queue.Queue, then its .get() method will block until something arrives in the queue. Try using .get_nowait() but you may have to wrap it in a try block if you want execution to continue even when the queue is empty.

```<code>try:
    self.filename = self.fileQueue.get_nowait()
except queue.Empty:
    time.sleep(1)
</code>```

see queue docs for more

Title: Shutting down daemon thread properly

Body:
I've created my own thread class that will be used in a threadpool as follows:

class SendFilesThread(threading.Thread):
    execute = True

    def __init__(self, port, rate, fileQueue):
        self.daemon = True
        self.fileQueue = fileQueue
        #Other initialization

    def run(self):
        while SendFilesThread.execute == True or not self.fileQueue.empty():
            self.filename = self.fileQueue.get()
            #some file processing
            self.fileQueue.task_done()

    @staticmethod
    def terminate():
        SendFilesThread.execute = False

In the main thread of the program, after I have processed all of my files, I try and shut down the threadpool as follows:

SendFilesThread.terminate()
for t in threadPool:
    if t.is_alive():
        t.join()
exit()

My understanding is that if I call join() it will block the calling thread, in this case the main thread, from continuing until the joined thread finishes processing. My issue is that despite the thread completing, it never returns to the main thread and the program just hangs. Am I doing anything wrong when shutting down my threadpool?

Body:
if fileQueue is a multiprocessing.Queue or queue.Queue, then its .get() method will block until something arrives in the queue. Try using .get_nowait() but you may have to wrap it in a try block if you want execution to continue even when the queue is empty.

try:
    self.filename = self.fileQueue.get_nowait()
except queue.Empty:
    time.sleep(1)

see queue docs for more


问:
How to set function converted from number into html span tag
I need help with the last line in this. I need to take the current month,
picked from the getMonthText var and have it be in the

```<code><h1><span id="month_year"> </span></h1>
</code>```

Beginning of code.
My issue is at the bottom
This part turns the month number into a name.

```<code>    var getMonthText = function(currentMonth) {
        if (currentMonth === 0) { return "January"; }
        else if (currentMonth === 1) { return "February"; }
        else if (currentMonth === 2) { return "March"; }
        else if (currentMonth === 3) { return "April"; }
        else if (currentMonth === 4) { return "May"; }
        else if (currentMonth === 5) { return "June"; }
        else if (currentMonth === 6) { return "July"; }
        else if (currentMonth === 7) { return "August"; }
        else if (currentMonth === 8) { return "September"; }
        else if (currentMonth === 9) { return "October"; }
        else if (currentMonth === 10) { return "November"; }
        else if (currentMonth === 11) { return "December"; }
    };
</code>```

After that and some other code
......
This is the problem area

```<code>    $("#month-year").html(getMonthText);  <-- set it to the html ***This is the part I'm having trouble with, even though it should be simple.
</code>```

Thanks for any/all help.

答:
Your function works, you just called it wrong way. See example:

var getMonthText = function(currentMonth) {
    if (currentMonth === 0) { return "January"; }
    else if (currentMonth === 1) { return "February"; }
    else if (currentMonth === 2) { return "March"; }
    else if (currentMonth === 3) { return "April"; }
    else if (currentMonth === 4) { return "May"; }
    else if (currentMonth === 5) { return "June"; }
    else if (currentMonth === 6) { return "July"; }
    else if (currentMonth === 7) { return "August"; }
    else if (currentMonth === 8) { return "September"; }
    else if (currentMonth === 9) { return "October"; }
    else if (currentMonth === 10) { return "November"; }
    else if (currentMonth === 11) { return "December"; }
};

$("#month-year").text(getMonthText(0));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="month-year"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I need help with the last line in this. I need to take the current month,
picked from the getMonthText var and have it be in the

Beginning of code.
My issue is at the bottom
This part turns the month number into a name.

    var getMonthText = function(currentMonth) {
        if (currentMonth === 0) { return "January"; }
        else if (currentMonth === 1) { return "February"; }
        else if (currentMonth === 2) { return "March"; }
        else if (currentMonth === 3) { return "April"; }
        else if (currentMonth === 4) { return "May"; }
        else if (currentMonth === 5) { return "June"; }
        else if (currentMonth === 6) { return "July"; }
        else if (currentMonth === 7) { return "August"; }
        else if (currentMonth === 8) { return "September"; }
        else if (currentMonth === 9) { return "October"; }
        else if (currentMonth === 10) { return "November"; }
        else if (currentMonth === 11) { return "December"; }
    };

After that and some other code
......
This is the problem area

    $("#month-year").html(getMonthText);  <-- set it to the html ***This is the part I'm having trouble with, even though it should be simple.

Thanks for any/all help.

Body:
Your function works, you just called it wrong way. See example:

var getMonthText = function(currentMonth) {
    if (currentMonth === 0) { return "January"; }
    else if (currentMonth === 1) { return "February"; }
    else if (currentMonth === 2) { return "March"; }
    else if (currentMonth === 3) { return "April"; }
    else if (currentMonth === 4) { return "May"; }
    else if (currentMonth === 5) { return "June"; }
    else if (currentMonth === 6) { return "July"; }
    else if (currentMonth === 7) { return "August"; }
    else if (currentMonth === 8) { return "September"; }
    else if (currentMonth === 9) { return "October"; }
    else if (currentMonth === 10) { return "November"; }
    else if (currentMonth === 11) { return "December"; }
};

$("#month-year").text(getMonthText(0));

<div id="month-year"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Do I have to start Elastic search?
If Elastic Search is always running on port:9200, do I have to start it each time I use it?

I am using Linux, MAC and Windows, in a nut shell I run command "bin/elastic" or another variation based on OS commands and it usually "starts" Elastic Search.

I just want to know why its always running on port:9200 and if I need too start Elastic each time I boot up a Operation System.

答:
you download elasticsearch.zip and unzip it and run with "bin/elasticsearch"

you can download deb (for Debian or Ubuntu Linux) or rpm (for redhat or centos) version and install it as service for example in centos:

```<code>sudo wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.0.0.rpm
sudo rpm -ivh elasticsearch-6.0.0.rpm
sudo systemctl start elasticsearch.service
sudo systemctl enable elasticsearch.service // for running after boot
</code>```

if you want to change the default port of elastic you must edit the elasticsearch.yml file. you can find this file in the manual running in config/elasticsearch.yml and in installation as service in centos in the /etc/elasticsearch/elasticsearch.yml

you can uncomment this line:

```<code>#http.port: 9200
</code>```

and change port for example:

```<code>http.port: 9900
</code>```

Title: Do I have to start Elastic search?

Body:
you download elasticsearch.zip and unzip it and run with "bin/elasticsearch"

you can download deb (for Debian or Ubuntu Linux) or rpm (for redhat or centos) version and install it as service for example in centos:

sudo wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.0.0.rpm
sudo rpm -ivh elasticsearch-6.0.0.rpm
sudo systemctl start elasticsearch.service
sudo systemctl enable elasticsearch.service // for running after boot

if you want to change the default port of elastic you must edit the elasticsearch.yml file. you can find this file in the manual running in config/elasticsearch.yml and in installation as service in centos in the /etc/elasticsearch/elasticsearch.yml

you can uncomment this line:

#http.port: 9200

and change port for example:

http.port: 9900


问:
rearrange associative array based on unique value php
Given this:

```<code>array("Peter"=>"Marketing", "Clark"=>"Accounts", "John"=>"Accounts");
</code>```

I would like to get an array with following result:

```<code>array(2) { ["Marketing"]=> array(1) { [0]=> "Peter" } ["Accounts"]=> array(2) { [0]=> "Clark" [1]=> "John" } }
</code>```

What i have tried so far ->

```<code>$rearrange = array();
foreach($array as $key => $val) {
  if(array_key_exists($key,$array)) {
     $rearrange[$value] = $key;
  }
 }
</code>```

答:
Not sure why the array_key_exists but you almost had it:

```<code>foreach($array as $key => $val) {
    $rearrange[$val][] = $key;
}
</code>```

You foreach as $val but then use $value which doesn't exist

You need to dynamically append a new element []

Body:
Given this:

array("Peter"=>"Marketing", "Clark"=>"Accounts", "John"=>"Accounts");

I would like to get an array with following result:

array(2) { ["Marketing"]=> array(1) { [0]=> "Peter" } ["Accounts"]=> array(2) { [0]=> "Clark" [1]=> "John" } }

What i have tried so far ->

$rearrange = array();
foreach($array as $key => $val) {
  if(array_key_exists($key,$array)) {
     $rearrange[$value] = $key;
  }
 }

Body:
Not sure why the array_key_exists but you almost had it:

foreach($array as $key => $val) {
    $rearrange[$val][] = $key;
}

You foreach as $val but then use $value which doesn't exist

You need to dynamically append a new element []


问:
java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library
I have two web-applications which need to run on Tomcat 6, MS SQL 2008 and JTDS-1.2.2 as driver.

If I start only one web application everything is working fine, but as soon as I start the second one I get the following error (it does not matter the order):

```<code>java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library
</code>```

Of course, the library ntlmauth.dll is under C:\WINDOWS\system32

It seems that the second application which starts is not able to find the ntlmauth.dll for the single sign on.

答:
This is the solution:

Download the jTDS driver, unzip it, and copy x86\SSO\ntlmauth.dll to jdk\jre\bin.

This should solve your issue.

Edit:

Without the JDK installed the path for me was C:\Program Files\Java\jre7\bin\ntlmauth.dll

jTDS must be able to load the native SPPI library (ntlmauth.dll). Place this DLL anywhere in the system path (defined by the PATH system variable) and you're all set.

Body:
I have two web-applications which need to run on Tomcat 6, MS SQL 2008 and JTDS-1.2.2 as driver.

If I start only one web application everything is working fine, but as soon as I start the second one I get the following error (it does not matter the order):

java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library

Of course, the library ntlmauth.dll is under C:\WINDOWS\system32

It seems that the second application which starts is not able to find the ntlmauth.dll for the single sign on.


答:
You are missing the value your passing to the function: getMonthText(2) the (value) is missing.

You also have a type error. your html id is month_year but your jquery is month-year

var getMonthText = function(currentMonth) {
  if (currentMonth === 0) {
    return "January";
  } else if (currentMonth === 1) {
    return "February";
  } else if (currentMonth === 2) {
    return "March";
  } else if (currentMonth === 3) {
    return "April";
  } else if (currentMonth === 4) {
    return "May";
  } else if (currentMonth === 5) {
    return "June";
  } else if (currentMonth === 6) {
    return "July";
  } else if (currentMonth === 7) {
    return "August";
  } else if (currentMonth === 8) {
    return "September";
  } else if (currentMonth === 9) {
    return "October";
  } else if (currentMonth === 10) {
    return "November";
  } else if (currentMonth === 11) {
    return "December";
  }
};
$("#month_year").html(getMonthText(2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span id="month_year"> </span></h1></code>```

Title: How to set function converted from number into html span tag

Body:
You are missing the value your passing to the function: getMonthText(2) the (value) is missing.

You also have a type error. your html id is month_year but your jquery is month-year

var getMonthText = function(currentMonth) {
  if (currentMonth === 0) {
    return "January";
  } else if (currentMonth === 1) {
    return "February";
  } else if (currentMonth === 2) {
    return "March";
  } else if (currentMonth === 3) {
    return "April";
  } else if (currentMonth === 4) {
    return "May";
  } else if (currentMonth === 5) {
    return "June";
  } else if (currentMonth === 6) {
    return "July";
  } else if (currentMonth === 7) {
    return "August";
  } else if (currentMonth === 8) {
    return "September";
  } else if (currentMonth === 9) {
    return "October";
  } else if (currentMonth === 10) {
    return "November";
  } else if (currentMonth === 11) {
    return "December";
  }
};
$("#month_year").html(getMonthText(2));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span id="month_year">&nbsp;</span></h1>


问:
selecting not None value from a dataframe column
I would like to use the fillna function to fill None value of a column with its own first most frequent value that is not None or nan.

Input DF:

```<code>Col_A
a
None
None
c
c
d
d
</code>```

The output Dataframe could be either:

```<code>Col_A
a
c
c
c
c
d
d
</code>```

Any suggestion would be very appreciated.
Many Thanks, Best Regards,
Carlo

答:
To address 'None', you need to use replace then fillna much like @COLDSPEED suggests:

```<code>dr = df.Col_A.replace('None',np.nan)
dr.fillna(dr.dropna().value_counts().index[0])
</code>```

Output:

```<code>0    a
1    d
2    d
3    c
4    c
5    d
6    d
Name: Col_A, dtype: object
</code>```

Body:
I would like to use the fillna function to fill None value of a column with its own first most frequent value that is not None or nan.

Input DF:

Col_A
a
None
None
c
c
d
d

The output Dataframe could be either:

Col_A
a
c
c
c
c
d
d

Any suggestion would be very appreciated.
Many Thanks, Best Regards,
Carlo

Body:
To address 'None', you need to use replace then fillna much like @COLDSPEED suggests:

dr = df.Col_A.replace('None',np.nan)
dr.fillna(dr.dropna().value_counts().index[0])

Output:

0    a
1    d
2    d
3    c
4    c
5    d
6    d
Name: Col_A, dtype: object


问:
Acumatica: CSV Data provider - Ignore lines in header
I have a file with payment info from a PSP an would like to use an Import scenario for this.

Problem is, the file includes a header before the actual column headings. Could you ignore the first lines in some way?

File header and column headers below:

Transaktionsrapport (): Debiterade transaktioner

Rapporten genererades:  16/11-2017 kl. 04:25:07

Transaktionsperiod:
  Startdatum: 15/11-2017 kl. 00:00:00
  Slutdatum: 15/11-2017 kl. 23:59:59

Ordernr,Transaktionsnr,Belopp i SEK ,Belopp,Valuta,Avgift,Korttyp,Tidpunkt f�r auktorisation,Debiteringstidpunkt,Tidpunkt f�r �terbetalning,Avtal,Orderinformation
187411_171115064526,196621321,5450.00,3210.00,752,0.00,MC(SE),15/11-2017 kl. 06:46:51 ,15/11-2017 kl. 06:49:17 ,,EULI,

答:
There is a skip headers functionality when Import Scenario is consumed.

Is this something you can use to resolve your issue?


问:
Load DataTable Using Linq - Convert C# to VB.Net
I found the following example on http://www.erictobia.com/2009/02/21/LoadADataTableWithLINQ.aspx
  Unfortunately, I need it in VB and it's using some constructs that neither I nor the automated code converters reciognize.  Anyone out there know how this should be written in VB.Net?  (the problem spot is the "select new {...")</p>

```<code>PeopleDataSet ds = new PeopleDataSet();
using (PeopleDataContext context = new PeopleDataContext())
{
    (from p in context.Persons
     select new
                {
                    Row = ds.Person.AddPersonRow(p.Id, p.FirstName, p.LastName)
                }).ToList();

}
</code>```

答:
```<code> tbl_EmployeeDetail obj_empdetails = new tbl_EmployeeDetail();
                obj_empdetails = Connection.obj_EmployeeDataClassesDataContext.tbl_EmployeeDetails.Single(m => m.EmployeeID == Convert.ToInt32(int_EmpID));
                obj_empdetails.FirstName = str_FirstName;
                obj_empdetails.LastName = str_LastName;
                obj_empdetails.DateOfJoining = dt_DateOfJoining;
                obj_empdetails.DepartmentID = int_DepartmentID;
                obj_empdetails.Designation = str_Designation;
                obj_empdetails.ExperienceInMonths = int_ExperienceInMonths;
                obj_empdetails.salary = dec_Salary;
                Connection.obj_EmployeeDataClassesDataContext.SubmitChanges();
</code>```

Body:
I found the following example on http://www.erictobia.com/2009/02/21/LoadADataTableWithLINQ.aspx
  Unfortunately, I need it in VB and it's using some constructs that neither I nor the automated code converters reciognize.  Anyone out there know how this should be written in VB.Net?  (the problem spot is the "select new {...")

PeopleDataSet ds = new PeopleDataSet();
using (PeopleDataContext context = new PeopleDataContext())
{
    (from p in context.Persons
     select new
                {
                    Row = ds.Person.AddPersonRow(p.Id, p.FirstName, p.LastName)
                }).ToList();

}


问:
How can I call bind on a computation expression without the let keyword?
Say I have this:

```<code>MyComputationExpression {
    let! addr = Salesrecord.Address
    let! name = Salesrecord.Name
    return (name + " " + addr)
}
</code>```

Is there any way to "unwrap" (call the bind method on) the address and name on the fly? Sort of like:

```<code>MyComputationExpression {
    (Salesrecord.Name! + " " + Salesrecord.Address!)
}
</code>```

(If ! was the operator for unwrap on the fly). It seems a bit verbose to have to declare a new variable every time I want to use the result of bind just once.

答:
Your specific example may be easily called from an operator, in order to be inlined:

```<code>let inline (+?) a b =
    MyComputationExpression(){
        let! x = a
        let! y = b
        return x + y }

Some 3 +? None
salesrecord.Address +? Some " " +? salesrecord.Name
</code>```

In more complicated cases, the need to explicity execute bind on the remainder of the computation may at least improve readability.

Body:
Say I have this:

MyComputationExpression {
    let! addr = Salesrecord.Address
    let! name = Salesrecord.Name
    return (name + " " + addr)
}

Is there any way to "unwrap" (call the bind method on) the address and name on the fly? Sort of like:

MyComputationExpression {
    (Salesrecord.Name! + " " + Salesrecord.Address!)
}

(If ! was the operator for unwrap on the fly). It seems a bit verbose to have to declare a new variable every time I want to use the result of bind just once.

Body:
Your specific example may be easily called from an operator, in order to be inlined:

let inline (+?) a b =
    MyComputationExpression(){
        let! x = a
        let! y = b
        return x + y }

Some 3 +? None
salesrecord.Address +? Some " " +? salesrecord.Name

In more complicated cases, the need to explicity execute bind on the remainder of the computation may at least improve readability.


问:
Visual Studio 2015 Tries to Access Optical Drive After Debug Finished
I recently installed Microsoft VS  2105 Professional (Update 3) on a new computer and I experience a strange behavior. Whenever I try to debug a program, the moment I stop the debugger it tries to access my DVD drive that is both strange and very annoying. Other than my usual daily projects, I tried that with clean "Hello World" style C++ and C# projects and it continues to behave the same.

I have disabled the diagnostic tools (Tools->Options->Debugging->disable Enable Diagnostic Tools while debugging) and also run the VS in safe mode (devenv /SafeMode) but the problem persists. I used "Process Monitor" to identify the program that triggers access to the DVD drive and apparently "StandardCollector.Service.exe" is the culprit. You can find the log from  Process Monitor down below (I removed time and PID columns). I know there have been some reported issues (memory) with this particular process (StandardCollector.Service.exe) but why it tries to create/access a file on my DVD drive is a mystery to me. My OS is Windows 10 Home Edition. Can anyone suggest any diagnostic or solution for this problem?

This behavior happens only by Visual Studio upon stopping the debug process and not any other program (Windows does the same upon start-up but I think that is natural). I need to add that if I disable and then enable the DVD drive from Device Manager, the problem goes away  (no access to DVD drive when the debugging finished) but it re-appears again after 1-2 minutes.

************************************ LOG FROM PROCESS MONITOR:

StandardCollector.Service.exe  IRP_MJ_CREATE H: SUCCESS Desired
  Access: Generic Read/Write, Dis"Apple-tab-span"
  style="white-space:pre;">  IRP_MJ_CREATE H:\ INVALID PARAMETER Desired
  Access: Synchronize, Dis"Apple-tab-span" style="white-space:pre;">
  IRP_MJ_DEVICE_CONTROL H: FAST IO DISALLOWED Control:
  IOCTL_SCSI_PASS_THROUGH_DIRECT StandardCollector.Service.exe
  IRP_MJ_DEVICE_CONTROL H: SUCCESS Control:
  IOCTL_SCSI_PASS_THROUGH_DIRECT StandardCollector.Service.exe
  IRP_MJ_DEVICE_CONTROL H: FAST IO DISALLOWED Control:
  IOCTL_DISK_GET_DRIVE_GEOMETRY StandardCollector.Service.exe
  IRP_MJ_DEVICE_CONTROL H: NO MEDIA Control:
  IOCTL_DISK_GET_DRIVE_GEOMETRY StandardCollector.Service.exe
  IRP_MJ_DEVICE_CONTROL H: FAST IO DISALLOWED Control:
  IOCTL_STORAGE_QUERY_PROPERTY StandardCollector.Service.exe
  IRP_MJ_DEVICE_CONTROL H: SUCCESS Control: IOCTL_STORAGE_QUERY_PROPERTY
  StandardCollector.Service.exe  IRP_MJ_DEVICE_CONTROL H: FAST IO
  DISALLOWED Control: IOCTL_CDROM_GET_CONFIGURATION
  StandardCollector.Service.exe  IRP_MJ_DEVICE_CONTROL H: SUCCESS
  Control: IOCTL_CDROM_GET_CONFIGURATION StandardCollector.Service.exe
  IRP_MJ_DEVICE_CONTROL H: FAST IO DISALLOWED Control:
  IOCTL_SCSI_PASS_THROUGH_DIRECT StandardCollector.Service.exe
  IRP_MJ_DEVICE_CONTROL H: SUCCESS Control:
  IOCTL_SCSI_PASS_THROUGH_DIRECT StandardCollector.Service.exe
  IRP_MJ_CLEANUP H: SUCCESS  StandardCollector.Service.exe  IRP_MJ_CLOSE
  H: SUCCESS

答: The same thing happens to me in Visual Studio 2017. The simplest solution for me was to go to Device Manager, right click on the drive, and select "Disable device". I never use the optical drive anymore so this works fine. It can easily be re-enabled from Device Manager if I ever need to use it.</p>


问:
Is there a better conditional setTimeout pattern?
I have the following code:

```<code>if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}
</code>```

It seems like there should be a better pattern than calling flyOut in each if  condition.  Seems wasteful to me and pollutes the code.

Is there a better way?

答:
```<code>async function foo() {
  const delay = isFlyoutAnimationDisabled ? 0 : 250;
  await new Promise(x => setTimeout(x, delay));
  flyOut();
}
</code>```

Literally no if-else needed. Promise is used here, and concurrency issue is avoided. Inspired by @Bergi's answer.

Body:
I have the following code:

if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}

It seems like there should be a better pattern than calling flyOut in each if  condition.  Seems wasteful to me and pollutes the code.

Is there a better way?

Body:
async function foo() {
  const delay = isFlyoutAnimationDisabled ? 0 : 250;
  await new Promise(x => setTimeout(x, delay));
  flyOut();
}

Literally no if-else needed. Promise is used here, and concurrency issue is avoided. Inspired by @Bergi's answer.


问:
Closing Case in Acumatica through API
I want to close the case in Partners Portal remotely using Web API, whenever I close the case in my (client) side. I was able to implement the code but ran into below issue.

It is changing the status and resolution of the case in Partners Portal but Close Case button is enabled and it is visible in My Open Case bucket. Please let me know if I can close the case remotely using Web API or if I am missing anything.

protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if(!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203000WS.Screen context = new SP203000WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203000.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203000WS.LoginResult result = context.Login(username, password);

     SP203000WS.Content CR306000 = context.GetSchema();
     context.Clear();
     SP203000WS.Content[] CR306000Content = context.Submit
      (
       new SP203000WS.Command[]
       {
        new SP203000WS.Value
        {
         Value = acumaticaCaseCD,
         LinkedCommand = CR306000.Case.CaseID
        },
         new SP203000WS.Value
        {
         Value = "C",
         LinkedCommand = new SP203000WS.Field { FieldName="Status", ObjectName="Case"}
        },
        new SP203000WS.Value
        {
         Value = "RD",
         LinkedCommand = new SP203000WS.Field { FieldName="Resolution", ObjectName="Case"}
        },
        CR306000.Actions.Submit,
        CR306000.Case.CaseID
       }
     );

     context.Logout();
    }
   }
  }
 }
}```
</div>
</div>
</p>

<p>Tried below code using CloseCase Action: -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if (!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203010WS.Screen context = new SP203010WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203010.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203010WS.LoginResult result = context.Login(username, password);

     SP203010WS.Content CR306000 = context.GetSchema();
     context.Clear();

     var commands1 = new SP203010WS.Command[]
     {
      new SP203010WS.Value
       {
        Value = acumaticaCaseCD,
        LinkedCommand = CR306000.Case.CaseID
       },
      new SP203010WS.Value
       {
        Value = "Yes",
        LinkedCommand = CR306000.Case.ServiceCommands.DialogAnswer, Commit = true
       },
      CR306000.Actions.CloseCase
     };

     var data = context.Submit(commands1);

     context.Logout();

    }
   }
  }
 }
}</code>```

In the below image you can see that the case is already closed but Close Case menu button is still visible.

Close Case Confirmation Dialogbox on Partners Portal. How should I answer this dialogbox programatically while closing the case using Web API.

答: Have you tried to invoke Close action via Web API instead of changing values of the Status and Resolution fields? As far as I know, Close button on the Partner Portal updates support case Status to Open and Reason to Pending Closure. Then it's up to support personnel to manually close the case.

Title: Closing Case in Acumatica through API

Body:
I want to close the case in Partners Portal remotely using Web API, whenever I close the case in my (client) side. I was able to implement the code but ran into below issue.

It is changing the status and resolution of the case in Partners Portal but Close Case button is enabled and it is visible in My Open Case bucket. Please let me know if I can close the case remotely using Web API or if I am missing anything.

protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if(!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203000WS.Screen context = new SP203000WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203000.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203000WS.LoginResult result = context.Login(username, password);

     SP203000WS.Content CR306000 = context.GetSchema();
     context.Clear();
     SP203000WS.Content[] CR306000Content = context.Submit
      (
       new SP203000WS.Command[]
       {
        new SP203000WS.Value
        {
         Value = acumaticaCaseCD,
         LinkedCommand = CR306000.Case.CaseID
        },
         new SP203000WS.Value
        {
         Value = "C",
         LinkedCommand = new SP203000WS.Field { FieldName="Status", ObjectName="Case"}
        },
        new SP203000WS.Value
        {
         Value = "RD",
         LinkedCommand = new SP203000WS.Field { FieldName="Resolution", ObjectName="Case"}
        },
        CR306000.Actions.Submit,
        CR306000.Case.CaseID
       }
     );

     context.Logout();
    }
   }
  }
 }
}

Tried below code using CloseCase Action: -

protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if (!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203010WS.Screen context = new SP203010WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203010.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203010WS.LoginResult result = context.Login(username, password);

     SP203010WS.Content CR306000 = context.GetSchema();
     context.Clear();

     var commands1 = new SP203010WS.Command[]
     {
      new SP203010WS.Value
       {
        Value = acumaticaCaseCD,
        LinkedCommand = CR306000.Case.CaseID
       },
      new SP203010WS.Value
       {
        Value = "Yes",
        LinkedCommand = CR306000.Case.ServiceCommands.DialogAnswer, Commit = true
       },
      CR306000.Actions.CloseCase
     };

     var data = context.Submit(commands1);

     context.Logout();

    }
   }
  }
 }
}

In the below image you can see that the case is already closed but Close Case menu button is still visible.

Close Case Confirmation Dialogbox on Partners Portal. How should I answer this dialogbox programatically while closing the case using Web API.


问:
jQuery runs the second time but not the first
I have the following code to post a comment on my website

```<code>$('#leave-comment').keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
        post_comment();
    }
});
</code>```

Then the following is the post_comment function

```<code>$('#leave-comment').submit();

$('#frm-leave-comment').unbind('submit');

$('#frm-leave-comment').submit(function(e) {

    // Code here for submit

}
</code>```

When I press enter the first time it runs the keypress (verified by putting an alert in). It also gets the correct key pressed (enter - 13) and it also runs the post_comment function.

The problem is it doesn't submit the form

```<code>$('#frm-leave-comment').submit(function(e) {
</code>```

However, the second time I press enter it does submit the form and works perfectly.

One thing to note is that the first block of code is run from a page loaded with ajax.

The second block of code is in an external javascript loaded when the page loads.

I have checked jquery isn't loaded twice.

There are other niggly things that are happening also like if I wrap the top block of code in a $(document).ready it doesn't fire the code and when using stopPropagation in other places on my website it works the second time but not the first so I think it's just a problem with the way jquery is loaded and not the above code.

Does anybody have an idea as to what may be happening here?

答:
Presumably your form doesn't have any default "submit" action taking place?  At least this appears to be what you claim in your comment above:

When I call submit I put in e.preventDefault to stop the form submitting.

So let's break down what your function is doing:

First time you call the function:

$('#leave-comment').submit(); // does nothing, by your design

$('#frm-leave-comment').unbind('submit'); // removes any existing submit handler, so doesn't observably do anything

$('#frm-leave-comment').submit(function(e) { /*...*/ }); // adds a new submit handler, to be used *the next time* the form is submitted

Second time you call the function:

$('#leave-comment').submit(); // invokes your submit handler

$('#frm-leave-comment').unbind('submit'); // removes your submit handler

$('#frm-leave-comment').submit(function(e) { /*...*/ }); // re-adds *the same submit handler* you just removed

So the first time you execute this function, you're not actually submitting anything.  You're just binding the submit handler to be used the next time you execute this function.

And you keep un-binding and re-binding the same submit handler.

This is vastly overcomplicating things.  Remove that post_comment function entirely and just bind your submit handler when the page loads:

```<code>$(function () {
    $('#frm-leave-comment').submit(function(e) {
        // Code here for submit
    }
});
</code>```

Then in your keypress handler, simply submit the form:

```<code>$('#leave-comment').keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
        $('#leave-comment').submit();
        $('#frm-leave-comment').submit();
    }
});
</code>```

Body:
I have the following code to post a comment on my website

$('#leave-comment').keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
        post_comment();
    }
});

Then the following is the post_comment function

$('#leave-comment').submit();

$('#frm-leave-comment').unbind('submit');

$('#frm-leave-comment').submit(function(e) {

    // Code here for submit

}

When I press enter the first time it runs the keypress (verified by putting an alert in). It also gets the correct key pressed (enter - 13) and it also runs the post_comment function.

The problem is it doesn't submit the form

$('#frm-leave-comment').submit(function(e) {

However, the second time I press enter it does submit the form and works perfectly.

One thing to note is that the first block of code is run from a page loaded with ajax.

The second block of code is in an external javascript loaded when the page loads.

I have checked jquery isn't loaded twice.

There are other niggly things that are happening also like if I wrap the top block of code in a $(document).ready it doesn't fire the code and when using stopPropagation in other places on my website it works the second time but not the first so I think it's just a problem with the way jquery is loaded and not the above code.

Does anybody have an idea as to what may be happening here?

Body:
Presumably your form doesn't have any default "submit" action taking place?  At least this appears to be what you claim in your comment above:

When I call submit I put in e.preventDefault to stop the form submitting.

So let's break down what your function is doing:

First time you call the function:

$('#leave-comment').submit(); // does nothing, by your design

$('#frm-leave-comment').unbind('submit'); // removes any existing submit handler, so doesn't observably do anything

$('#frm-leave-comment').submit(function(e) { /*...*/ }); // adds a new submit handler, to be used *the next time* the form is submitted

Second time you call the function:

$('#leave-comment').submit(); // invokes your submit handler

$('#frm-leave-comment').unbind('submit'); // removes your submit handler

$('#frm-leave-comment').submit(function(e) { /*...*/ }); // re-adds *the same submit handler* you just removed

So the first time you execute this function, you're not actually submitting anything.  You're just binding the submit handler to be used the next time you execute this function.

And you keep un-binding and re-binding the same submit handler.

This is vastly overcomplicating things.  Remove that post_comment function entirely and just bind your submit handler when the page loads:

$(function () {
    $('#frm-leave-comment').submit(function(e) {
        // Code here for submit
    }
});

Then in your keypress handler, simply submit the form:

$('#leave-comment').keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
        $('#leave-comment').submit();
        $('#frm-leave-comment').submit();
    }
});