问:
Submit/log in click Selenium + Python
I'm trying to auto submit login details and then log in to a page.

My code snippet thus far is:

```<code>from selenium import webdriver
import selenium
from selenium.webdriver.common.by import By
driver = webdriver.Chrome("PathOfChromeDriver")

driver.get("URL")

username = driver.find_element_by_name("UserName")
password = driver.find_element_by_name("Password")

username.send_keys("My_Username")
password.send_keys("My_Password")
</code>```

The above snippet works fine. The problem is submitting/ pressing login:

```<code>driver.find_element_by_xpath("Sign in").click()
</code>```

I have tried every conceivable variation i could find on this forum of the above such as:

```<code>driver.find_element_by_name("submit").click()
</code>```

etc.

The source code to the website element in question is:

```<code><form action="/Account/SignIn?returnUrl=%252fProducts" method="post" id="page-root" class="signin-page local-new-style" autocomplete="off">

<div class="login">
    <img alt="logo" src="/Content/images/bg_login_logo.png" />
    <div class="inner_content ">
        <div class="content">

            <h1>Access your account</h1>
            <div>
                <input type="text" name="UserName" placeholder="Login" />

            </div>
            <div>
                <input type="password" name="Password" placeholder="Password" />

            </div>

            <div>
                <label>
                    <input type="checkbox" name="RememberMe" value="True" />
                    Remember my login on this computer
                </label>
            </div>
            <div>
                <button type="submit">Sign in</button>
            </div>
        </div>
    </div>
</div>

</form>
</code>```

I just cannot get it to work. It usually gives me an error of the type "unable to locate an element with the ZZZ expression YYY".

Any input is appreciated and the person with a solution is nothing short of a Hero!

答:
Try this:

```<code>driver.find_element_by_css_selector("form[id='page-root'] button").click()
</code>```

This should also work:

```<code>driver.find_element_by_id("page-root").submit()
</code>```

Title: Submit/log in click Selenium + Python

Body:
I'm trying to auto submit login details and then log in to a page.

My code snippet thus far is:

from selenium import webdriver
import selenium
from selenium.webdriver.common.by import By
driver = webdriver.Chrome("PathOfChromeDriver")

driver.get("URL")

username = driver.find_element_by_name("UserName")
password = driver.find_element_by_name("Password")

username.send_keys("My_Username")
password.send_keys("My_Password")

The above snippet works fine. The problem is submitting/ pressing login:

driver.find_element_by_xpath("Sign in").click()

I have tried every conceivable variation i could find on this forum of the above such as:

driver.find_element_by_name("submit").click()

etc.

The source code to the website element in question is:

<form action="/Account/SignIn?returnUrl=%252fProducts" method="post" id="page-root" class="signin-page local-new-style" autocomplete="off">

Access your account

                <input type="text" name="UserName" placeholder="Login" />

                <input type="password" name="Password" placeholder="Password" />

                    <input type="checkbox" name="RememberMe" value="True" />
                    Remember my login on this computer

                <button type="submit">Sign in</button>

</form>

I just cannot get it to work. It usually gives me an error of the type "unable to locate an element with the ZZZ expression YYY".

Any input is appreciated and the person with a solution is nothing short of a Hero!

Body:
Try this:

driver.find_element_by_css_selector("form[id='page-root'] button").click()

This should also work:

driver.find_element_by_id("page-root").submit()


来源: stackexchange

问:
Bypass <app-route> to make normal links work in Polymer 2
My site uses Polymer 2, <app-location> and <app-route>. The <app-route> allows me to change the URL on user interaction with the app, but it seems that it is also preventing normal links from functioning.

How can I make normal href="/some/url/on/my/domain"> links work? Is there a way to make links bypass <app-route>?

答:
The app-location use iron-location which listen click event on document. So just stop click event before it propagates to document.

```<code><a href='/some/url' on-click='stopPropagation'>
...
stopPropagation (event) {
  event.stopPropagation()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My site uses Polymer 2, <app-location> and <app-route>. The <app-route> allows me to change the URL on user interaction with the app, but it seems that it is also preventing normal links from functioning.

How can I make normal  links work? Is there a way to make links bypass <app-route>?

Body:
The app-location use iron-location which listen click event on document. So just stop click event before it propagates to document.

<a href='/some/url' on-click='stopPropagation'>
...
stopPropagation (event) {
  event.stopPropagation()
}


问:
What is the difference between itms-app:// and https:// App Store link
I'm trying to create the link to App Store and I found many ways to do it.

Open App Store page in iTunes Store.

```<code>let url  = URL(string: "itms://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")
</code>```

Open App Store.

```<code>let url  = URL(string: "https://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")
</code>```

Open App Store.

```<code>let url  = URL(string: "itms-apps://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542?mt=8")
</code>```

As far as I know, Method #2 and #3 almost produce the same result.

But I curious it should have some difference?.

答:
if you have using this link itms-app:// it will open the app directly in the store.

```<code>let url  = URL(string: "itms://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")
</code>```

you have using this link https:// it will open links from launching iTunes with Safari.

```<code>var iTunesLink = "https://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542"
UIApplication.shared.openURL(URL(string: iTunesLink)!)
</code>```

Body:
I'm trying to create the link to App Store and I found many ways to do it.

Open App Store page in iTunes Store.

let url  = URL(string: "itms://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")

Open App Store.

let url  = URL(string: "https://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")

Open App Store.

let url  = URL(string: "itms-apps://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542?mt=8")

As far as I know, Method #2 and #3 almost produce the same result.

But I curious it should have some difference?.

Body:
if you have using this link itms-app:// it will open the app directly in the store.

let url  = URL(string: "itms://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")

you have using this link https:// it will open links from launching iTunes with Safari.

var iTunesLink = "https://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542"
UIApplication.shared.openURL(URL(string: iTunesLink)!)


问:
Get the attributes of the selected item in a GeoJSONDataSource
I want to link a plot containing patches (from a GeoJSONDataSource) with a line chart but i'm having trouble getting the attributes of the selected patch.

Its basically a plot showing polygons, and when a polygon is selected, i want to update the line chart with a timeseries of data for that polygon. The line chart is driven by a normal ColumnDataSource.

I can get the indices of the selected patch by adding a callback combined with geo_source.selected['1d']['indices']. But how do i get the data/attributes which correspond to that index? I need to get a 'key' in the attributes which i can then use to update the line chart.

The GeoJSONDataSource has no data attribute in which i can lookup the data itself. Bokeh can use the attributes for things like coloring/tooltips etc, so i assume there must be a way to get these out of the GeoJSONDataSource, i cant find it unfortunately.

edit:

Here is working toy example showing what i've got so far.

```<code>import pandas as pd
import numpy as np

from bokeh import events
from bokeh.models import (Select, Column, Row, ColumnDataSource, HoverTool,
                          Range1d, LinearAxis, GeoJSONDataSource)
from bokeh.plotting import figure
from bokeh.io import curdoc

import os
import datetime
from collections import OrderedDict

def make_plot(src):
    # function to create the line chart

    p = figure(width=500, height=200, x_axis_type='datetime', title='Some parameter',
               tools=['xwheel_zoom', 'xpan'], logo=None, toolbar_location='below', toolbar_sticky=False)

    p.circle('index', 'var1', color='black', fill_alpha=0.2, size=10, source=src)

    return p

def make_geo_plot(src):
    # function to create the spatial plot with polygons

    p = figure(width=300, height=300, title="Select area", tools=['tap', 'pan', 'box_zoom', 'wheel_zoom','reset'], logo=None)

    p.patches('xs', 'ys', fill_alpha=0.2, fill_color='black',
              line_color='black', line_width=0.5, source=src)

    p.on_event(events.SelectionGeometry, update_plot_from_geo)

    return p

def update_plot_from_geo(event):
    # update the line chart based on the selected polygon

    selected = geo_source.selected['1d']['indices']

    if (len(selected) > 0):
        first = selected[0]
        print(geo_source.selected['1d']['indices'])

def update_plot(attrname, old, new):
    # Callback for the dropdown menu which updates the line chart
    new_src = get_source(df, area_select.value)
    src.data.update(new_src.data)

def get_source(df, fieldid):
    # function to get a subset of the multi-hierarchical DataFrame

    # slice 'out' the selected area
    dfsub = df.xs(fieldid, axis=1, level=0)
    src = ColumnDataSource(dfsub)

    return src

# example timeseries
n_points = 100
df = pd.DataFrame({('area_a','var1'): np.sin(np.linspace(0,5,n_points)) + np.random.rand(100)*0.1,
                   ('area_b','var1'): np.sin(np.linspace(0,2,n_points)) + np.random.rand(100)*0.1,
                   ('area_c','var1'): np.sin(np.linspace(0,3,n_points)) + np.random.rand(100)*0.1,
                   ('area_d','var1'): np.sin(np.linspace(0,4,n_points)) + np.random.rand(100)*0.1},
                  index=pd.DatetimeIndex(start='2017-01-01', freq='D', periods=100))

# example polygons
geojson = """{
"type":"FeatureCollection",
"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},
"features":[
{"type":"Feature","properties":{"key":"area_a"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-108.8,42.7],[-104.5,42.0],[-108.3,39.3],[-108.8,42.7]]]]}},
{"type":"Feature","properties":{"key":"area_b"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-106.3,44.0],[-106.2,42.6],[-103.3,42.6],[-103.4,44.0],[-106.3,44.0]]]]}},
{"type":"Feature","properties":{"key":"area_d"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-104.3,41.0],[-101.5,41.0],[-102.9,37.8],[-104.3,41.0]]]]}},
{"type":"Feature","properties":{"key":"area_c"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-105.8,40.3],[-108.3,37.7],[-104.0,37.4],[-105.8,40.3]]]]}}
]
}"""

geo_source = GeoJSONDataSource(geojson=geojson)

# populate a drop down menu with the area's
area_ids = sorted(df.columns.get_level_values(0).unique().values.tolist())
area_ids = [str(x) for x in area_ids]
area_select = Select(value=area_ids[0], title='Select area', options=area_ids)
area_select.on_change('value', update_plot)

src = get_source(df, area_select.value)

p = make_plot(src)
pgeo = make_geo_plot(geo_source)

# add to document
curdoc().add_root(Row(Column(area_select, p), pgeo))
</code>```

Save the code in a .py file and load with bokeh serve example.py --show

答:
The geojson data that you pass to GeoJSONDataSource is stored in its geojson property -- as a string. My suggestion isn't particularly elegant: you can just parse the json string using the built-in json module. Here's a working version of update_plot_from_geo that updates the line plot based on the selected polygon:

```<code>def update_plot_from_geo(event):
    # update the line chart based on the selected polygon

    indices = geo_source.selected['1d']['indices']

    if indices:
        parsed_geojson = json.loads(geo_source.geojson)
        features = parsed_geojson['features']
        series_key = features[indices[0]]['properties']['key']
        new_source = get_source(df, series_key)
        src.data.update(new_source.data)
</code>```

You'll also need to import json at the top.

I'm a little surprised there's not an obvious way to get the parsed json data. The GeoJSONDataSource documentation indicates the existence of the geojson attribute, but says it's a JSON object. The JSON documentation seems to hint that you should be able to do something like src.geojson.parse. But the type of geojson is just str. Upon closer inspection, it appears that the docs are using "JSON" ambiguously, referring to the Bokeh JSON class in some cases, and to the built-in JavaScript JSON object in others.

So at the moment, I don't believe there's a better way to get at this data.

Body:
I want to link a plot containing patches (from a GeoJSONDataSource) with a line chart but i'm having trouble getting the attributes of the selected patch.

Its basically a plot showing polygons, and when a polygon is selected, i want to update the line chart with a timeseries of data for that polygon. The line chart is driven by a normal ColumnDataSource.

I can get the indices of the selected patch by adding a callback combined with geo_source.selected['1d']['indices']. But how do i get the data/attributes which correspond to that index? I need to get a 'key' in the attributes which i can then use to update the line chart.

The GeoJSONDataSource has no data attribute in which i can lookup the data itself. Bokeh can use the attributes for things like coloring/tooltips etc, so i assume there must be a way to get these out of the GeoJSONDataSource, i cant find it unfortunately.

edit:

Here is working toy example showing what i've got so far.

import pandas as pd
import numpy as np

from bokeh import events
from bokeh.models import (Select, Column, Row, ColumnDataSource, HoverTool,
                          Range1d, LinearAxis, GeoJSONDataSource)
from bokeh.plotting import figure
from bokeh.io import curdoc

import os
import datetime
from collections import OrderedDict

def make_plot(src):
    # function to create the line chart

    p = figure(width=500, height=200, x_axis_type='datetime', title='Some parameter',
               tools=['xwheel_zoom', 'xpan'], logo=None, toolbar_location='below', toolbar_sticky=False)

    p.circle('index', 'var1', color='black', fill_alpha=0.2, size=10, source=src)

    return p

def make_geo_plot(src):
    # function to create the spatial plot with polygons

    p = figure(width=300, height=300, title="Select area", tools=['tap', 'pan', 'box_zoom', 'wheel_zoom','reset'], logo=None)

    p.patches('xs', 'ys', fill_alpha=0.2, fill_color='black',
              line_color='black', line_width=0.5, source=src)

    p.on_event(events.SelectionGeometry, update_plot_from_geo)

    return p

def update_plot_from_geo(event):
    # update the line chart based on the selected polygon

    selected = geo_source.selected['1d']['indices']

    if (len(selected) > 0):
        first = selected[0]
        print(geo_source.selected['1d']['indices'])

def update_plot(attrname, old, new):
    # Callback for the dropdown menu which updates the line chart
    new_src = get_source(df, area_select.value)
    src.data.update(new_src.data)

def get_source(df, fieldid):
    # function to get a subset of the multi-hierarchical DataFrame

    # slice 'out' the selected area
    dfsub = df.xs(fieldid, axis=1, level=0)
    src = ColumnDataSource(dfsub)

    return src

# example timeseries
n_points = 100
df = pd.DataFrame({('area_a','var1'): np.sin(np.linspace(0,5,n_points)) + np.random.rand(100)*0.1,
                   ('area_b','var1'): np.sin(np.linspace(0,2,n_points)) + np.random.rand(100)*0.1,
                   ('area_c','var1'): np.sin(np.linspace(0,3,n_points)) + np.random.rand(100)*0.1,
                   ('area_d','var1'): np.sin(np.linspace(0,4,n_points)) + np.random.rand(100)*0.1},
                  index=pd.DatetimeIndex(start='2017-01-01', freq='D', periods=100))

# example polygons
geojson = """{
"type":"FeatureCollection",
"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},
"features":[
{"type":"Feature","properties":{"key":"area_a"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-108.8,42.7],[-104.5,42.0],[-108.3,39.3],[-108.8,42.7]]]]}},
{"type":"Feature","properties":{"key":"area_b"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-106.3,44.0],[-106.2,42.6],[-103.3,42.6],[-103.4,44.0],[-106.3,44.0]]]]}},
{"type":"Feature","properties":{"key":"area_d"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-104.3,41.0],[-101.5,41.0],[-102.9,37.8],[-104.3,41.0]]]]}},
{"type":"Feature","properties":{"key":"area_c"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-105.8,40.3],[-108.3,37.7],[-104.0,37.4],[-105.8,40.3]]]]}}
]
}"""

geo_source = GeoJSONDataSource(geojson=geojson)

# populate a drop down menu with the area's
area_ids = sorted(df.columns.get_level_values(0).unique().values.tolist())
area_ids = [str(x) for x in area_ids]
area_select = Select(value=area_ids[0], title='Select area', options=area_ids)
area_select.on_change('value', update_plot)

src = get_source(df, area_select.value)

p = make_plot(src)
pgeo = make_geo_plot(geo_source)

# add to document
curdoc().add_root(Row(Column(area_select, p), pgeo))

Save the code in a .py file and load with bokeh serve example.py --show

Body:
The geojson data that you pass to GeoJSONDataSource is stored in its geojson property -- as a string. My suggestion isn't particularly elegant: you can just parse the json string using the built-in json module. Here's a working version of update_plot_from_geo that updates the line plot based on the selected polygon:

def update_plot_from_geo(event):
    # update the line chart based on the selected polygon

    indices = geo_source.selected['1d']['indices']

    if indices:
        parsed_geojson = json.loads(geo_source.geojson)
        features = parsed_geojson['features']
        series_key = features[indices[0]]['properties']['key']
        new_source = get_source(df, series_key)
        src.data.update(new_source.data)

You'll also need to import json at the top.

I'm a little surprised there's not an obvious way to get the parsed json data. The GeoJSONDataSource documentation indicates the existence of the geojson attribute, but says it's a JSON object. The JSON documentation seems to hint that you should be able to do something like src.geojson.parse. But the type of geojson is just str. Upon closer inspection, it appears that the docs are using "JSON" ambiguously, referring to the Bokeh JSON class in some cases, and to the built-in JavaScript JSON object in others.

So at the moment, I don't believe there's a better way to get at this data.


问:
jQuery .load() - corner plugin not working in IE - Firefox is ok
I have two simple pages I'm using for testing.

On my first page, I use $.load() to load a div from the second page.

Both pages contains the plugin to do the cornering. If I load the first page which loads the div from the second page, the cornering does not work. However, if I load the second page myself, the cornering does work so it's to do with $.load().

Here's some code, from page 1:

```<code> <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                $("#load").load('testLoadCornering2.aspx #loadMe');
            });
        </script>

        <script src="resources/js/curvycorners.js" type="text/javascript"></script>

        <script src="resources/js/curvycorners.src.js" type="text/javascript"></script>

        <link href="resources/css/main.css" rel="stylesheet" type="text/css" />
        <link href="resources/css/buttons.css" rel="stylesheet" type="text/css" />
        <link href="resources/css/confirm.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <form id="form1" runat="server">
        <div id="load" class="BWTable">
        </div>
        </form>
    </body>
    </html>
</code>```

You see the page trying to load the second div.

And the second page:

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

    <script src="resources/js/curvycorners.js" type="text/javascript"></script>

    <script src="resources/js/curvycorners.src.js" type="text/javascript"></script>

    <link href="resources/css/main.css" rel="stylesheet" type="text/css" />
    <link href="resources/css/buttons.css" rel="stylesheet" type="text/css" />
    <link href="resources/css/confirm.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div id="loadMe" class="BWTable">
        <p>
            Test Test Test Test Test Test Test
        </p>
    </div>
    </form>
</body>
</html>
</code>```

And the CSS it uses for the rounding (along with the rounded corners plugin):

```<code> background-image: url(         '../../images/wp_form2.gif' );
 border: solid 1px #000000;
 margin-left: auto;
 margin-right: auto;
 text-align: center;
 color: white;
 -moz-border-radius: 10px; /* Rounded corners plugin */
 -webkit-border-radius: 10px; /* Rounded corners plugin */
</code>```

In Firefox, this works fine - but in IE (specially version 8 I've been trying) the corners are never rounded.

To reiterate, manually going to the second page in IE 8 corners correctly, it's only when the .load() method is used.

Any help appreciated.

Note: I'm aware I shouldn't need to add the style sheets on both pages etc as they should be loaded from the first page, but I've added them to show you the full code of what it's trying to do.
Thanks,
Ricky

答:
The issue here is that curvycorners will only spring into life for IE as Firefox fully supports the CSS3 rounded corners so while it's working in Firefox, that's only because curvycorners isn't attempting to do anything.

Your JQuery load is placed within a document-ready block and so won't execute until the whole page has loaded, including (I believe) the javascript, so curvycorners is running before your second page div is loaded. You need to find a way to either load the curvycorners script after your second page div or find out how to call curvycorners to reparse the page once it has loaded the second page div.

From the curvycorners documentation:

If you need to change some attributes
  or styling of the redrawable elements,
  this should not be done directly
  through the DOM. Instead, having
  identified the DOM object (e.g. with
  document.getElementById()), call

curvyCorners.adjust(DOMObj,
  propertyName, newValue);

where:

DOMObj is the element object with
  className curvyRedraw that needs to be
  changed;

  propertyName is the name of
  the property without a leading dot; if
  it is a style property, it should be
  expressed as 'style.property'.

  newValue is the new value, e.g.
  'none'.

curvyCorners.adjust() must
  take all three parameters described
  above. It returns no useful value.

ContentLicense: CC BY-SA 2.5

Body:
I have two simple pages I'm using for testing.

On my first page, I use $.load() to load a div from the second page.

Both pages contains the plugin to do the cornering. If I load the first page which loads the div from the second page, the cornering does not work. However, if I load the second page myself, the cornering does work so it's to do with $.load().

Here's some code, from page 1:

        <title>Untitled Page</title>

        <link href="resources/css/main.css" rel="stylesheet" type="text/css" />
        <link href="resources/css/buttons.css" rel="stylesheet" type="text/css" />
        <link href="resources/css/confirm.css" rel="stylesheet" type="text/css" />

        <form id="form1" runat="server">

        </form>

You see the page trying to load the second div.

And the second page:

    <title>Untitled Page</title>

    <link href="resources/css/main.css" rel="stylesheet" type="text/css" />
    <link href="resources/css/buttons.css" rel="stylesheet" type="text/css" />
    <link href="resources/css/confirm.css" rel="stylesheet" type="text/css" />

    <form id="form1" runat="server">

            Test Test Test Test Test Test Test

    </form>

And the CSS it uses for the rounding (along with the rounded corners plugin):

 background-image: url(         '../../images/wp_form2.gif' );
 border: solid 1px #000000;
 margin-left: auto;
 margin-right: auto;
 text-align: center;
 color: white;
 -moz-border-radius: 10px; /* Rounded corners plugin */
 -webkit-border-radius: 10px; /* Rounded corners plugin */

In Firefox, this works fine - but in IE (specially version 8 I've been trying) the corners are never rounded.

To reiterate, manually going to the second page in IE 8 corners correctly, it's only when the .load() method is used.

Any help appreciated.

Note: I'm aware I shouldn't need to add the style sheets on both pages etc as they should be loaded from the first page, but I've added them to show you the full code of what it's trying to do.
Thanks,
Ricky


问:
How to move a gameobject using movetowards
How do I make my GameObject move towards another GameObject using Vector3.MoveTowards method?

Heres my current code:

```<code>void update()
{
    TargetObject.transform.position = Vector3.MoveTowards (TargetObject.transform.position, Cube.transform.position , MaxDistanceDelta);
}
</code>```

答:
```<code>void Update() {
    myGameObject.transform.position = Vector3.MoveTowards(myGameObject.transform.position, targetObject.transform.position, Time.deltaTime * speed);
}
</code>```

myGameObject - object you want to move

targetObject - object you are moving to

speed - float value to set the speed

Body:
How do I make my GameObject move towards another GameObject using Vector3.MoveTowards method?

Heres my current code:

void update()
{
    TargetObject.transform.position = Vector3.MoveTowards (TargetObject.transform.position, Cube.transform.position , MaxDistanceDelta);
}

Body:
void Update() {
    myGameObject.transform.position = Vector3.MoveTowards(myGameObject.transform.position, targetObject.transform.position, Time.deltaTime * speed);
}

myGameObject - object you want to move

targetObject - object you are moving to

speed - float value to set the speed


问:
How to export two DataTables in just one PDF file
I'm currently using DataTables to draw tables in a webpage. I have a table which is not hidden and users can view it without problems. On the other hand, I have a hidden table which has to be exported with the not hidden table at same time.

I want to be able to click on "Export PDF" in the not hidden table and generate a PDF file with both tables, the hidden and the not hidden table.

Could someone help me? I'm a little confused about how to do that.

答:
If you have identical tables it is dead easy. Simply have a third (or fourth etc) hidden table you only use for export purposes. When your "PDF" button is clicked follow these steps :

Beforehand, set the *_wrapper container to display: none; so the user never sees flicker or garbage on the screen

Use the API to collect data from all tables and merge them

Initialise the hidden export table and use the merged data as data source

Trigger the PDF export programmatically

Clean up the hidden export table so no conflicts occurs when the user tries to export a second time

===

```<code>$('#example').DataTable({ });
$('#example2').DataTable({ });

$('button').on('click', function() {
  var data = $('#example').DataTable().table().data();
  $.merge( data, $('#example2').DataTable().table().data() );
  $('#export-table').DataTable({
    dom: 'B',
    data: data,
    buttons: [{
      extend: 'pdfHtml5'
    }],
    drawCallback: function() {
      $('#export-table_wrapper .buttons-pdf').click()
       setTimeout(function() {
          $('#export-table').DataTable().destroy(false);
       }, 200)
    }
  })
})
</code>```

Here is a demo with one visible table, one hidden table and a third table which takes care of the export -> https://jsfiddle.net/u20x4be0/

Body:
If you have identical tables it is dead easy. Simply have a third (or fourth etc) hidden table you only use for export purposes. When your "PDF" button is clicked follow these steps :

Beforehand, set the *_wrapper container to display: none; so the user never sees flicker or garbage on the screen

Use the API to collect data from all tables and merge them

Initialise the hidden export table and use the merged data as data source

Trigger the PDF export programmatically

Clean up the hidden export table so no conflicts occurs when the user tries to export a second time

===

$('#example').DataTable({ });
$('#example2').DataTable({ });

$('button').on('click', function() {
  var data = $('#example').DataTable().table().data();
  $.merge( data, $('#example2').DataTable().table().data() );
  $('#export-table').DataTable({
    dom: 'B',
    data: data,
    buttons: [{
      extend: 'pdfHtml5'
    }],
    drawCallback: function() {
      $('#export-table_wrapper .buttons-pdf').click()
       setTimeout(function() {
          $('#export-table').DataTable().destroy(false);
       }, 200)
    }
  })
})

Here is a demo with one visible table, one hidden table and a third table which takes care of the export -> https://jsfiddle.net/u20x4be0/


问:
java.lang.SecurityException: Permission Denial:
I use Instrumentation to test PhoneApp
I wrote my test application via Instrumentation

I created apk and installed it on Nexus One - Android Phone - this passed
In my code I am using internal classes that are not a part of standard SDK.
I build it not in Eclipse but in my embedded env. I am eng in company that developing for Android so I have and Android tree with all internals libraries.

I use appropriate permissions in my manifest .

my apk created probably signed with some signature !!
But probably this signature not good enough.

Now I run test via adb and got this error immediately:

```<code>-------------------------------------------------------------------------------------
INSTRUMENTATION_STATUS: id=ActivityManagerService
INSTRUMENTATION_STATUS: Error=Permission Denial: starting instrumentation ComponentInfo{com.android.phonetests/com.android.phonetests.PhoneInstrumentationTestRunner} from pid=495, uid=495 not allowed because package com.android.phonetests does not have a
 signature matching the target com.android.phone
INSTRUMENTATION_STATUS_CODE: -1
java.
lang.SecurityException: Permission Denial: starting instrumentation ComponentInfo{com.android.phonetests/com.android.phonetests.PhoneInstrumentationTestRunner} from pid=495, uid=495 not allowed because package com.android.phonetests does not have a
signature matching the target com.android.phone
-------------------------------------------------------------------------------------
</code>```

Please help.

答:
This solution is only for system app

In my case, this error occur when I create InstrumentationTest case for existing system app (We are building our own android OS based on AOSP)

We normally build the apk using mm command based on Android.mk file, here the key is LOCAL_CERTIFICATE.

Find Android.mk in Targeted system app and the test case project developing by you.

system app's Android.mk LOCAL_CERTIFICATE value should match with InstrumentationTest case project's Android.mk LOCAL_CERTIFICATE value

Good luck!

Body:
I use Instrumentation to test PhoneApp
I wrote my test application via Instrumentation

I created apk and installed it on Nexus One - Android Phone - this passed
In my code I am using internal classes that are not a part of standard SDK.
I build it not in Eclipse but in my embedded env. I am eng in company that developing for Android so I have and Android tree with all internals libraries.

I use appropriate permissions in my manifest .

my apk created probably signed with some signature !!
But probably this signature not good enough.

Now I run test via adb and got this error immediately:

-------------------------------------------------------------------------------------
INSTRUMENTATION_STATUS: id=ActivityManagerService
INSTRUMENTATION_STATUS: Error=Permission Denial: starting instrumentation ComponentInfo{com.android.phonetests/com.android.phonetests.PhoneInstrumentationTestRunner} from pid=495, uid=495 not allowed because package com.android.phonetests does not have a
 signature matching the target com.android.phone
INSTRUMENTATION_STATUS_CODE: -1
java.
lang.SecurityException: Permission Denial: starting instrumentation ComponentInfo{com.android.phonetests/com.android.phonetests.PhoneInstrumentationTestRunner} from pid=495, uid=495 not allowed because package com.android.phonetests does not have a
signature matching the target com.android.phone
-------------------------------------------------------------------------------------

Please help.


问:
How to successfully change " public " folder name to " public_html " in laravel 5.2
i had to ask this question here. i have seen so many other responses and none of them worked.. even after i editted the register function inside the app/providers/AppServiceProvider.php file - from a solution i got on laracasts.

```<code>public function register(){

    $this->app->bind('path.public_html', function(){
        return base_path(). '/public_html';
    });
    //
}
</code>```

with this set, the hompage loaded successfully.
but then after editting the welcome route to this ::

```<code>Route::get('/', function () {
   echo public_path();  //resolves to:: C:\xampp\htdocs\paprng\public
   exit;
   return view('welcome');
</code>```

});

my public_path() function resolves to " C:\xampp\htdocs\paprng\public "..

please is there a string value of "public" somewhere in the laravel app. structure that requires editting to " public_html ", to avoid this error.

Thanks in advance.

答:
Change the name of the public folder for whatever you want, and then add this code to index.php

```<code>$app->bind('path.public', function() {
    return __DIR__;
});
</code>```

EDIT:

On your bootstrap/app.php file, add this code after the declaration of $app variable:

```<code>$app->bind('path.public', function() {
    return realpath(__DIR__.'/../public_html');
});
</code>```

Body:
i had to ask this question here. i have seen so many other responses and none of them worked.. even after i editted the register function inside the app/providers/AppServiceProvider.php file - from a solution i got on laracasts.

public function register(){

    $this->app->bind('path.public_html', function(){
        return base_path(). '/public_html';
    });
    //
}

with this set, the hompage loaded successfully.
but then after editting the welcome route to this ::

Route::get('/', function () {
   echo public_path();  //resolves to:: C:\xampp\htdocs\paprng\public
   exit;
   return view('welcome');

});

my public_path() function resolves to " C:\xampp\htdocs\paprng\public "..

please is there a string value of "public" somewhere in the laravel app. structure that requires editting to " public_html ", to avoid this error.

Thanks in advance.

Body:
Change the name of the public folder for whatever you want, and then add this code to index.php

$app->bind('path.public', function() {
    return __DIR__;
});

EDIT:

On your bootstrap/app.php file, add this code after the declaration of $app variable:

$app->bind('path.public', function() {
    return realpath(__DIR__.'/../public_html');
});


问:
where is "PS_META_DESCRIPTION" and "PS_META_KEYWORDS" and how can i change it?
in classes/Meta.php i found this lines in "completeMetaTags" function:

```<code>if (empty($meta_tags['meta_description'])) {
      $meta_tags['meta_description'] = Configuration::get('PS_META_DESCRIPTION', $context->language->id) ? Configuration::get('PS_META_DESCRIPTION', $context->language->id) : '';
}
if (empty($meta_tags['meta_keywords'])) {
      $meta_tags['meta_keywords'] = Configuration::get('PS_META_KEYWORDS', $context->language->id) ? Configuration::get('PS_META_KEYWORDS', $context->language->id) : '';
}
</code>```

it seems, when a page doesn't have any keywords or description, it tries to set "PS_META_KEYWORDS" and "PS_META_DESCRIPTION" to those.

but the value of "PS_META_DESCRIPTION" and "PS_META_KEYWORDS" are empty for me and i don't know where can i change these values ?

i searched "configuration" table but i can't find "PS_META_DESCRIPTION" and "PS_META_KEYWORDS" values.

答:
I cannot find what you are searching for in the whole raw Prestashop 1.6 repository, except the legacy code you are talking about.

A way to set this could be to make a simple module with these fields to custom, you can find an helper here : https://validator.prestashop.com

Anyway it's not possible with the actual version, it surely was in the past.

Body:
in classes/Meta.php i found this lines in "completeMetaTags" function:

if (empty($meta_tags['meta_description'])) {
      $meta_tags['meta_description'] = Configuration::get('PS_META_DESCRIPTION', $context->language->id) ? Configuration::get('PS_META_DESCRIPTION', $context->language->id) : '';
}
if (empty($meta_tags['meta_keywords'])) {
      $meta_tags['meta_keywords'] = Configuration::get('PS_META_KEYWORDS', $context->language->id) ? Configuration::get('PS_META_KEYWORDS', $context->language->id) : '';
}

it seems, when a page doesn't have any keywords or description, it tries to set "PS_META_KEYWORDS" and "PS_META_DESCRIPTION" to those.

but the value of "PS_META_DESCRIPTION" and "PS_META_KEYWORDS" are empty for me and i don't know where can i change these values ?

i searched "configuration" table but i can't find "PS_META_DESCRIPTION" and "PS_META_KEYWORDS" values.


问:
Combine 2 dataframe and then separate them
I have 2 dataframes with same column headers. I wish to perform hot encoding on both of them. I cannot perform them one by one. I wish to append two dataframe together and then perform hot encoding and then split them into 2 dataframes with headers on each of them again.

Code below perform hot encoding one by one instead of merging them and then hot encode.

```<code>train = pd.get_dummies(train, columns= ['is_discount', 'gender', 'city'])
test = pd.get_dummies(test, columns= ['is_discount', 'gender', 'city'])
</code>```

答:
Use concat with keys then divide i.e </p>

```<code>#Example Dataframes
train = pd.DataFrame({'x':[1,2,3,4]})
test = pd.DataFrame({'x':[4,2,5,0]})

# Concat with keys
temp = pd.get_dummies(pd.concat([train,test],keys=[0,1]), columns=['x'])

# Selecting data from multi index
train,test = temp.xs(0),temp.xs(1)
</code>```

<p>Output : </p>

```
#Train
  x_0  x_1  x_2  x_3  x_4  x_5
0    0    1    0    0    0    0
1    0    0    1    0    0    0
2    0    0    0    1    0    0
3    0    0    0    0    1    0

#Test
   x_0  x_1  x_2  x_3  x_4  x_5
0    0    0    0    0    1    0
1    0    0    1    0    0    0
2    0    0    0    0    0    1
3    1    0    0    0    0    0
```

Body:
I have 2 dataframes with same column headers. I wish to perform hot encoding on both of them. I cannot perform them one by one. I wish to append two dataframe together and then perform hot encoding and then split them into 2 dataframes with headers on each of them again.

Code below perform hot encoding one by one instead of merging them and then hot encode.

train = pd.get_dummies(train, columns= ['is_discount', 'gender', 'city'])
test = pd.get_dummies(test, columns= ['is_discount', 'gender', 'city'])

Body:
Use concat with keys then divide i.e

#Example Dataframes
train = pd.DataFrame({'x':[1,2,3,4]})
test = pd.DataFrame({'x':[4,2,5,0]})

# Concat with keys
temp = pd.get_dummies(pd.concat([train,test],keys=[0,1]), columns=['x'])

# Selecting data from multi index
train,test = temp.xs(0),temp.xs(1)

Output :

#Train
  x_0  x_1  x_2  x_3  x_4  x_5
0    0    1    0    0    0    0
1    0    0    1    0    0    0
2    0    0    0    1    0    0
3    0    0    0    0    1    0

#Test
   x_0  x_1  x_2  x_3  x_4  x_5
0    0    0    0    0    1    0
1    0    0    1    0    0    0
2    0    0    0    0    0    1
3    1    0    0    0    0    0


问:
Unable to print CCK field in template in Drupal
I'm trying to print CCK field in my node.tpl.php -file like this;

    print $node->field_name_here[0]['view'];

But when I navigate to that page, I can't see the contents.
Even when i use print_r($node); I can't see any info about the variable. Drupal only renders everything else in node.tpl.php -file.

BUT... if I stop the execution of node.tpl.php by putting die(); anywhere after the print_r() or
    print $node->field_name_here[0]['view'];
 the CCK field / variable renders as it should.

It's not issue with permission since I have allowed all users to see the contents of these fields. I even tried to disable and uninstall CCK field permissions -module, but still can't print CCK fields in my template properly.

What am I missing here?

答:
shouldnt it be the following?

```<code> print $node->field_name_here[0]['value'];
</code>```

instead?  (value instead of view) -  In scripts i acces them like that and it's also shown on the node's devel tab

Body:
shouldnt it be the following?

 print $node->field_name_here[0]['value'];

instead?  (value instead of view) -  In scripts i acces them like that and it's also shown on the node's devel tab


问:
Uncommitted Postgresql Row lock
I was wondering if anyone knows how to release a lock from an uncommitted dead function?

Lets say that I have a service that does a lock on a row of data, yet before the lock is commited, I terminate the service. What would happen with the locked row and how would I release the lock?
Thanks.

答: As soon as the function has ended and the transaction if finished, the locks are gone.</p>

Title: Uncommitted Postgresql Row lock


问:
Convert Decimal to Binary using Recursion Java
I am trying to simply convert to Binary with recursion. I am having problems with the return statement. This compiles but give an overflow error when run. I don't know what to return (or if my statement is wrong) to prevent this error.

Thanks!

```<code>public static String convertToBinary(int number)
{
  if(number > 0)
    {
      convertToBinary(number / 2);
      convertToBinary((number % 2 ));
     }

   return convertToBinary((number));
}
</code>```

答:
```<code>class DecBin {
    static int convert(int i) {
        if (i > 0) {
            convert (i/2);
            System.out.println(i%2);
            return 0;
        } else {
            return 0;
        }
     }

    public static void main(String[]  args) {
        DecBin.convert(10);
    }
}
</code>```

Body:
I am trying to simply convert to Binary with recursion. I am having problems with the return statement. This compiles but give an overflow error when run. I don't know what to return (or if my statement is wrong) to prevent this error.

Thanks!

public static String convertToBinary(int number)
{
  if(number > 0)
    {
      convertToBinary(number / 2);
      convertToBinary((number % 2 ));
     }

   return convertToBinary((number));
}


问:
How to make an ImageView with rounded corners?
In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

Note that from 2021 onwards, simply use ShapeableImageView

答:
here my solution:

```<code><com.myproject.ui.RadiusCornerImageView
        android:id="@+id/imageViewPhoto"
        android:layout_width="160dp"
        android:layout_height="160dp"
        app:corner_radius_dp="5"
        app:corner_radius_position="top"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</code>```

And in java code:

```<code>public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
    private int cornerRadiusDP = 0; // dp
    private int corner_radius_position;

    public RadiusCornerImageView(Context context) {
        super(context);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
        try {
            cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
            corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
        } finally {
            typeArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
        Path clipPath = new Path();
        RectF rect = null;
        if (corner_radius_position == 0) { // all
            // round corners on all 4 angles
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        } else if (corner_radius_position == 1) {
            // round corners only on top left and top right
            rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);

    } else {
        throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
    }
    clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
    canvas.clipPath(clipPath);
    super.onDraw(canvas);
 }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
here my solution:

<com.myproject.ui.RadiusCornerImageView
        android:id="@+id/imageViewPhoto"
        android:layout_width="160dp"
        android:layout_height="160dp"
        app:corner_radius_dp="5"
        app:corner_radius_position="top"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

And in java code:

public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
    private int cornerRadiusDP = 0; // dp
    private int corner_radius_position;

    public RadiusCornerImageView(Context context) {
        super(context);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
        try {
            cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
            corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
        } finally {
            typeArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
        Path clipPath = new Path();
        RectF rect = null;
        if (corner_radius_position == 0) { // all
            // round corners on all 4 angles
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        } else if (corner_radius_position == 1) {
            // round corners only on top left and top right
            rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);

    } else {
        throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
    }
    clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
    canvas.clipPath(clipPath);
    super.onDraw(canvas);
 }
}


问:
How to verify installed spaCy version?
I have installed spaCy with python for my NLP project.

I have installed that using pip.  How can I verify installed spaCy version?

using

```<code>pip install -U spacy
</code>```

What is command to verify installed spaCy version?

答: You can also do python -m spacy info. If you're updating an existing installation, you might want to run python -m spacy validate, to check that the models you already have are compatible with the version you just installed.

Title: How to verify installed spaCy version?

Body:
I have installed spaCy with python for my NLP project.

I have installed that using pip.  How can I verify installed spaCy version?

using

pip install -U spacy

What is command to verify installed spaCy version?


问:
Custom Login Page for Sharepoint 2010
I'm trying to create a custom login page for my SP2010 site.

Now, I understand that I need to enable FBA (Form Based Authentication) for my application, but I couldn't do this. Because; new, extend and delete buttons are disabled in Web Application management page in Central Administration. Therefore, don't know why (I'm the admin and all), but I can't create a web application to enable forms authentication type.

I've done some reading on the net, but every page suggests a way that I can't follow because of the reasons above.

What should I do?

Thanks.

答:
Is your user a member of farm administrators and a local administrator on all WFE in the farm? you need those permissions to create new web applications, because it creates new IIS websites.

Once the buttons becomes enabled, with sharepoint 2010 you will be creating a new web application that is "claims" based.

Title: Custom Login Page for Sharepoint 2010


问:
Display Titles From two other tables
I have a CONTAINS table in my DB:

```<code>CREATE TABLE CONTAINS(
    album_id INTEGER NOT NULL REFERENCES Album,
    song_id INTEGER NOT NULL REFERENCES Song,
    PRIMARY KEY(album_id , song_id)
);
</code>```

I have two Other Tables ALBUM and SONG:

```<code>CREATE TABLE ALBUM(
    album_id INTEGER NOT NULL,
    title TEXT NOT NULL,
    PRIMARY KEY(album_id)
);

CREATE TABLE SONG(
    song_id INTEGER NOT NULL,
    title TEXT NOT NULL,
    PRIMARY KEY(album_id)
);
</code>```

If I do SELECT * FROM CONTAINS, I will get Album_Id and their respective Song_Id s. Now how do I display the album names and song names instead of their IDs?

答:
Try this query:</p>

```<code>select a.title as album_name,s.title as song_name
from contains c join album a
on c.album_id=a.album_id
join song s
on c.song_id=s.song_id;
</code>```

Title: Display Titles From two other tables

Body:
I have a CONTAINS table in my DB:

CREATE TABLE CONTAINS(
    album_id INTEGER NOT NULL REFERENCES Album,
    song_id INTEGER NOT NULL REFERENCES Song,
    PRIMARY KEY(album_id , song_id)
);

I have two Other Tables ALBUM and SONG:

CREATE TABLE ALBUM(
    album_id INTEGER NOT NULL,
    title TEXT NOT NULL,
    PRIMARY KEY(album_id)
);

CREATE TABLE SONG(
    song_id INTEGER NOT NULL,
    title TEXT NOT NULL,
    PRIMARY KEY(album_id)
);

If I do SELECT * FROM CONTAINS, I will get Album_Id and their respective Song_Id s. Now how do I display the album names and song names instead of their IDs?

Body:
Try this query:

select a.title as album_name,s.title as song_name
from contains c join album a
on c.album_id=a.album_id
join song s
on c.song_id=s.song_id;


答:
First of all itms and itms-apps are defined Apple URL Schemes and they are only linked immediately to their specific app as you said itms will open iTunes Store and itms-apps will open the App Store.(if they exist)

```<code>    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url!, options: [:]) { (finished) in
        }
    } else {
        // Fallback on earlier versions
        UIApplication.shared.openURL(url!)
    }
</code>```

Using https if used with openURL or open will launch the App Store if exist or iOS supported otherwise it will launch Safari.

Title: What is the difference between itms-app:// and https:// App Store link

Body:
I'm trying to create the link to App Store and I found many ways to do it.

Open App Store page in iTunes Store.

let url  = URL(string: "itms://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")

Open App Store.

let url  = URL(string: "https://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542")

Open App Store.

let url  = URL(string: "itms-apps://itunes.apple.com/th/app/cafe-amazon-smart-pay/id1047593542?mt=8")

As far as I know, Method #2 and #3 almost produce the same result.

But I curious it should have some difference?.

Body:
First of all itms and itms-apps are defined Apple URL Schemes and they are only linked immediately to their specific app as you said itms will open iTunes Store and itms-apps will open the App Store.(if they exist)

    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url!, options: [:]) { (finished) in
        }
    } else {
        // Fallback on earlier versions
        UIApplication.shared.openURL(url!)
    }

Using https if used with openURL or open will launch the App Store if exist or iOS supported otherwise it will launch Safari.


问:
How to create a dataview In Sharepoint with data from a join query?
I have 3 Lists in Sharepoint.

I want to create a dataview that is a join of 3 tables.

Table1 is joined with Table2 on FieldA
Table 2 is joined to Table3 on FieldB

Table1 has duplicate values in FieldA so I need to only return one value to join with Table2.

In Access my query looks like this:
SELECT DISTINCT WRK_InputWorkOrders.WorkOrder, Production1.[Part Number], Production1.[Work Order], Production1.Location, StationItems.Station, Production1.Description, Production1.Revision, WRK_InputWorkOrders.Status
FROM StationItems INNER JOIN (WRK_InputWorkOrders INNER JOIN Production1 ON WRK_InputWorkOrders.WorkOrder = Production1.[Work Order]) ON StationItems.Item = Production1.[Part Number]
WHERE (((WRK_InputWorkOrders.Status)<>"closed"));

Is there a way to write sql-like queries for dataviews?

I have Sharepoint Designer 2007 and Access.

The goal is to get a report that a user can view in Internet Explorer.
I have tried using this method. But it returns duplicate records
I found this suggestion. It suggests using an XPath Filter
not(@yourvalue = preceding-sibling::dfs:YourRepeatingRowName/@yourvalue)

But wasn't able to get it to work. I don't know what to enter as YourRepeatingRowName

I found this link. Does anyone know if it can be used to perform such a join?

答:
I found this third part add on

Enesys RS Data Extension lets you query (retrieve, join, merge,...) data from any SharePoint list and use the result for building "Reporting Services" reports as you would do with any other data sources. http://www.enesyssoftware.com/

I can't use it because I am currently running the basic Sharepoint version that uses the internal database.


问:
Undoing a git merge
I'm not that experienced with Git and now I have a big problem falling into my lap.

Here's how my current branch look like:

```<code>feature       /---F1-----F2----\
             /                  \
master -----M0-----M1-----M2-----M3-----M4
             \                        /
bugfix        \--B1-----B2-----------/
</code>```

The situation:

Someone did a very bad thing and pushed a really bad merge (M3). I only noticed the bad merge when our models (not source code) wouldn't load after I merged B1 and B2 into M4. Luckily, I haven't pushed M4 yet.

The problem:

How do I set things right again? I want M0, M1, M2, F1, F2, B1, and B2. But I don't want M3 and M4 (since M4 is obviously broken). If I have to abandon changes, then F1 and F2 can be sacrificed :)

I looked at git revert but I'm not confident that I fully understand how it works. So... I'm really hoping for help on how to resolve this.

Thanks in advance.

答:
So to clarify, what you want is this, right?

```<code>feature       /---F1-----F2
             /
master -----M0-----M1-----M2
             \
bugfix        \--B1-----B2
</code>```

Make sure that the HEADs feature and bugfix are still on F2 and B2 respectively.

Edit: if feature and bugfix are no branches, make them branches (stash your work if it is uncommited):

```<code>git checkout F2
git branch feature
git checkout B2
git branch bugfix
</code>```

Edit end

Then reset the master to M2:

```<code>git checkout master
git reset M2 --hard
</code>```

(reset will make you lose your local changes, stash them if you don't want that.)

M3 and M4 are not destroyed right away, but will be eventually. They should not show up in git log or gitk.

Then it's time to merge feature and make a M3' that is correct.

Title: Undoing a git merge

Body:
I'm not that experienced with Git and now I have a big problem falling into my lap.

Here's how my current branch look like:

feature       /---F1-----F2----\
             /                  \
master -----M0-----M1-----M2-----M3-----M4
             \                        /
bugfix        \--B1-----B2-----------/

The situation:

Someone did a very bad thing and pushed a really bad merge (M3). I only noticed the bad merge when our models (not source code) wouldn't load after I merged B1 and B2 into M4. Luckily, I haven't pushed M4 yet.

The problem:

How do I set things right again? I want M0, M1, M2, F1, F2, B1, and B2. But I don't want M3 and M4 (since M4 is obviously broken). If I have to abandon changes, then F1 and F2 can be sacrificed :)

I looked at git revert but I'm not confident that I fully understand how it works. So... I'm really hoping for help on how to resolve this.

Thanks in advance.

Body:
So to clarify, what you want is this, right?

feature       /---F1-----F2
             /
master -----M0-----M1-----M2
             \
bugfix        \--B1-----B2

Make sure that the HEADs feature and bugfix are still on F2 and B2 respectively.

Edit: if feature and bugfix are no branches, make them branches (stash your work if it is uncommited):

git checkout F2
git branch feature
git checkout B2
git branch bugfix

Edit end

Then reset the master to M2:

git checkout master
git reset M2 --hard

(reset will make you lose your local changes, stash them if you don't want that.)

M3 and M4 are not destroyed right away, but will be eventually. They should not show up in git log or gitk.

Then it's time to merge feature and make a M3' that is correct.


问:
Why isn't my ListView's selection changed event being triggered?
Why isn't my ListView's selection changed event being triggered?

I expect the selected True attribute to generate the InputContentType message.

However it doesn't.

```<code>listview =
    select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
        [ option [ value "instructions" ] [ text "Content Type" ]
        , option [ value "Article", selected True ] [ text "Article" ]
        , option [ value "Video" ] [ text "Video" ]
        ]
</code>```

In the actual code that I have (which isn't shown here), I programmatically select an item in my listview based on a value in a textbox. This is done in my view function.

Is there a recommended practice for achieving this?

Appendix:

```<code>type Msg
    = ...
    | InputContentType String
</code>```

答: Currently you have a fixed selection. Since the selected attribute is set to always True then "Article" will always be selected. My suggestion would be to add selected to every option, and then make the Bool contingent on which option is currently selected in the moment, information that should be stored in your model.

Body:
Why isn't my ListView's selection changed event being triggered?

I expect the selected True attribute to generate the InputContentType message.

However it doesn't.

listview =
    select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
        [ option [ value "instructions" ] [ text "Content Type" ]
        , option [ value "Article", selected True ] [ text "Article" ]
        , option [ value "Video" ] [ text "Video" ]
        ]

In the actual code that I have (which isn't shown here), I programmatically select an item in my listview based on a value in a textbox. This is done in my view function.

Is there a recommended practice for achieving this?

Appendix:

type Msg
    = ...
    | InputContentType String


问:
How to simplify with spread syntax es6
How to simplify the code, I tried to generate the object and call for each change method and depends on arguments(newValues) I change some field, seems I have duplicate code, how to avoid it this case? Should I use some more difficult method to avoid with spread syntax </p>

```<code>const formName = {
    fieldRange: 'miConfiguration.fieldRange',
    defaultTimeout: 'miConfiguration.doorConfiguration.defaultTimeout',
    standAlone: 'miConfiguration.doorConfiguration.standAlone',
    overrideTimeout: 'miConfiguration.doorConfiguration.overrideTimeout',
    inputMode: 'miConfiguration.doorConfiguration.inputMode',
    stopMi: 'miConfiguration.doorConfiguration.stopMi',
    activeLow: 'miConfiguration.doorConfiguration.activeLow',
    enableDualTechnology: 'miConfiguration.enableDualTechnology',
    passageName: 'miConfiguration.passageName',
}

let {fieldRange, defaultTimeout, standAlone, overrideTimeout, inputMode, stopMi, activeLow, enableDualTechnology, passageName} = formName

let configurationsMi = {
    [passageName]:  null,

    [fieldRange]: null,
    [activeLow]: false,
    [standAlone]: null,
    [defaultTimeout]: null,
    [overrideTimeout]: null,
    [inputMode]: null,
    [stopMi]: null,
    [enableDualTechnology]: false,
}

const defaultValues = {
    [MiConfigurationTypes.AccessPointOnly]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Disabled,
    },

    [MiConfigurationTypes.WanderingDetection]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
    },
    [MiConfigurationTypes.MuteWanderingDetection]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
    },
    [MiConfigurationTypes.LockedWanderingControl]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
        [standAlone]:  DoorStates.Locked,
        [defaultTimeout]: '00:00:03',
        [overrideTimeout]: '00:00:30',
        [inputMode]: InputModes.NotUsed,
        [stopMi]: false,
    },
    [MiConfigurationTypes.OpenWanderingControl]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
        [standAlone]:  DoorStates.Locked,
        [defaultTimeout]: '00:00:03',
        [overrideTimeout]: '00:00:30',
        [inputMode]: InputModes.NotUsed,
        [stopMi]: false,
    },
}

 onChange={(e, newValue) => {
                console.log(defaultValues)
                Object.keys(defaultValues[newValue]).forEach(key => change(key, defaultValues[newValue][key]))
            }}
</code>```

答:
You can just put the repeated section in an extra object literal - like you already did with configurationsMi - and refer to that.

```<code>const configurationsWanderingControl = {
    [fieldRange]:  MiFieldRanges.Small,
    [standAlone]:  DoorStates.Locked,
    [defaultTimeout]: '00:00:03',
    [overrideTimeout]: '00:00:30',
    [inputMode]: InputModes.NotUsed,
    [stopMi]: false,
};
const defaultValues = {
    …
    [MiConfigurationTypes.LockedWanderingControl]: {
        ...configurationsMi,
        ...configurationsWanderingControl,
    },
    [MiConfigurationTypes.OpenWanderingControl]: {
        ...configurationsMi,
        ...configurationsWanderingControl,
    },
};
</code>```

Of course there's also the default approach at avoiding duplication: put the repeated code in a function (possibly with parameters for the little details that differ), and call that from multiple places.

Title: How to simplify with spread syntax es6

Body:
How to simplify the code, I tried to generate the object and call for each change method and depends on arguments(newValues) I change some field, seems I have duplicate code, how to avoid it this case? Should I use some more difficult method to avoid with spread syntax

const formName = {
    fieldRange: 'miConfiguration.fieldRange',
    defaultTimeout: 'miConfiguration.doorConfiguration.defaultTimeout',
    standAlone: 'miConfiguration.doorConfiguration.standAlone',
    overrideTimeout: 'miConfiguration.doorConfiguration.overrideTimeout',
    inputMode: 'miConfiguration.doorConfiguration.inputMode',
    stopMi: 'miConfiguration.doorConfiguration.stopMi',
    activeLow: 'miConfiguration.doorConfiguration.activeLow',
    enableDualTechnology: 'miConfiguration.enableDualTechnology',
    passageName: 'miConfiguration.passageName',
}

let {fieldRange, defaultTimeout, standAlone, overrideTimeout, inputMode, stopMi, activeLow, enableDualTechnology, passageName} = formName

let configurationsMi = {
    [passageName]:  null,

    [fieldRange]: null,
    [activeLow]: false,
    [standAlone]: null,
    [defaultTimeout]: null,
    [overrideTimeout]: null,
    [inputMode]: null,
    [stopMi]: null,
    [enableDualTechnology]: false,
}

const defaultValues = {
    [MiConfigurationTypes.AccessPointOnly]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Disabled,
    },

    [MiConfigurationTypes.WanderingDetection]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
    },
    [MiConfigurationTypes.MuteWanderingDetection]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
    },
    [MiConfigurationTypes.LockedWanderingControl]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
        [standAlone]:  DoorStates.Locked,
        [defaultTimeout]: '00:00:03',
        [overrideTimeout]: '00:00:30',
        [inputMode]: InputModes.NotUsed,
        [stopMi]: false,
    },
    [MiConfigurationTypes.OpenWanderingControl]: {
        ...configurationsMi,
        [fieldRange]:  MiFieldRanges.Small,
        [standAlone]:  DoorStates.Locked,
        [defaultTimeout]: '00:00:03',
        [overrideTimeout]: '00:00:30',
        [inputMode]: InputModes.NotUsed,
        [stopMi]: false,
    },
}

 onChange={(e, newValue) => {
                console.log(defaultValues)
                Object.keys(defaultValues[newValue]).forEach(key => change(key, defaultValues[newValue][key]))
            }}

Body:
You can just put the repeated section in an extra object literal - like you already did with configurationsMi - and refer to that.

const configurationsWanderingControl = {
    [fieldRange]:  MiFieldRanges.Small,
    [standAlone]:  DoorStates.Locked,
    [defaultTimeout]: '00:00:03',
    [overrideTimeout]: '00:00:30',
    [inputMode]: InputModes.NotUsed,
    [stopMi]: false,
};
const defaultValues = {
    …
    [MiConfigurationTypes.LockedWanderingControl]: {
        ...configurationsMi,
        ...configurationsWanderingControl,
    },
    [MiConfigurationTypes.OpenWanderingControl]: {
        ...configurationsMi,
        ...configurationsWanderingControl,
    },
};

Of course there's also the default approach at avoiding duplication: put the repeated code in a function (possibly with parameters for the little details that differ), and call that from multiple places.


问:
Are messages encrypted when consuming from Event Hub to my application? Is it SSL Secured?
I am consuming messages from the Azure Event Hub to my application and I am successfully receiving the messages. I want to know whether the messages sent from the Event Hub is encrypted. I searched in learn.microsoft.com but could not find much information. It would be a great help if anyone can help me out to understand.</p>

答:
Short answer: yes.

As you can find in the docs:

Any entity that reads event data from an event hub is an event consumer. All Event Hubs consumers connect via the AMQP 1.0 session and events are delivered through the session as they become available...

Now, there is more documentation around the use of AMQP regarding to the Service Bus and Event Hub, it can be found here:

It is the primary protocol of Azure Service Bus Messaging and Azure Event Hubs. Both services also support HTTPS.

and, more important in this context:

Azure Service Bus ( note: also Event Hub ) requires the use of TLS at all times. It supports connections over TCP port 5671, whereby the TCP connection is first overlaid with TLS before entering the AMQP protocol handshake, and also supports connections over TCP port 5672 whereby the server immediately offers a mandatory upgrade of connection to TLS using the AMQP-prescribed model. The AMQP WebSockets binding creates a tunnel over TCP port 443 that is then equivalent to AMQP 5671 connections.

In addition, Event Hub data is encrypted at rest, see [the docs])(https://learn.microsoft.com/en-us/azure/security/azure-security-encryption-atrest)


问:
C - Null Terminating char doesnt stop printing
in this part of code:

```<code>char* data;
char num[10];

sprintf(num, "%d", 260);
strcat(data, num);
strcat(data, "\0");

sprintf(num, "%d", 130);
strcat(data, num);

sprintf(num, "%d", 128);
strcat(data, num);

printf("Data: %s", data);
</code>```

it's printing:

```<code>Data: 260130128
</code>```

Why does this happen? The null terminator character shouldnt terminate the printing?

Thank you

Edits:

The data has been initialized before, I am getting it from a function.

Why does not print only 260? How can I do it?

答:
You need to use strcpy to copy the substring into your buffer after the existing data+NUL. Because you're basically putting multiple strings into a buffer you'll have to keep track of the total length of the data in the buffer yourself:

```<code>#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
  {
  char data[100] = "";
  char num[10];
  int  data_len = 0;

  sprintf(num, "%d", 260);
  strcpy(data+data_len, num);
  data_len += strlen(num)+1;

  sprintf(num, "%d", 130);
  strcpy(data+data_len, num);
  data_len += strlen(num)+1;

  sprintf(num, "%d", 128);
  strcpy(data+data_len, num);
  data_len += strlen(num)+1;

  printf("data_len = %d\n", data_len);
  printf("Data: %s\n", data);
  }
</code>```

Best of luck.

Body:
in this part of code:

char* data;
char num[10];

sprintf(num, "%d", 260);
strcat(data, num);
strcat(data, "\0");

sprintf(num, "%d", 130);
strcat(data, num);

sprintf(num, "%d", 128);
strcat(data, num);

printf("Data: %s", data);

it's printing:

Data: 260130128

Why does this happen? The null terminator character shouldnt terminate the printing?

Thank you

Edits:

The data has been initialized before, I am getting it from a function.

Why does not print only 260? How can I do it?

Body:
You need to use strcpy to copy the substring into your buffer after the existing data+NUL. Because you're basically putting multiple strings into a buffer you'll have to keep track of the total length of the data in the buffer yourself:

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
  {
  char data[100] = "";
  char num[10];
  int  data_len = 0;

  sprintf(num, "%d", 260);
  strcpy(data+data_len, num);
  data_len += strlen(num)+1;

  sprintf(num, "%d", 130);
  strcpy(data+data_len, num);
  data_len += strlen(num)+1;

  sprintf(num, "%d", 128);
  strcpy(data+data_len, num);
  data_len += strlen(num)+1;

  printf("data_len = %d\n", data_len);
  printf("Data: %s\n", data);
  }

Best of luck.


问:
Android Volley newRequestQueue - Incompatible types
I'm making application for getting data from server with Volley. But when I need to get request:

```<code>rq = Volley.newRequestQueue(this);
</code>```

Getting this error

I already set INTERNET permission in Manifest and also in app set: compile 'com.android.volley:volley:1.0.0'

My all code:

```<code>package com.example.doma.fp;

import android.net.http.RequestQueue;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    RequestQueue rq ;
    TextView nameText;

    String name;

    String url = "http://127.0.0.1/OOP/database/android.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rq = Volley.newRequestQueue(this);
        nameText = (TextView) findViewById(R.id.textname);

      //  sendjsonrequest();

    }

    public void sendjsonrequest()
    {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    name = response.getString("name");

                    nameText.setText(name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

    }

}
</code>```

Thanks for help.

答: You have imported android.net.http.RequestQueue instead of com.android.volley.RequestQueue;</p>

Body:
I'm making application for getting data from server with Volley. But when I need to get request:

rq = Volley.newRequestQueue(this);

Getting this error

I already set INTERNET permission in Manifest and also in app set: compile 'com.android.volley:volley:1.0.0'

My all code:

package com.example.doma.fp;

import android.net.http.RequestQueue;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    RequestQueue rq ;
    TextView nameText;

    String name;

    String url = "http://127.0.0.1/OOP/database/android.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rq = Volley.newRequestQueue(this);
        nameText = (TextView) findViewById(R.id.textname);

      //  sendjsonrequest();

    }

    public void sendjsonrequest()
    {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    name = response.getString("name");

                    nameText.setText(name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

    }

}

Thanks for help.


问:
How to list files ignored by git that are currently staged or committed?
How does one get a list of those files that match a rule in .gitignore file, but that have been staged or committed in the past?</p>

答:
Just going to leave this one here, based on Richard's answer:

git ls-files --cached -i --exclude-standard

To delete every tracked file that is ignored by .gitignore:

git ls-files --cached -i --exclude-standard | xargs git rm --cached


问:
scikit learn documentation in PDF
Does anyone have any idea how I can get the scikit learn documentation (http://scikit-learn.org/stable/documentation.html) specifically the user guide, tutorials and examples, in PDF format?

If they are not readily available, is there a way to convert them to PDF programmatically? I looked around for html to pdf conversion api services but none of them is free...

Thanks in advance.

答:
According to:
https://github.com/scikit-learn/scikit-learn/tree/master/doc

more recent versions are here:
https://github.com/scikit-learn/scikit-learn.github.io

in 0.1x/_downloads/scikit-learn-docs.pdf.

e.g. the most recent as of today is:
https://github.com/scikit-learn/scikit-learn.github.io/blob/master/0.19/_downloads/scikit-learn-docs.pdf

Title: scikit learn documentation in PDF


问:
How to prevent xtick labels too cramped?
With xticks automatically generated by gnuplot we find too often that the labels are too tight / cramped together as shown in this snapshot.
How can we fix this issue?

答:
This is a very crude workaround. The idea is telling how many (approximate) number of tick labels one wants, and have gnuplot "translate" that into a suitable tick spacing according to the whole plotting range.

I am posting what I am using now, and it works reasonably well.
It takes xmin=0.
You could guess the way it works and tune it.

```<code># Get/print stats about input data, ...
stats "output.csv"  using 2:5  nooutput
# ... and use them for setting the number of tick labels for x axes, to avoid overlap
#tmin = STATS_min_x
tmin = 0
tmax = STATS_max_x
nxtics = 5                        # Tune this
# Do not count 0 as a tick
nxtics = nxtics - 1
# Shift numbers to the range [1,10)
ttic1 = tmax / nxtics
nshift_digits = -floor(log10(ttic1))
shift = 10.0**nshift_digits
tmax_shift = tmax * shift
ttic1_shift = ttic1 * shift
# ttic1_shift should be between [1,10)
# Use (arbitrary) specified tick spacing (here at 1, 2, 5 in the first significant digit, but one could use others, including 2.5, e.g.), which better matches the data range and selected number of tick labels. Note that the number of tick labels would not be strictly maintained.
# Tune these numbers
ttic_shift = 1.0
if (ttic1_shift < 1.3) {
    ttic_shift = 1.0
} else { if (ttic1_shift < 3.0) {
    ttic_shift = 2.0
} else { if (ttic1_shift < 7.0) {
    ttic_shift = 5.0
} else {
    ttic_shift = 10.0
} } }
ttic = ttic_shift / shift
print "ttic=", ttic
</code>```

PS: I could not have this working, although I did not try "hard". I guess that solution might work for a single plotted dataset, but not sure it would work for more than one.

Body:
This is a very crude workaround. The idea is telling how many (approximate) number of tick labels one wants, and have gnuplot "translate" that into a suitable tick spacing according to the whole plotting range.

I am posting what I am using now, and it works reasonably well.
It takes xmin=0.
You could guess the way it works and tune it.

# Get/print stats about input data, ...
stats "output.csv"  using 2:5  nooutput
# ... and use them for setting the number of tick labels for x axes, to avoid overlap
#tmin = STATS_min_x
tmin = 0
tmax = STATS_max_x
nxtics = 5                        # Tune this
# Do not count 0 as a tick
nxtics = nxtics - 1
# Shift numbers to the range [1,10)
ttic1 = tmax / nxtics
nshift_digits = -floor(log10(ttic1))
shift = 10.0**nshift_digits
tmax_shift = tmax * shift
ttic1_shift = ttic1 * shift
# ttic1_shift should be between [1,10)
# Use (arbitrary) specified tick spacing (here at 1, 2, 5 in the first significant digit, but one could use others, including 2.5, e.g.), which better matches the data range and selected number of tick labels. Note that the number of tick labels would not be strictly maintained.
# Tune these numbers
ttic_shift = 1.0
if (ttic1_shift < 1.3) {
    ttic_shift = 1.0
} else { if (ttic1_shift < 3.0) {
    ttic_shift = 2.0
} else { if (ttic1_shift < 7.0) {
    ttic_shift = 5.0
} else {
    ttic_shift = 10.0
} } }
ttic = ttic_shift / shift
print "ttic=", ttic

PS: I could not have this working, although I did not try "hard". I guess that solution might work for a single plotted dataset, but not sure it would work for more than one.


问:
Access Tasks in Eclipse
The lines with // TODO are available in Task Section in Eciplse IDE. How can we access the List of Items in Tasks Section.

Presently we can add tags using IMarker library.  But to access them from Task Section is not available.

Screenshot of Eclipse IDE

答:
You use the IResource findMarkers method to get any marker.

IResource resource = .... any file, folder, workspace root ...

IMarker[] markers = resource.findMarkers(IMarker.TASK, true, IResource.DEPTH_ZERO);
```

<p><code>IMarker.TASK</code> gives you the tasks list. <code>IResource.DEPTH_ZERO</code> searches child resources as well.</p>

<p>You get the line number from a marker with:</p>

<pre class="lang-java prettyprint-override"><code>int lineNumber = marker.getAttribute(IMarker.LINE_NUMBER, -1);
</code>```

Title: Access Tasks in Eclipse

Body:
You use the IResource findMarkers method to get any marker.

IResource resource = .... any file, folder, workspace root ...

IMarker[] markers = resource.findMarkers(IMarker.TASK, true, IResource.DEPTH_ZERO);

IMarker.TASK gives you the tasks list. IResource.DEPTH_ZERO searches child resources as well.

You get the line number from a marker with:

int lineNumber = marker.getAttribute(IMarker.LINE_NUMBER, -1);


问:
Drop down of auto values country/state/city WooCommerce storefront
I am looking for a drop down of country/state/city. I am getting country state auto populated, but cities are not going through well. By default, I am able to get the countries.</p>
```<code>// State-Country additions

/**
 * Code goes in functions.php or a custom plugin.
 */

add_filter('woocommerce_states', 'SA_woocommerce_states');

function SA_woocommerce_states($states) {
    $states['ZA'] = array(
        'EC' => __('Eastern Cape', 'woocommerce'),
    );
    return $states;
}

// Change "city" checkout billing and shipping fields to a dropdown

add_filter('woocommerce_checkout_fields', 'override_checkout_city_fields');

function override_checkout_city_fields($fields) {

    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
        '' => __('Select your city'),
        'a' => 'a',
    );

    $fields['billing']['billing_city']['type'] = 'select';
    $fields['billing']['billing_city']['options'] = $option_cities;
    $fields['shipping']['shipping_city']['type'] = 'select';
    $fields['shipping']['shipping_city']['options'] = $option_cities;

    return $fields;
}
</code>```

答:
With your actual code you are replacing all existing states of "South Africa" (ZA) by one state. So you are getting something like:

To add this state you should need to change your code a little bit this way:

```<code>add_filter('woocommerce_states', 'sa_woocommerce_states');
add_filter('woocommerce_countries_allowed_country_states', 'sa_woocommerce_states');

function SA_woocommerce_states( $states ) {
    $states['ZA']['EC'] = __('Eastern Cape', 'woocommerce');
    return $states;
}
</code>```

The code goes in the function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works. You will get that instead this time:

Now to get the cities auto populated you should use this:

```<code>add_filter( 'woocommerce_default_address_fields', 'override_checkout_city_fields', 10, 1 );
function override_checkout_city_fields($fields) {

    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
        '' => __( 'Select your city' ),
        'a' => 'a',
    );

    $fields['city']['type'] = 'select';
    $fields['city']['options'] = $option_cities;

    return $fields;
}
</code>```

The code goes in the function.php file of your active child theme (or theme) or also in any plugin file.

It was tested ad worked…

But you will not get cities by states as this is a real development and too broad for Stack Overflow

Body:
I am looking for a drop down of country/state/city. I am getting country state auto populated, but cities are not going through well. By default, I am able to get the countries.

// State-Country additions

/**
 * Code goes in functions.php or a custom plugin.
 */

add_filter('woocommerce_states', 'SA_woocommerce_states');

function SA_woocommerce_states($states) {
    $states['ZA'] = array(
        'EC' => __('Eastern Cape', 'woocommerce'),
    );
    return $states;
}

// Change "city" checkout billing and shipping fields to a dropdown

add_filter('woocommerce_checkout_fields', 'override_checkout_city_fields');

function override_checkout_city_fields($fields) {

    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
        '' => __('Select your city'),
        'a' => 'a',
    );

    $fields['billing']['billing_city']['type'] = 'select';
    $fields['billing']['billing_city']['options'] = $option_cities;
    $fields['shipping']['shipping_city']['type'] = 'select';
    $fields['shipping']['shipping_city']['options'] = $option_cities;

    return $fields;
}

Body:
With your actual code you are replacing all existing states of "South Africa" (ZA) by one state. So you are getting something like:

To add this state you should need to change your code a little bit this way:

add_filter('woocommerce_states', 'sa_woocommerce_states');
add_filter('woocommerce_countries_allowed_country_states', 'sa_woocommerce_states');

function SA_woocommerce_states( $states ) {
    $states['ZA']['EC'] = __('Eastern Cape', 'woocommerce');
    return $states;
}

The code goes in the function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works. You will get that instead this time:

Now to get the cities auto populated you should use this:

add_filter( 'woocommerce_default_address_fields', 'override_checkout_city_fields', 10, 1 );
function override_checkout_city_fields($fields) {

    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
        '' => __( 'Select your city' ),
        'a' => 'a',
    );

    $fields['city']['type'] = 'select';
    $fields['city']['options'] = $option_cities;

    return $fields;
}

The code goes in the function.php file of your active child theme (or theme) or also in any plugin file.

It was tested ad worked…

But you will not get cities by states as this is a real development and too broad for Stack Overflow


问:
Octlet, quad word or what?
I am translating some documentation on libraw1394 to Russian. The documentation on libraw1394 says:

The basic data structures defined in
  the standard and used in this document
  are the quadlet (32 bit quantity) and
  the octlet (64 bit quantity)...

There is no such unit like "octlet" in Russian. I used to use "quad word" (russian "chetvertnoye slovo") for 64 bit quantity. Would it be correct to substitute "octlet" by "quad word"?

What are the alternative terms for "octlet"?

答: I've never heard of an "octlet" before. Can't you just translate "64-bit quantity" literally? I find "quad word" confusing as well, as on a native 64-bit platform, a "word" could be considered to be 64 bits as well. In fact, this whole definition of a "word" seems to go back to the bad old days of 16-bit computing.</p>

Title: Octlet, quad word or what?


问:
How to pass url value in django to views
My url.py is as below,

```<code>from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
]
</code>```

Now my views.py is as below,

```<code>@api_view(['GET'])
def get_request(request):
   #How can I get request ID (base url here)?
   return HttpResponse('test')
</code>```

In the above if I do request in my browser with url as below it reaches my get_request method,

```<code>http://localhost:8080/myapp/get_requests/
</code>```

But the same gives error 404 when I try with some ID in the end as below,

```<code>http://localhost:8080/myapp/get_requests/40
</code>```

Now How can I get this ID number 40 in my views.py method?

答:
If you want to pick up id from url, you just have to write something like this :

```<code>@login_required
def MyFunction(request, id) :

    myobject = get_object_or_404(MyModel, pk=id)

    context = {
            "myobject" : myobject,
    }

    return render(request, 'my template.html', context)
</code>```

And your url, you have to add url(r'^myapp/get_requests/(?P<id>\d+)/$', views.get_requests),

I assume your url is correct and he's already created with id inside. So I just gave you How I pick up object according to this ID.

Body:
My url.py is as below,

from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
]

Now my views.py is as below,

@api_view(['GET'])
def get_request(request):
   #How can I get request ID (base url here)?
   return HttpResponse('test')

In the above if I do request in my browser with url as below it reaches my get_request method,

http://localhost:8080/myapp/get_requests/

But the same gives error 404 when I try with some ID in the end as below,

http://localhost:8080/myapp/get_requests/40

Now How can I get this ID number 40 in my views.py method?

Body:
If you want to pick up id from url, you just have to write something like this :

@login_required
def MyFunction(request, id) :

    myobject = get_object_or_404(MyModel, pk=id)

    context = {
            "myobject" : myobject,
    }

    return render(request, 'my template.html', context)

And your url, you have to add url(r'^myapp/get_requests/(?P<id>\d+)/$', views.get_requests),

I assume your url is correct and he's already created with id inside. So I just gave you How I pick up object according to this ID.


答:
Seems you've imported the wrong class...

This

```<code>import android.net.http.RequestQueue;
</code>```

supposed to be -

```<code>import com.android.volley.RequestQueue;
</code>```

Title: Android Volley newRequestQueue - Incompatible types

Body:
Seems you've imported the wrong class...

This

import android.net.http.RequestQueue;

supposed to be -

import com.android.volley.RequestQueue;


答:
The problem with your code is the dimension of A[i] in your code.
A is initialised as matrix[1,n] (1 row and n columns - you have double [[]] brackets in np.array([[]])), so you reference of type A[i] actually means "the whole i'th row, or an array(n) in this case).
I'm quite new to python and numpy, but to access individual cells and set each to 1 or 0 could be coded this way (of course, only if you are forced to use FOR loops here):

```<code> for i in range(A.shape[1]):
 if A[0,i]>0.5:
    Y_prediction[0,i] = 1
 else:
    Y_prediction[0,i] = 0
</code>```

But,definitely, the best solution, as others described above, is to avoid for loop.

Title: convert numpy array to 0 or 1

Body:
A = np.array([[0.94366988, 0.86095311, 0.88896715, 0.93630641, 0.74075403, 0.52849619
                  , 0.03094677, 0.85707681, 0.88457925, 0.67279696, 0.26601085, 0.4823794
                  , 0.74741157, 0.78575729, 0.00978911, 0.9203284, 0.02453695, 0.84884703
                  , 0.2050248, 0.03703224, 0.92931392, 0.11930532, 0.01411064, 0.7832698
                  , 0.58188015, 0.66897565, 0.75119007, 0.01323558, 0.03402649, 0.99735115
                  , 0.21031727, 0.78123225, 0.6815842, 0.46647604, 0.66323375, 0.03424828
                  , 0.08031627, 0.76570656, 0.34760863, 0.06177743, 0.6987531, 0.4106426
                  , 0.6648871, 0.02776868, 0.93053125, 0.46395717, 0.23971605, 0.9771735
                  , 0.66202407, 0.10482388]])

Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5)

for i in range(A.shape[1]):
if A[i]>0.5:
    Y_prediction[i] = 1
else:
    Y_prediction[i] = 0

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

And how to use vectorize this
thx

Body:
The problem with your code is the dimension of A[i] in your code.
A is initialised as matrix[1,n] (1 row and n columns - you have double [[]] brackets in np.array([[]])), so you reference of type A[i] actually means "the whole i'th row, or an array(n) in this case).
I'm quite new to python and numpy, but to access individual cells and set each to 1 or 0 could be coded this way (of course, only if you are forced to use FOR loops here):

 for i in range(A.shape[1]):
 if A[0,i]>0.5:
    Y_prediction[0,i] = 1
 else:
    Y_prediction[0,i] = 0

But,definitely, the best solution, as others described above, is to avoid for loop.


问:
Wpf: How to color portion of a rectangle based on percentage?
I need to split a rectangle and color the various portions based on percentage, I've looked around and found some solutions but I can't understand which one is the best option for what I need. I post here an image showing what I need.

please can anyone point me in the right direction? Thanks

答:
How about using a Grid layout? You can define the rows using percentages and then define for each row a border and background color.
You can read more about Grid in the link. Grid Tutorial

You can find more details here. I think the option of placing a Border inside each cell should be a good fit here.