问:
Calling methods in different classes from one button in Kivy
Edit:  So I answered my first question which was right in the Kivy docs :-).
Basically I needed to add a propoerty to the KV file like mygridwid_widget: mygridwid and then pass that to my method get_apptime like this

```<code>Switch:
                id: startbutton
#                text: "Start / Stop"
#                size_hint_x: 1
                on_active: root.get_apptime(self, self.active, mygridwid)
</code>```

Now everything compiles and I can see the system is calling the update method when active the switch. Now my problem is though is that the UI does not seem to repaint the updated Grid but when i run the debugger I can see the Grid has been created and populated with data. Anyone have a idea of what I am doing wrong?

I am brand new to Kivy and somewhat inexperienced with Python. My problem is I am making a simple GUI for a project. In my GUI I need to have a button that turns on the system, keeps track of test time, and then updates a Grid layout with data as long as the main switch is "on." When it's off it should not update the button. Right now I am just trying to prototype the main UI elements and latter will connect my MQTT code to push data to the system.

In my code below I specifically want to know how to call the update_data method in MyGrid class from BDdemoForm class get_apptime method here:

```<code>def get_apptime(self, instance, value):
        myappstate = value

        if myappstate == True:
            self.bsdemo_currenttime = time.asctime()
            #how do i call this method in this class
            root.MyGrid.update_display()

            print(myappstate)
        else:
            self.bsdemo_currenttime = "0"
            print(myappstate)
</code>```

Anyways here is my code, main.py:

```<code>import time
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.properties import BooleanProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
#custom and helper classes
import labelb
import DeviceData
#import AppState
class TableHeader(Label):
    pass

class PlayerRecord(Label):
    pass

class BSdemoRoot(BoxLayout):
    pass

myappstate = BooleanProperty()
myappstate = False
#mygridob = MyGrid()
# class my widget
class BSdemoForm(BoxLayout):
    bsdemo_currenttime = StringProperty()
    device_data = ObjectProperty()

    def __init__(self, **kwargs):
        super(BSdemoForm, self).__init__(**kwargs)
        self.bsdemo_currenttime = "0"

    def get_apptime(self, instance, value):
        myappstate = value

        if myappstate == True:
            self.bsdemo_currenttime = time.asctime()
            root.MyGrid.update_display()
            #MyGrid(self).update_display()
            print(myappstate)
        else:
            self.bsdemo_currenttime = "0"
            print(myappstate)
        # sys_data = self.get_devicedata()
#create a data manager class
class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.get_tableheaders()
        self.get_devicedata()
        self.display_data()

    def get_tableheaders(self):
        self.tabledata = [
            {'LRT': 'Last Recived Time', 'Type': 'Classification Type', 'STR': 'Session Time Remaining'},
        ]

    def get_devicedata(self):
        self.data = [
            {'LRT': '8.243', 'Type': 'DJI Mavic', 'STR': '4.39'},
            {'LRT': '5.243', 'Type': 'Parrot BeBop', 'STR': 'Close'},
            {'LRT': '7.11', 'Type': 'Parrot Ebee', 'STR': 'Close'},
            {'LRT': '5.3', 'Type': 'Parrot DISCO', 'STR': '11.12'},
            {'LRT': '3.20', 'Type': 'Yuneec Typhoon', 'STR': '2.13'},
            {'LRT': '5.44', 'Type': 'Yuneec', 'STR': '5.23'},
            {'LRT': '1.12', 'Type': 'DJI Pro 4', 'STR': '1.10'},
            {'LRT': '2', 'Type': 'Parrot Sumo', 'STR': '2.3555'}
        ]

# assembles the items to be pushed into the gridlayout widget

    def display_data(self):
        self.clear_widgets()
        print(myappstate)
        for myi in xrange(len(self.tabledata)):
            print("display data method was run")
            myrow = self.create_header(myi)
            for myitem in myrow:
                self.add_widget(myitem)

        if myappstate == True:
            for i in xrange(len(self.data)):
                row = self.create_player_info(i)
                #add all the items to the widget
                for item in row:
                    self.add_widget(item)

    @classmethod
    def update_display(self):
        self.clear_widgets()
        print(myappstate)
        for myi in xrange(len(self.tabledata)):
            print("update data display was called")
            myrow = self.create_header(myi)
            for myitem in myrow:
                self.add_widget(myitem)

        if myappstate == True:
            for i in xrange(len(self.data)):
                row = self.create_player_info(i)
                #add all the items to the widget
                for item in row:
                    self.add_widget(item)

# this allows you to change the tableheader column names and number
    def create_header(self,i):
        first_column = TableHeader(text=self.tabledata[i]['LRT'])
        second_column = TableHeader(text=self.tabledata[i]['Type'])
        third_column = TableHeader(text=self.tabledata[i]['STR'])
        return [first_column, second_column, third_column]

# puts the data into the right column to build the table
    def create_player_info(self, i):
        first_column = PlayerRecord(text=self.data[i]['LRT'])
        second_column = PlayerRecord(text=self.data[i]['Type'])
        third_column = PlayerRecord(text=self.data[i]['STR'])
        return [first_column, second_column, third_column]

class BSKivyApp(App):
    pass

if __name__ == '__main__':
    BSKivyApp().run()
</code>```

And here is my kv file BSKivy.ky.

```<code>#: import ListItemLabel kivy.uix.listview.ListItemLabel
#: import ListAdapter kivy.adapters.listadapter.ListAdapter

<PlayerRecord>:
    id: myplayer
    size_hint_y: None
    height: '30dp'
    width: '100dp'

    canvas.before:
        Color:
            rgb: 0.2, 0.2, 0.2
        Rectangle:
            pos: self.pos
            size: self.size

<TableHeader>:
    id: myheader
    size_hint_y: None
    height: '30dp'
    width: '100dp'

    canvas.before:
        Color:
            rgb: 0.5, 0.5, 0.5
        Rectangle:
            pos: self.pos
            size: self.size

BSdemoRoot:
<BSdemoRoot>:
    BSdemoForm
<BSdemoForm>
    orientation: "vertical"
    #device_data: device_data_results
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            Label:
                text: "BS Demo Interface and GUI"
        BoxLayout:
            Label:
                text: "Current Time"
                size_hint_x: 1
            Label:
                id: app_runtime_label
                text: root.bsdemo_currenttime
                size_hint_x: 1
            Switch:
                id: startbutton
#                text: "Start / Stop"
#                size_hint_x: 1
                on_active: root.get_apptime(self, self.active)

                # ; app.root.MyGrid.display_data(self)
        ScrollView:
            size_hint_y: None
            height: '200dp'

            MyGrid:
                id: mygridwid
                cols: 3
                size_hint_y: None
                height: self.minimum_height
                spacing: '1dp'

        BoxLayout:
            Label:
                text: "replace with a button"
</code>```

答: So I got this working and will close it. Basically, I had two issues. One was not understanding how to use property and ID's correctly. My second issue was a simple variable scope issue. </p>

Body:
Edit:  So I answered my first question which was right in the Kivy docs :-).
Basically I needed to add a propoerty to the KV file like mygridwid_widget: mygridwid and then pass that to my method get_apptime like this

Switch:
                id: startbutton
#                text: "Start / Stop"
#                size_hint_x: 1
                on_active: root.get_apptime(self, self.active, mygridwid)

Now everything compiles and I can see the system is calling the update method when active the switch. Now my problem is though is that the UI does not seem to repaint the updated Grid but when i run the debugger I can see the Grid has been created and populated with data. Anyone have a idea of what I am doing wrong?

I am brand new to Kivy and somewhat inexperienced with Python. My problem is I am making a simple GUI for a project. In my GUI I need to have a button that turns on the system, keeps track of test time, and then updates a Grid layout with data as long as the main switch is "on." When it's off it should not update the button. Right now I am just trying to prototype the main UI elements and latter will connect my MQTT code to push data to the system.

In my code below I specifically want to know how to call the update_data method in MyGrid class from BDdemoForm class get_apptime method here:

def get_apptime(self, instance, value):
        myappstate = value

        if myappstate == True:
            self.bsdemo_currenttime = time.asctime()
            #how do i call this method in this class
            root.MyGrid.update_display()

            print(myappstate)
        else:
            self.bsdemo_currenttime = "0"
            print(myappstate)

Anyways here is my code, main.py:

import time
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.properties import BooleanProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
#custom and helper classes
import labelb
import DeviceData
#import AppState
class TableHeader(Label):
    pass

class PlayerRecord(Label):
    pass

class BSdemoRoot(BoxLayout):
    pass

myappstate = BooleanProperty()
myappstate = False
#mygridob = MyGrid()
# class my widget
class BSdemoForm(BoxLayout):
    bsdemo_currenttime = StringProperty()
    device_data = ObjectProperty()

    def __init__(self, **kwargs):
        super(BSdemoForm, self).__init__(**kwargs)
        self.bsdemo_currenttime = "0"

    def get_apptime(self, instance, value):
        myappstate = value

        if myappstate == True:
            self.bsdemo_currenttime = time.asctime()
            root.MyGrid.update_display()
            #MyGrid(self).update_display()
            print(myappstate)
        else:
            self.bsdemo_currenttime = "0"
            print(myappstate)
        # sys_data = self.get_devicedata()
#create a data manager class
class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.get_tableheaders()
        self.get_devicedata()
        self.display_data()

    def get_tableheaders(self):
        self.tabledata = [
            {'LRT': 'Last Recived Time', 'Type': 'Classification Type', 'STR': 'Session Time Remaining'},
        ]

    def get_devicedata(self):
        self.data = [
            {'LRT': '8.243', 'Type': 'DJI Mavic', 'STR': '4.39'},
            {'LRT': '5.243', 'Type': 'Parrot BeBop', 'STR': 'Close'},
            {'LRT': '7.11', 'Type': 'Parrot Ebee', 'STR': 'Close'},
            {'LRT': '5.3', 'Type': 'Parrot DISCO', 'STR': '11.12'},
            {'LRT': '3.20', 'Type': 'Yuneec Typhoon', 'STR': '2.13'},
            {'LRT': '5.44', 'Type': 'Yuneec', 'STR': '5.23'},
            {'LRT': '1.12', 'Type': 'DJI Pro 4', 'STR': '1.10'},
            {'LRT': '2', 'Type': 'Parrot Sumo', 'STR': '2.3555'}
        ]

# assembles the items to be pushed into the gridlayout widget

    def display_data(self):
        self.clear_widgets()
        print(myappstate)
        for myi in xrange(len(self.tabledata)):
            print("display data method was run")
            myrow = self.create_header(myi)
            for myitem in myrow:
                self.add_widget(myitem)

        if myappstate == True:
            for i in xrange(len(self.data)):
                row = self.create_player_info(i)
                #add all the items to the widget
                for item in row:
                    self.add_widget(item)

    @classmethod
    def update_display(self):
        self.clear_widgets()
        print(myappstate)
        for myi in xrange(len(self.tabledata)):
            print("update data display was called")
            myrow = self.create_header(myi)
            for myitem in myrow:
                self.add_widget(myitem)

        if myappstate == True:
            for i in xrange(len(self.data)):
                row = self.create_player_info(i)
                #add all the items to the widget
                for item in row:
                    self.add_widget(item)

# this allows you to change the tableheader column names and number
    def create_header(self,i):
        first_column = TableHeader(text=self.tabledata[i]['LRT'])
        second_column = TableHeader(text=self.tabledata[i]['Type'])
        third_column = TableHeader(text=self.tabledata[i]['STR'])
        return [first_column, second_column, third_column]

# puts the data into the right column to build the table
    def create_player_info(self, i):
        first_column = PlayerRecord(text=self.data[i]['LRT'])
        second_column = PlayerRecord(text=self.data[i]['Type'])
        third_column = PlayerRecord(text=self.data[i]['STR'])
        return [first_column, second_column, third_column]

class BSKivyApp(App):
    pass

if __name__ == '__main__':
    BSKivyApp().run()

And here is my kv file BSKivy.ky.

#: import ListItemLabel kivy.uix.listview.ListItemLabel
#: import ListAdapter kivy.adapters.listadapter.ListAdapter

<PlayerRecord>:
    id: myplayer
    size_hint_y: None
    height: '30dp'
    width: '100dp'

    canvas.before:
        Color:
            rgb: 0.2, 0.2, 0.2
        Rectangle:
            pos: self.pos
            size: self.size

<TableHeader>:
    id: myheader
    size_hint_y: None
    height: '30dp'
    width: '100dp'

    canvas.before:
        Color:
            rgb: 0.5, 0.5, 0.5
        Rectangle:
            pos: self.pos
            size: self.size

BSdemoRoot:
<BSdemoRoot>:
    BSdemoForm
<BSdemoForm>
    orientation: "vertical"
    #device_data: device_data_results
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            Label:
                text: "BS Demo Interface and GUI"
        BoxLayout:
            Label:
                text: "Current Time"
                size_hint_x: 1
            Label:
                id: app_runtime_label
                text: root.bsdemo_currenttime
                size_hint_x: 1
            Switch:
                id: startbutton
#                text: "Start / Stop"
#                size_hint_x: 1
                on_active: root.get_apptime(self, self.active)

                # ; app.root.MyGrid.display_data(self)
        ScrollView:
            size_hint_y: None
            height: '200dp'

            MyGrid:
                id: mygridwid
                cols: 3
                size_hint_y: None
                height: self.minimum_height
                spacing: '1dp'

        BoxLayout:
            Label:
                text: "replace with a button"


来源: stackexchange

问:
WebBrowser Control - Prevent Right-Click
In my application, I have a form that contains a browser control in which I display an SSRS report. I would like to prevent the user from right-clicking in the browser control and being shown the popup menu. Ideally I'd like the right-click to do nothing. Is there a way I can accomplish this?</p>

答:
You can set the IsWebBrowserContextMenuEnabled equal to false. You will probably also want to set AllowWebBrowserDrop equal to false too so they cant drag a url into the app and have it load.</p>

```<code>        webBrowser1.IsWebBrowserContextMenuEnabled = false;
        webBrowser1.AllowWebBrowserDrop = false;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can set the IsWebBrowserContextMenuEnabled equal to false. You will probably also want to set AllowWebBrowserDrop equal to false too so they cant drag a url into the app and have it load.

        webBrowser1.IsWebBrowserContextMenuEnabled = false;
        webBrowser1.AllowWebBrowserDrop = false;


问:
Xamarin Forms - StackLayout inside AbsoluteLayout
I'm new to Xamarin Forms and I'm stuck trying to make StackLayout work inside an AbsoluteLayout. There are 2 children inside my StackLayout: an Image (300x300 random image) and a Label. I'll show an example that illustrates my problem.

The following code works just fine for me (i'm using a 300x300 image) :

```<code>public class TestedPage : ContentPage
{
    public TestPage()
    {
    BackgroundColor = Color.Brown;
    StackLayout stl = new StackLayout();
    AbsoluteLayout ab = new AbsoluteLayout();

    Image img = new Image();
    img.Source = ImageSource.FromFile("circle.png");

    Label lbl = new Label
    {
        Text = "#Text1000",
        TextColor = Color.White,
        FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
        HorizontalOptions = LayoutOptions.Center
    };

    stl.Children.Add(img);
    stl.Children.Add(lbl);

    ab.Children.Add(stl);

    Content = ab;
    }
}
</code>```

The problem is that the above code simply will throw 'stl' in it without positioning, which is big deal for me because I need it to be positioned exactly where I want.
So, you may ask "why don't you use more parameters for Children.Add() ?", well ab.Children.Add(stl, new Rectangle(0,0,450,450)); will not position 'stl' correctly, for me at least, in the above code, it will be at start of screen and a bit after center, to the right, and not origin(0,0).
Also, curious that I debugged and found out that Stack, Image and Absolute all have different height and width. Above code gives me 450, 450 for 'stl' (which is fine); 616, 360 for 'ab'; 150, 450 for 'img'.

So, is there anything I'm missing here ? It is a little confusing for me because I get it to work but it's a little "buggy", does not behave as I expected.
Since I'm not experienced in Xamarin Forms I believe I'm missing something important here, which is why I hope you guys might give me some clues.

Any ideas ?

Any help is appreciated. Thanks!

答:
You might try:</p>

```<code>AbsoluteLayout.SetLayoutFlags(stl, AbsoluteLayoutFlags.All);

AbsoluteLayout.SetLayoutBounds(stl, new Rectangle(0f, 0f, 1f, 1f));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to Xamarin Forms and I'm stuck trying to make StackLayout work inside an AbsoluteLayout. There are 2 children inside my StackLayout: an Image (300x300 random image) and a Label. I'll show an example that illustrates my problem.

The following code works just fine for me (i'm using a 300x300 image) :

public class TestedPage : ContentPage
{
    public TestPage()
    {
    BackgroundColor = Color.Brown;
    StackLayout stl = new StackLayout();
    AbsoluteLayout ab = new AbsoluteLayout();

    Image img = new Image();
    img.Source = ImageSource.FromFile("circle.png");

    Label lbl = new Label
    {
        Text = "#Text1000",
        TextColor = Color.White,
        FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
        HorizontalOptions = LayoutOptions.Center
    };

    stl.Children.Add(img);
    stl.Children.Add(lbl);

    ab.Children.Add(stl);

    Content = ab;
    }
}

The problem is that the above code simply will throw 'stl' in it without positioning, which is big deal for me because I need it to be positioned exactly where I want.
So, you may ask "why don't you use more parameters for Children.Add() ?", well ab.Children.Add(stl, new Rectangle(0,0,450,450)); will not position 'stl' correctly, for me at least, in the above code, it will be at start of screen and a bit after center, to the right, and not origin(0,0).
Also, curious that I debugged and found out that Stack, Image and Absolute all have different height and width. Above code gives me 450, 450 for 'stl' (which is fine); 616, 360 for 'ab'; 150, 450 for 'img'.

So, is there anything I'm missing here ? It is a little confusing for me because I get it to work but it's a little "buggy", does not behave as I expected.
Since I'm not experienced in Xamarin Forms I believe I'm missing something important here, which is why I hope you guys might give me some clues.

Any ideas ?

Any help is appreciated. Thanks!

Body:
You might try:

AbsoluteLayout.SetLayoutFlags(stl, AbsoluteLayoutFlags.All);

AbsoluteLayout.SetLayoutBounds(stl, new Rectangle(0f, 0f, 1f, 1f));


问:
Need to print specific items in XML and JSON response using python
I am getting a response from the google maps api and I just need to get the distance from the Json response and the XML response. I am having trouble finding good examples on how to do this. I am supposed to be using requests and bs4 modules to do this.

The program needs 3 arguments when ran the first being -j for json or -x for XML.

The second is an origin city and state. Example: Nashville,TN

The third is destination city or state. Example: Smynra,TN

```<code>import requests
from bs4 import BeautifulSoup as bs
import sys
import json

funCall = sys.argv[1]
key = "AIzaSyD6-37WvsoTYvlgXKdquv5TRFFwgARvq4w"

def Xfunction():
    x = 4
def aFunction():
    x = 3

if funCall == "-j":
    origin = sys.argv[2]
    dest = sys.argv[3]

    url = "https://maps.googleapis.com/maps/api/distancematrix/json?
           units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})

elif funCall == "-x":
    origin = sys.argv[2]
    dest = sys.argv[3]

    url = "https://maps.googleapis.com/maps/api/distancematrix/xml?
           units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})

elif funCall == "-a":
    aFunction()
</code>```

Ignore the functions at the top I am getting responses within the if statement the -j is jason and the -x is XML.

If i print after my jason req using print(req.content) I get:

```<code>b'{\n   "destination_addresses" : [ "Smyrna, TN, USA" ],\n   "origin_addresses" : [ "Nashville, TN, USA" ],\n   "rows" : [\n      {\n         "elements" : [\n            {\n               "distance" : {\n                  "text" : "24.2 mi",\n                  "value" : 39005\n               },\n               "duration" : {\n                  "text" : "31 mins",\n                  "value" : 1873\n               },\n               "status" : "OK"\n            }\n         ]\n      }\n   ],\n   "status" : "OK"\n}\n'
</code>```

I just need the distance text value and I do not know how to parse it from the json or xml.

答:
Read the JSON like this:

```<code>if funCall == "-j":
    origin = sys.argv[2]
    dest = sys.argv[3]
    url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})
    distance = req.json()['rows'][0]['elements'][0][ 'distance']['text']
    print (distance)
</code>```

Outputs

```<code>24.2 mi
</code>```

And the XML like this:

```<code>elif funCall == "-x":
    origin = sys.argv[2]
    dest = sys.argv[3]
    url = "https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})
    soup = bs(req.text, "xml")
    distance = soup.find('distance').findNext('text').text
    print (distance)
</code>```

Outputs

```<code>24.2 mi
</code>```

But you are duplicating 2 (nearly 4) lines of code in the if and elif statements, if you move them to before the statements your code will be better.

Body:
I am getting a response from the google maps api and I just need to get the distance from the Json response and the XML response. I am having trouble finding good examples on how to do this. I am supposed to be using requests and bs4 modules to do this.

The program needs 3 arguments when ran the first being -j for json or -x for XML.

The second is an origin city and state. Example: Nashville,TN

The third is destination city or state. Example: Smynra,TN

import requests
from bs4 import BeautifulSoup as bs
import sys
import json

funCall = sys.argv[1]
key = "AIzaSyD6-37WvsoTYvlgXKdquv5TRFFwgARvq4w"

def Xfunction():
    x = 4
def aFunction():
    x = 3

if funCall == "-j":
    origin = sys.argv[2]
    dest = sys.argv[3]

    url = "https://maps.googleapis.com/maps/api/distancematrix/json?
           units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})

elif funCall == "-x":
    origin = sys.argv[2]
    dest = sys.argv[3]

    url = "https://maps.googleapis.com/maps/api/distancematrix/xml?
           units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})

elif funCall == "-a":
    aFunction()

Ignore the functions at the top I am getting responses within the if statement the -j is jason and the -x is XML.

If i print after my jason req using print(req.content) I get:

b'{\n   "destination_addresses" : [ "Smyrna, TN, USA" ],\n   "origin_addresses" : [ "Nashville, TN, USA" ],\n   "rows" : [\n      {\n         "elements" : [\n            {\n               "distance" : {\n                  "text" : "24.2 mi",\n                  "value" : 39005\n               },\n               "duration" : {\n                  "text" : "31 mins",\n                  "value" : 1873\n               },\n               "status" : "OK"\n            }\n         ]\n      }\n   ],\n   "status" : "OK"\n}\n'

I just need the distance text value and I do not know how to parse it from the json or xml.

Body:
Read the JSON like this:

if funCall == "-j":
    origin = sys.argv[2]
    dest = sys.argv[3]
    url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})
    distance = req.json()['rows'][0]['elements'][0][ 'distance']['text']
    print (distance)

Outputs

24.2 mi

And the XML like this:

elif funCall == "-x":
    origin = sys.argv[2]
    dest = sys.argv[3]
    url = "https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&origins="+origin+"&destinations="+dest+"&key="+key
    req = requests.get(url, headers={}, params={})
    soup = bs(req.text, "xml")
    distance = soup.find('distance').findNext('text').text
    print (distance)

Outputs

24.2 mi

But you are duplicating 2 (nearly 4) lines of code in the if and elif statements, if you move them to before the statements your code will be better.


问:
Capybara is checkbox checked?
In the following HTML Code I am in a row that contains 4 columns: read, create, edit and delete (twice for cities and projects).

What I would like to do is to check if the read button is checked in projects. I am very new in capybara, I tried find('citites') then I don't know how to mention its children to check if create is checked.
Your help will be very much appreciated.

  Cities

  Projects

```

答:
expect(page).to have_checked_field("my_check_name")

Link to doc: http://www.rubydoc.info/github/jnicklas/capybara/Capybara%2FRSpecMatchers%3Ahave_checked_field

Title: Capybara is checkbox checked?


问:
Can I create an alias of a type in Golang?
I'm struggling with my learning of Go.

I found this neat implementation of a Set in go: gopkg.in/fatih/set.v0, but I'd prefer naming my sets with a more explicit name that set.Set, doing something like:

```<code>type View set.Set
</code>```

In essence, I want my View type to inherit set.Set's methods. Because, well, View is a set.Set of descriptors. But I know Go is pretty peaky on inheritance, and typing in general.

For now I've been trying the following kinda inheritance, but it's causing loads of errors when trying to use some functions like func Union(set1, set2 Interface, sets ...Interface) Interface or func (s *Set) Merge(t Interface):

```<code>type View struct {
    set.Set
}
</code>```

I'd like to know if there's a way to achieve what I want in a Go-like way, or if I'm just trying to apply my good-ol' OO practices to a language that discards them, please.

答:
Note, I think the simple aliasing you proposed initially is syntactically valid though having had a quick look at the set library, rather than aliasing set.Set it might make more sense to alias set.Interface, e.g.:

```<code>package main

import (
  "fmt"

  set "gopkg.in/fatih/set.v0"
)

// View is a type alias for the set.Interface interface
type View set.Interface

// Display takes one of our View types in order to print it.
func Display(view View) {
  fmt.Println(view.List())
}

func main() {
  // create our first set.Interface or View
  v1 := set.New()
  v1.Add("foo")

  // create our second set.Interface or View
  v2 := set.New("bar")

  // call a set function
  v3 := set.Union(v1, v2)

  // call our function that takes a View
  Display(v3)
}
</code>```

You may have noticed I'm cheating somehow because I make no real mention of the aliased type in the above code other than in defining the parameter to the Display function above which you'll note takes in a View instance rather than a set.Interface. If you have lots of functions working on these things, then that might read more expressively for your domain.

Note that because our View type is an alias to an interface type, it precludes adding your own functions to that type as Go doesn't allow us to have an interface receiver type for a function (I might be expressing that incorrectly). By this I mean that you can't do anything like:

```<code>func (v View) Display() string {
  return v.String()
}
</code>```

In summary I think aliasing things is fine, it can make internal APIs more readable, and you can lean on the compiler to help eliminate certain classes of errors; however this doesn't allow you to add functionality to the custom type. If this is required an alternate approach would be necessary, either embedding or simple composition (i.e. a View has a Set).

Body:
I'm struggling with my learning of Go.

I found this neat implementation of a Set in go: gopkg.in/fatih/set.v0, but I'd prefer naming my sets with a more explicit name that set.Set, doing something like:

type View set.Set

In essence, I want my View type to inherit set.Set's methods. Because, well, View is a set.Set of descriptors. But I know Go is pretty peaky on inheritance, and typing in general.

For now I've been trying the following kinda inheritance, but it's causing loads of errors when trying to use some functions like func Union(set1, set2 Interface, sets ...Interface) Interface or func (s *Set) Merge(t Interface):

type View struct {
    set.Set
}

I'd like to know if there's a way to achieve what I want in a Go-like way, or if I'm just trying to apply my good-ol' OO practices to a language that discards them, please.

Body:
Note, I think the simple aliasing you proposed initially is syntactically valid though having had a quick look at the set library, rather than aliasing set.Set it might make more sense to alias set.Interface, e.g.:

package main

import (
  "fmt"

  set "gopkg.in/fatih/set.v0"
)

// View is a type alias for the set.Interface interface
type View set.Interface

// Display takes one of our View types in order to print it.
func Display(view View) {
  fmt.Println(view.List())
}

func main() {
  // create our first set.Interface or View
  v1 := set.New()
  v1.Add("foo")

  // create our second set.Interface or View
  v2 := set.New("bar")

  // call a set function
  v3 := set.Union(v1, v2)

  // call our function that takes a View
  Display(v3)
}

You may have noticed I'm cheating somehow because I make no real mention of the aliased type in the above code other than in defining the parameter to the Display function above which you'll note takes in a View instance rather than a set.Interface. If you have lots of functions working on these things, then that might read more expressively for your domain.

Note that because our View type is an alias to an interface type, it precludes adding your own functions to that type as Go doesn't allow us to have an interface receiver type for a function (I might be expressing that incorrectly). By this I mean that you can't do anything like:

func (v View) Display() string {
  return v.String()
}

In summary I think aliasing things is fine, it can make internal APIs more readable, and you can lean on the compiler to help eliminate certain classes of errors; however this doesn't allow you to add functionality to the custom type. If this is required an alternate approach would be necessary, either embedding or simple composition (i.e. a View has a Set).


问:
How to kill a web process
I have a web script that takes a really long time to run (and it's supposed to take a long time). By "web script" I mean a script that's run by visiting a page in a browser and opposed to executed on the command line. The script is in PHP and I'm on a LAMP stack.

How can I find and kill this process if I want to?

"Kill" might be the wrong word. I just want the script to stop. I could conceivably make this script "watch" for some state of my system to change, and then halt when it notices that change. If I do that, I'm not sure what the best way to do that would be. In any case, I'm completely open to any suggestions.

答:
Are you simply going to the web page of the script ie.. www.mysite.com/mywebscript.php or are you running the script from another page? I'd suggest using system() or something, that way you can actually look up the process id on your linux platform.

Also, you could use a thread in your script. You could make it perform whatever, and take input at the same time, and just send a command to kill it whenever.

Title: How to kill a web process

ContentLicense: CC BY-SA 4.0


问:
floor gives unexpected result, and therefore so does focalWeight function from R's raster package
I've used the focalWeight function in R's raster package to create focal "moving window" weight matrices for tens of thousands of images.  On a few dozen of the images the function does not behave as expected.  I expect a 3x3 matrix, but am returned a 1x3 matrix.

Upon digging into the problem I think it is due to the floor function which is called internally.

I'll demonstrate the problem below (I have a raster named r).  I'm running code from .circular.weight

```<code>res(r)                               # raster resolution is 1
#[1] 1 1
rs <- res(r)
d <- 1                               # window diameter is 1
nx <- 1 + 2 * floor(d/rs[1])         # number of columns is 3
nx                                   #  this is expected
#[1] 3
ny <- 1 + 2 * floor(d/rs[2])          # number of rows is 1
ny                                    # this is unexpected
#[1] 1
1 + 2 * floor(d/rs[2])
#[1] 1
2 * floor(d/rs[2])
#[1] 0
floor(d/rs[2])                         # the floor of 1 is 0
#[1] 0
d/rs[2]
#[1] 1
floor(1)                            # but the floor of 1 should be 1
#[1] 1

res(r) == 1                        # the resolution appears to be 1, 1
# [1] 1 1
res(r) == 1                        # but it isn't really
# [1]  TRUE FALSE
</code>```

?floor says that unexpected results like this have been seen before.  It says, "It is normally necessary to use a tolerance."

How do I use a tolerance?
How can I fix the focalWeight function?

答:
By using round, I can solve the problem.  This answer told me how to work with unexpected results of floor

```<code>> floor(d/rs[2])
[1] 0
> floor(d/round(rs[2]))
[1] 1
</code>```

This works in my case where the resolution is 1 1.  I'm not sure about other cases.

Body:
I've used the focalWeight function in R's raster package to create focal "moving window" weight matrices for tens of thousands of images.  On a few dozen of the images the function does not behave as expected.  I expect a 3x3 matrix, but am returned a 1x3 matrix.

Upon digging into the problem I think it is due to the floor function which is called internally.

I'll demonstrate the problem below (I have a raster named r).  I'm running code from .circular.weight

res(r)                               # raster resolution is 1
#[1] 1 1
rs <- res(r)
d <- 1                               # window diameter is 1
nx <- 1 + 2 * floor(d/rs[1])         # number of columns is 3
nx                                   #  this is expected
#[1] 3
ny <- 1 + 2 * floor(d/rs[2])          # number of rows is 1
ny                                    # this is unexpected
#[1] 1
1 + 2 * floor(d/rs[2])
#[1] 1
2 * floor(d/rs[2])
#[1] 0
floor(d/rs[2])                         # the floor of 1 is 0
#[1] 0
d/rs[2]
#[1] 1
floor(1)                            # but the floor of 1 should be 1
#[1] 1

res(r) == 1                        # the resolution appears to be 1, 1
# [1] 1 1
res(r) == 1                        # but it isn't really
# [1]  TRUE FALSE

?floor says that unexpected results like this have been seen before.  It says, "It is normally necessary to use a tolerance."

How do I use a tolerance?
How can I fix the focalWeight function?

Body:
By using round, I can solve the problem.  This answer told me how to work with unexpected results of floor

> floor(d/rs[2])
[1] 0
> floor(d/round(rs[2]))
[1] 1

This works in my case where the resolution is 1 1.  I'm not sure about other cases.


问:
Importing csv file with line breaks to R or Python Pandas
I have a csv file that includes line breaks within columns:

```<code>"id","comment","x"
1,"ABC\"xyz",123
2,"xyz\"abc",543
3,"abc
xyz",483
</code>```

ID 3, for example contains such a line break.

How can this be imported into python or R? Also, I don't mind if those line breaks were to be replaced by a space, for example.

答:
You can also use python pandas library read_csv function. Make sure to specify escape char.

```<code>import pandas as pd
df = pd.read_csv('path_to_csv', sep=',', escapechar='\\')
</code>```

Please note second backslash escaping first one. It has nothing to do with pandas or csv.

Body:
I have a csv file that includes line breaks within columns:

"id","comment","x"
1,"ABC\"xyz",123
2,"xyz\"abc",543
3,"abc
xyz",483

ID 3, for example contains such a line break.

How can this be imported into python or R? Also, I don't mind if those line breaks were to be replaced by a space, for example.

Body:
You can also use python pandas library read_csv function. Make sure to specify escape char.

import pandas as pd
df = pd.read_csv('path_to_csv', sep=',', escapechar='\\')

Please note second backslash escaping first one. It has nothing to do with pandas or csv.


问:
Ensure that there is space at the sides of columns and between columns
How do I create space between the DOM and the column, my text is too close to the DOM side. </p>

```<code><template>

    <div>

<md-layout md-row md-md-columns>

        <md-layout md-column = "5" class = "mdcolor">
        <p class = "md-display-1"> Connect Soft documents </p>

          <p class = "">Allow documents that feed into each other to provide a consistent, untainted view of what your institution is doing.</p>

      </md-layout>
</md-layout>

 </div>

</template>
</code>```

答:
Just add CSS padding: https://codepen.io/aprouja1/pen/gRjPgB</p>

```<code>#app{
  padding-left:10px;
}
</code>```

Body:
How do I create space between the DOM and the column, my text is too close to the DOM side.

<template>

<md-layout md-row md-md-columns>

        <md-layout md-column = "5" class = "mdcolor">

 Connect Soft documents

Allow documents that feed into each other to provide a consistent, untainted view of what your institution is doing.

      </md-layout>
</md-layout>

</template>

Body:
Just add CSS padding: https://codepen.io/aprouja1/pen/gRjPgB

#app{
  padding-left:10px;
}


问:
JQuery selector returns undefined
This html code was generated of my php code, but I copied this out of the HTML code of the browser.

The console.log prints out undefined. I don't know why. It's probably a really dumb mistake, like always. Thank you for your help.

$('.show').click(function() {
  var id = $(this).attr('id');
  var div = $("div#" + id);
  console.log(div.html());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Heading +</h3>
<div class='.slidetoggle' id='2962' style='display: none;'>
  <p>Test!</p>
</div></code>```

答:
It's because the .show element is an a, not a div. The selector is wrong:

```<code>var div = $("a#" + id);
</code>```

Update:

You are right, but I want to show the div, not the a

In this case you need to use DOM traversal to find the relevant element. Your current code doesn't work as you have duplicate id attributes. This is invalid as they must be unique. Try this:

$('.show').click(function() {
  $(this).closest('h3').next('.slidetoggle').slideToggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slidetoggle { display: none; }</code>```

Heading +

Test!

Another Heading +

Another Test!

```

Title: JQuery selector returns undefined

Body:
This html code was generated of my php code, but I copied this out of the HTML code of the browser.

The console.log prints out undefined. I don't know why. It's probably a really dumb mistake, like always. Thank you for your help.

$('.show').click(function() {
  var id = $(this).attr('id');
  var div = $("div#" + id);
  console.log(div.html());
});

Heading +

Test!

Body:
It's because the .show element is an a, not a div. The selector is wrong:

var div = $("a#" + id);

Update:

You are right, but I want to show the div, not the a

In this case you need to use DOM traversal to find the relevant element. Your current code doesn't work as you have duplicate id attributes. This is invalid as they must be unique. Try this:

$('.show').click(function() {
  $(this).closest('h3').next('.slidetoggle').slideToggle();
});

.slidetoggle { display: none; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Heading <a href="#" class="show">+</a></h3>
<div class="slidetoggle">
  <p>Test!</p>
</div>

<h3>Another Heading <a href="#" class="show">+</a></h3>
<div class="slidetoggle">
  <p>Another Test!</p>
</div>


问:
Compressing video file based with Multiple Resolution format options in Android
I am using MediaCodec Native API to compress video. My requirement is , I also need to show the user, list of available resolution formats for video compression(assuming that if user selects any of the resolution format, the output file should be less than 5MB). So, I need to be able to calculate the compressed video size based on resolution option chosen by the user before the actual compression. Is this possible in Android? I have searched extensively, but unable to find any answer. Any leads would be very helpful. Thanks!</p>

答: You can calculate the output size by multiplying the output bitrate (bit per second) with the length (seconds) of the video.</p>


问:
How to stop Auth user from visiting own page with non auth user privileges in laravel?
My laravel application is a social media site. Here's the route for visiting another laravel user's profile

```<code>Route::get('/dashboard/{id}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);
</code>```

It works just fine. However, I've discovered a bug that when I input the Auth user's ID into the route, I get taken to the same page where I can then add myself as a friend, I do not want this to happen. I would rather get taken back to the home screen if I'm visiting my own profile.

Here's the controller:

```<code> public function getProfile($id)
{

    if(Auth::user() === $id)
        redirect('dashboard');

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}
</code>```

I've tried to get it to redirect to 'dashboard' instead of 'profile.index' if it's the Auth user's page instead of pulling up just like a regular non-auth profile, but can't seem to get it to work. Any ideas on how to fix this small bug?

答:
You get user instance by Auth::user() not only the user ID. You are comparing instance with the numeric value. It will not work. You have to use Auth::id() or Auth::user()->id in order to get ID of the logged in user. The following code will work in your case.

```<code>public function getProfile($id)
{

    if(Auth::id() == $id)
    {
        redirect('dashboard');
    }
    else
    {
        $user = User::where('id', $id)->first();
        $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
        $photos = Photo::paginate(6);
        return view('profile.index',compact('user','posts', 'photos'));
    }
}
</code>```

Let me know if it helps!

Body:
My laravel application is a social media site. Here's the route for visiting another laravel user's profile

Route::get('/dashboard/{id}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);

It works just fine. However, I've discovered a bug that when I input the Auth user's ID into the route, I get taken to the same page where I can then add myself as a friend, I do not want this to happen. I would rather get taken back to the home screen if I'm visiting my own profile.

Here's the controller:

 public function getProfile($id)
{

    if(Auth::user() === $id)
        redirect('dashboard');

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}

I've tried to get it to redirect to 'dashboard' instead of 'profile.index' if it's the Auth user's page instead of pulling up just like a regular non-auth profile, but can't seem to get it to work. Any ideas on how to fix this small bug?

Body:
You get user instance by Auth::user() not only the user ID. You are comparing instance with the numeric value. It will not work. You have to use Auth::id() or Auth::user()->id in order to get ID of the logged in user. The following code will work in your case.

public function getProfile($id)
{

    if(Auth::id() == $id)
    {
        redirect('dashboard');
    }
    else
    {
        $user = User::where('id', $id)->first();
        $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
        $photos = Photo::paginate(6);
        return view('profile.index',compact('user','posts', 'photos'));
    }
}

Let me know if it helps!


问:
Is there a way for Unix sort to ignore delimiter based on escape characters?
I want to use Unix sort but sometimes I want the field delimiter if enclosed by a pair of enclosing delimiter to not be treated as the field delimiter. For example, lets look at the base case and then then later look at the specific case:

Base Case:

```<code>"xyz"|27
"abc"|15
"xyz"|25
</code>```

When I perform the following command:

sort -t'|' -k1,1 -k2,2n test1.txt

I get what I want:

```<code>"abc"|15
"xyz"|25
"xyz"|27
</code>```

Now let's look at the second case with an escape character pair <> provided:

```<code>"x<|>yz"|27
"abc"|15
"xyz"|25
</code>```

If I run the same command, I get something that I don't want:

```<code>"abc"|15
"x<|>yz"|27
"xyz"|25
</code>```

Is there anyway to tell unix sort that if <> or {} or () or even a weird pair like <) is provided, then ignore the actual field delimiter inside the enclosing delimiter pair? The actual field delimiter will always be a pipe.

The desired result that I am aiming for is:

```<code>"abc"|15
"xyz"|25
"x<|>yz"|27
</code>```

答:
short: sort doesn't do that.

long: you can mostly work around this by pre/post-filtering of the data to make the fields align in columns.  If I had to use just the command-line sort, I'd preprocess the file using sed so that the delimiter is a tab character (which in POSIX is before any printable character).  After sorting, replacing the tab with the vertical bar would be another sed-command.

For "mostly", the main pitfall is that in some locales, the various punctuation characters are essentially ignored.

Body:
I want to use Unix sort but sometimes I want the field delimiter if enclosed by a pair of enclosing delimiter to not be treated as the field delimiter. For example, lets look at the base case and then then later look at the specific case:

Base Case:

"xyz"|27
"abc"|15
"xyz"|25

When I perform the following command:

sort -t'|' -k1,1 -k2,2n test1.txt

I get what I want:

"abc"|15
"xyz"|25
"xyz"|27

Now let's look at the second case with an escape character pair <> provided:

"x<|>yz"|27
"abc"|15
"xyz"|25

If I run the same command, I get something that I don't want:

"abc"|15
"x<|>yz"|27
"xyz"|25

Is there anyway to tell unix sort that if <> or {} or () or even a weird pair like <) is provided, then ignore the actual field delimiter inside the enclosing delimiter pair? The actual field delimiter will always be a pipe.

The desired result that I am aiming for is:

"abc"|15
"xyz"|25
"x<|>yz"|27


问:
object does not support indexing when overriding __getitem__
The Solution class inherits from object class, TypeError occurs: 'Solution' object does not support indexing? But if Solution class does not inherit from object, the code works find. My question is why Solution class does not support indexing when it inherits from object, even though it override getitem method.

```<code>class Solution(object):
    def findMin(self, nums):
        self.__getitem__ = lambda i: nums[i] <= nums[-1]
        return nums[bisect.bisect(self, False, 0, len(nums))]
</code>```

答:
When you inherit from object, you create a new-style class rather than an old style class.  For new-style classes, __getitem__ is looked up on the class, not on the instance of the class.  Even though you've added a __getitem__ method to a class instance (self), you haven't added that method to the class and therefore the lookup fails (for new style classes).

For old style classes, presumably the lookup still happens on the instance which is why the code works when you don't inherit from object.  Careful though -- In python3.x, all classes are new style whether you inherit from object explicitly or not.

Body:
The Solution class inherits from object class, TypeError occurs: 'Solution' object does not support indexing? But if Solution class does not inherit from object, the code works find. My question is why Solution class does not support indexing when it inherits from object, even though it override getitem method.

class Solution(object):
    def findMin(self, nums):
        self.__getitem__ = lambda i: nums[i] <= nums[-1]
        return nums[bisect.bisect(self, False, 0, len(nums))]


问:
First Addon help - Cycling through windows with for loop
I am making my first firefox extension today.  So far I have done a little...but now I would like to count the number of firefox windows the user has open (for example 3)  I can count tabs, that is easy so far...but I can't seem to find how to cycle through windows and count them (windows != tabs, like tabs are within windows, sorry, I hope this makes sense, even mozilla confuses it in their coding) I think basically, I am lost for the method name...

so I think it will be like:

```<code>var tomato = SOMETHING HERE MYSTERY DIFFICULT!!!!;
for (var i = 0; i < tomato; i++) {
WINDOW COUNTER HERE (EASY)
  }
</code>```

Any idea how to do this?

答:
You're looking for nsIWindowMediator - a snippet from MDC:</p>

```<code>var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var enumerator = wm.getEnumerator(type);
while(enumerator.hasMoreElements()) {
  var win = enumerator.getNext();
  // win is [Object ChromeWindow] (just like window), do something with it
}
</code>```

Body:
I am making my first firefox extension today.  So far I have done a little...but now I would like to count the number of firefox windows the user has open (for example 3)  I can count tabs, that is easy so far...but I can't seem to find how to cycle through windows and count them (windows != tabs, like tabs are within windows, sorry, I hope this makes sense, even mozilla confuses it in their coding) I think basically, I am lost for the method name...

so I think it will be like:

var tomato = SOMETHING HERE MYSTERY DIFFICULT!!!!;
for (var i = 0; i < tomato; i++) {
WINDOW COUNTER HERE (EASY)
  }

Any idea how to do this?

Body:
You're looking for nsIWindowMediator - a snippet from MDC:

var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var enumerator = wm.getEnumerator(type);
while(enumerator.hasMoreElements()) {
  var win = enumerator.getNext();
  // win is [Object ChromeWindow] (just like window), do something with it
}


问:
Regexp convert sql LIMIT syntax to SqlServer TOP syntax
I have some query string written for PostgreSQL and I have to convert them to SqlServer. I'm using C# 6.

In order to convert from LIMIT syntax to TOP syntax I've written the following simple regex:

```<code>SELECT ([\S\s]*)LIMIT (\d+) -> SELECT TOP $2 $1
</code>```

The complete line code is:

```<code>return Regex.Replace(query, @"SELECT ([\S\s]*)LIMIT (\d+)", "SELECT TOP $2 $1", RegexOptions.RightToLeft);
</code>```

Now, eveything works fine for simple query but it does not work for subquery: the TOP string is put everytime in the super parent query.

Try for example the following query:

```<code>SELECT b3.aaa,
       b3.count
FROM
(
    SELECT CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                      COUNT(b.foo) AS count
    FROM
    (
        SELECT b2.foo - (b2.foo % 10) AS foo
        FROM
        (
            SELECT CAST(b.foo * 100 AS INT) AS foo
            FROM eee b
                 INNER JOIN bar f ON b.bar_id = f.id
            WHERE b.foo < 1
                  AND f.nome = 'aaa'
        ) b2
    ) b
    GROUP BY b.foo
    ORDER BY b.foo
    LIMIT 10
)
</code>```

it is converted to:

```<code>SELECT TOP 10 b3.aaa,
       b3.count
FROM
(
    SELECT CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                      COUNT(b.foo) AS count
    FROM
    (
        SELECT b2.foo - (b2.foo % 10) AS foo
        FROM
        (
            SELECT CAST(b.foo * 100 AS INT) AS foo
            FROM eee b
                 INNER JOIN bar f ON b.bar_id = f.id
            WHERE b.foo < 1
                  AND f.nome = 'aaa'
        ) b2
    ) b
    GROUP BY b.foo
    ORDER BY b.foo
)
</code>```

while I'd like to have

```<code>SELECT b3.aaa,
       b3.count
FROM
(
    SELECT TOP 10 CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                      COUNT(b.foo) AS count
    FROM
    (
        SELECT b2.foo - (b2.foo % 10) AS foo
        FROM
        (
            SELECT CAST(b.foo * 100 AS INT) AS foo
            FROM eee b
                 INNER JOIN bar f ON b.bar_id = f.id
            WHERE b.foo < 1
                  AND f.nome = 'aaa'
        ) b2
    ) b
    GROUP BY b.foo
    ORDER BY b.foo
)
</code>```

How should I write the regex I need?

答:
This works okay with some changes I made to handle quoted parens:</p>

```<code>var pattern = @"SELECT ((?:[^'()]|(?>'[^']+')|(?<open>\()|(?<-open>\)))+(?(open)(?!)))LIMIT (\d+)";

query = Regex.Replace(query, pattern, "SELECT TOP $2 $1");
</code>```

Body:
I have some query string written for PostgreSQL and I have to convert them to SqlServer. I'm using C# 6.

In order to convert from LIMIT syntax to TOP syntax I've written the following simple regex:

SELECT ([\S\s]*)LIMIT (\d+) -> SELECT TOP $2 $1

The complete line code is:

return Regex.Replace(query, @"SELECT ([\S\s]*)LIMIT (\d+)", "SELECT TOP $2 $1", RegexOptions.RightToLeft);

Now, eveything works fine for simple query but it does not work for subquery: the TOP string is put everytime in the super parent query.

Try for example the following query:

SELECT b3.aaa,
       b3.count
FROM
(
    SELECT CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                      COUNT(b.foo) AS count
    FROM
    (
        SELECT b2.foo - (b2.foo % 10) AS foo
        FROM
        (
            SELECT CAST(b.foo * 100 AS INT) AS foo
            FROM eee b
                 INNER JOIN bar f ON b.bar_id = f.id
            WHERE b.foo < 1
                  AND f.nome = 'aaa'
        ) b2
    ) b
    GROUP BY b.foo
    ORDER BY b.foo
    LIMIT 10
)

it is converted to:

SELECT TOP 10 b3.aaa,
       b3.count
FROM
(
    SELECT CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                      COUNT(b.foo) AS count
    FROM
    (
        SELECT b2.foo - (b2.foo % 10) AS foo
        FROM
        (
            SELECT CAST(b.foo * 100 AS INT) AS foo
            FROM eee b
                 INNER JOIN bar f ON b.bar_id = f.id
            WHERE b.foo < 1
                  AND f.nome = 'aaa'
        ) b2
    ) b
    GROUP BY b.foo
    ORDER BY b.foo
)

while I'd like to have

SELECT b3.aaa,
       b3.count
FROM
(
    SELECT TOP 10 CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                      COUNT(b.foo) AS count
    FROM
    (
        SELECT b2.foo - (b2.foo % 10) AS foo
        FROM
        (
            SELECT CAST(b.foo * 100 AS INT) AS foo
            FROM eee b
                 INNER JOIN bar f ON b.bar_id = f.id
            WHERE b.foo < 1
                  AND f.nome = 'aaa'
        ) b2
    ) b
    GROUP BY b.foo
    ORDER BY b.foo
)

How should I write the regex I need?

Body:
This works okay with some changes I made to handle quoted parens:

var pattern = @"SELECT ((?:[^'()]|(?>'[^']+')|(?<open>\()|(?<-open>\)))+(?(open)(?!)))LIMIT (\d+)";

query = Regex.Replace(query, pattern, "SELECT TOP $2 $1");


问:
Can mobile apps access the phone's settings?
I had an idea for an android app that would need access to the phone's settings. I am not sure that the app would be able to change any settings (such as screen brightness or turning on wifi).</p>

答:
yes you can acces to such things,
change screen brightness:

```<code> android.provider.Settings.System.putInt(getContentResolver(),
                android.provider.Settings.System.SCREEN_BRIGHTNESS,
                value);
</code>```

add this to manifest

```<code><uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</code>```

turn on wi-fi

```<code>WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
manager.setWifiEnabled(true);
</code>```

add this to manifest :

```<code><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
</code>```

Body:
yes you can acces to such things,
change screen brightness:

 android.provider.Settings.System.putInt(getContentResolver(),
                android.provider.Settings.System.SCREEN_BRIGHTNESS,
                value);

add this to manifest

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

turn on wi-fi

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
manager.setWifiEnabled(true);

add this to manifest :

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />


问:
Difference between npm configuration commands
Are

```<code>npm config set <key> <value>
</code>```

and

```<code>npm set <key> <value>
</code>```

synonymous?

Configuration of npm init with both of this commands, add init configuration to /home/.npmrc

```<code>npm config set init.author.name 'Some One'
npm set init.author.email 'some@one.com
</code>```

答:
They are synonymous.

Check NPM's source code on GitHub: The code of the set command is short and calls config's set.

https://github.com/npm/npm/blob/master/lib/set.js

```<code>module.exports = set

set.usage = 'npm set <key> <value> (See `npm config`)'

var npm = require('./npm.js')

set.completion = npm.commands.config.completion

function set (args, cb) {
  if (!args.length) return cb(set.usage)
  npm.commands.config(['set'].concat(args), cb)
}
</code>```

config command: https://github.com/npm/npm/blob/master/lib/config.js

Body:
Are

npm config set <key> <value>

and

npm set <key> <value>

synonymous?

Configuration of npm init with both of this commands, add init configuration to /home/.npmrc

npm config set init.author.name 'Some One'
npm set init.author.email 'some@one.com

Body:
They are synonymous.

Check NPM's source code on GitHub: The code of the set command is short and calls config's set.

https://github.com/npm/npm/blob/master/lib/set.js

module.exports = set

set.usage = 'npm set <key> <value> (See `npm config`)'

var npm = require('./npm.js')

set.completion = npm.commands.config.completion

function set (args, cb) {
  if (!args.length) return cb(set.usage)
  npm.commands.config(['set'].concat(args), cb)
}

config command: https://github.com/npm/npm/blob/master/lib/config.js


问:
How to stop Android from scrolling to the end of an EditText when the text is selected?
Be default, in an EditText, when all the text is selected and it is larger than the size of the EditText, the text is scrolled to the end. Is there a way to override this behavior so that the text is selected but remains in the current position?

This default behavior can be seen in Google’s Contacts app.

Create a new contact.

Type a long number in the phone number field, something like 6521487754158895575569856552149211111111111111.

Scroll to the beginning of the phone number.

Double-tap on the number to select the entire text.  The number will be selected and automatically scrolled to the end.

答:
I not sure if i understand very well, but i think  if you need to stop the scroll in edittext use this:</p>

```<code>editText.setMovementMethod(null);
</code>```

Body:
I not sure if i understand very well, but i think  if you need to stop the scroll in edittext use this:

editText.setMovementMethod(null);


问:
copy an element as HTML to clipboard
I've managed to write some jQuery to find an element and copy it's html to the clipboard (ie only).

The problem is that when I paste this into a rich text box area in sharepoint it pastes the HTML as text only.

How do i replicate the user action of highlighting a link on a page and pressing copy. When I do this manually and then paste the clipboard contents the rich text area realises that it is markup and replicates the link as an anchor in the text content.

答:
This is what I used to copy/paste a hyperlink  HTML element to the clipboard so that when you paste it the href is hidden and you only see the "prettier" name.

HTML:

```<code><button onclick="copyToClipboard()">Copy me!</button>
</code>```

Javascript:

```<code>var copyToClipboard = (function() {
    var _dataString = null;
    $('.transform').toggleClass('transform-active');
    document.addEventListener("copy", function(e){
        if (_dataString !== null) {
            try {
                e.clipboardData.setData("text/html", link);
                e.preventDefault();
            } finally {
                _dataString = null;
            }
        }
    });
    return function(data) {
        _dataString = data;
        document.execCommand("copy");
    };
})();
</code>```

Title: copy an element as HTML to clipboard

Body:
This is what I used to copy/paste a hyperlink  HTML element to the clipboard so that when you paste it the href is hidden and you only see the "prettier" name.

HTML:

<button onclick="copyToClipboard()">Copy me!</button>

Javascript:

var copyToClipboard = (function() {
    var _dataString = null;
    $('.transform').toggleClass('transform-active');
    document.addEventListener("copy", function(e){
        if (_dataString !== null) {
            try {
                e.clipboardData.setData("text/html", link);
                e.preventDefault();
            } finally {
                _dataString = null;
            }
        }
    });
    return function(data) {
        _dataString = data;
        document.execCommand("copy");
    };
})();


问:
How do get a timestamp on an ASP.NET MVC App
On web apps,  you commonly see something like "Last Logged In: 3 hours 42 minutes ago".   What is the best way to go about doing this.?  Use strings or Dates?  Also,  i'm bringing that timestamp back into a Kendo MVC Grid.  The column looks as such.

```<code>columns.Bound(c => c.LastStatusDateDiff).Title("Updated");
</code>```

My Linq code looks as such

```<code>select new ATSReDto
                {
                    CreatedDate = atsr.CreatedDt,
                    Desciption = atsr.Description,
                    LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now
// get date difference between now "DateTime.Now" and
// date/time pulled from SQL Server to display in Grid
                };
</code>```

Any suggestions greatly appreciated

答:
Since it is Kendo UI related, you could add a read-only property in the ViewModel class.

```<code>public class ViewModel
{
    public DateTime LastStatus { get; set; }

    public string LastStatusText
    {
        get
        {
            var span = DateTime.Now - LastStatus;
            return string.Format("Last Logged in : {0} days  {1} hours {2} minutes ago",
                span.Days, span.Hours, span.Minutes);
        }
    }
}
</code>```

Usage

```<code>columns.Bound(c => c.LastStatusText).Title("Updated");
</code>```

Body:
On web apps,  you commonly see something like "Last Logged In: 3 hours 42 minutes ago".   What is the best way to go about doing this.?  Use strings or Dates?  Also,  i'm bringing that timestamp back into a Kendo MVC Grid.  The column looks as such.

columns.Bound(c => c.LastStatusDateDiff).Title("Updated");

My Linq code looks as such

select new ATSReDto
                {
                    CreatedDate = atsr.CreatedDt,
                    Desciption = atsr.Description,
                    LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now
// get date difference between now "DateTime.Now" and
// date/time pulled from SQL Server to display in Grid
                };

Any suggestions greatly appreciated

Body:
Since it is Kendo UI related, you could add a read-only property in the ViewModel class.

public class ViewModel
{
    public DateTime LastStatus { get; set; }

    public string LastStatusText
    {
        get
        {
            var span = DateTime.Now - LastStatus;
            return string.Format("Last Logged in : {0} days  {1} hours {2} minutes ago",
                span.Days, span.Hours, span.Minutes);
        }
    }
}

Usage

columns.Bound(c => c.LastStatusText).Title("Updated");


问:
How to include commas in an input while not interfering with a calculation?
I've added commas to an input to make the number easier to read. I then have a function that displays a new value based on that input. It works -- until the value is longer than four digits (X,XXX). At that point it returns NaN. Anyone know what's going wrong?

HTML

```<code><input class="number" id="loan_amount" oninput="calculate()">
<input id="savings_number">
</code>```

Function to calculate savings

```<code>function calculate() {
    var myBox1 = document.getElementById('loan_amount').value;
    var result = document.getElementById('savings_number');
    var myResult = myBox1 * 0.01;
    result.value = myResult;
}
</code>```

Function to add commas and remove all characters except numbers

```<code>$('input.number').keyup(function (event) {
  // skip for arrow keys
  if (event.which >= 37 && event.which <= 40) {
      event.preventDefault();
  }

  var currentVal = $(this).val();
  var testDecimal = testDecimals(currentVal);
  if (testDecimal.length > 1) {
    console.log("You cannot enter more than one decimal point");
    currentVal = currentVal.slice(0, -1);
  }
  $(this).val(replaceCommas(currentVal));

});

function testDecimals(currentVal) {
  var count;
  currentVal.match(/\./g) === null ? count = 0 : count = currentVal.match(/\./g);
  return count;
}

function replaceCommas(yourNumber) {
  var components = yourNumber.toString().split(".");
  if (components.length === 1)
    components[0] = yourNumber;
  components[0] = components[0].replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  if (components.length === 2)
    components[1] = components[1].replace(/\D/g, "");
  return components.join(".");
}
</code>```

答:
Your problem is that the oninput event runs before Jquery's onkeyup event.  This means that your calculations occur before the commas have been removed - resulting in NaN.

Is there some reason why the calculate function can't be included at the end of the keyup event handler?  That way, you can be sure that it will always run after you have removed the commas.

Body:
I've added commas to an input to make the number easier to read. I then have a function that displays a new value based on that input. It works -- until the value is longer than four digits (X,XXX). At that point it returns NaN. Anyone know what's going wrong?

HTML

<input class="number" id="loan_amount" oninput="calculate()">
<input id="savings_number">

Function to calculate savings

function calculate() {
    var myBox1 = document.getElementById('loan_amount').value;
    var result = document.getElementById('savings_number');
    var myResult = myBox1 * 0.01;
    result.value = myResult;
}

Function to add commas and remove all characters except numbers

$('input.number').keyup(function (event) {
  // skip for arrow keys
  if (event.which >= 37 && event.which <= 40) {
      event.preventDefault();
  }

  var currentVal = $(this).val();
  var testDecimal = testDecimals(currentVal);
  if (testDecimal.length > 1) {
    console.log("You cannot enter more than one decimal point");
    currentVal = currentVal.slice(0, -1);
  }
  $(this).val(replaceCommas(currentVal));

});

function testDecimals(currentVal) {
  var count;
  currentVal.match(/\./g) === null ? count = 0 : count = currentVal.match(/\./g);
  return count;
}

function replaceCommas(yourNumber) {
  var components = yourNumber.toString().split(".");
  if (components.length === 1)
    components[0] = yourNumber;
  components[0] = components[0].replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  if (components.length === 2)
    components[1] = components[1].replace(/\D/g, "");
  return components.join(".");
}


答: I don't have the reputation to comment yet so I will have to give it as an answer, but the element you want is an nchor but your jQuery selector is targeting a  element.</p>

Title: JQuery selector returns undefined

Body:
This html code was generated of my php code, but I copied this out of the HTML code of the browser.

The console.log prints out undefined. I don't know why. It's probably a really dumb mistake, like always. Thank you for your help.

$('.show').click(function() {
  var id = $(this).attr('id');
  var div = $("div#" + id);
  console.log(div.html());
});

Heading +

Test!


问:
HTML-encoding lost when attribute read from input field
I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

For example,

<input id='hiddenId' type='hidden' value='chalk & cheese' />
```

<p>gets pulled into</p>

<pre class="lang-html prettyprint-override"><code><input type='text' value='chalk & cheese' />
</code>```

via some jQuery to get the value from the hidden field (it’s at this point that I lose the encoding):

$('#hiddenId').attr('value')
```

The problem is that when I read chalk & cheese from the hidden field, JavaScript seems to lose the encoding. I do not want the value to be chalk & cheese. I want the literal amp; to be retained.

Is there a JavaScript library or a jQuery method that will HTML-encode a string?

答:
I had a similar problem and solve it using the function encodeURIComponent from JavaScript (documentation)

For example, in your case if you use:

```<code><input id='hiddenId' type='hidden' value='chalk & cheese' />
</code>```

and

```<code>encodeURIComponent($('#hiddenId').attr('value'))
</code>```

you will get chalk%20%26%20cheese. Even spaces are kept.

In my case, I had to encode one backslash and this code works perfectly

```<code>encodeURIComponent('name/surname')
</code>```

and I got name%2Fsurname

Body:
I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

For example,

<input id='hiddenId' type='hidden' value='chalk & cheese' />

gets pulled into

<input type='text' value='chalk & cheese' />

via some jQuery to get the value from the hidden field (it’s at this point that I lose the encoding):

$('#hiddenId').attr('value')

The problem is that when I read chalk & cheese from the hidden field, JavaScript seems to lose the encoding. I do not want the value to be chalk & cheese. I want the literal amp; to be retained.

Is there a JavaScript library or a jQuery method that will HTML-encode a string?

Body:
I had a similar problem and solve it using the function encodeURIComponent from JavaScript (documentation)

For example, in your case if you use:

<input id='hiddenId' type='hidden' value='chalk & cheese' />

and

encodeURIComponent($('#hiddenId').attr('value'))

you will get chalk%20%26%20cheese. Even spaces are kept.

In my case, I had to encode one backslash and this code works perfectly

encodeURIComponent('name/surname')

and I got name%2Fsurname


问:
Simulink & Masks: Dynamic access to parameters "evaluate" and "tunable"
First of all, matlab version is 2011b, so I cannot use Simulink.MaskParameters class.

I have one simulink mask and some parameters inside. I need to determine in my function for each parameter if it is "evaluable" or "tunable".

Those two things are two checkboxes in the mask parameters dialog which you can select for any parameter.

For "tunable", there's the MaskTunableValues property. For "enable", there's the "MaskEnables" property.

Do you know if there's a way to programmatically access the same property but for "evaluate" ?
Thanks

答:
You're using too old a release for most people to be able to give you an exact solution, however, I'm sure (from memory) that this parameter is available.

If you click on the mask to select the block, then go to the MATLAB command line and type

```<code>get_param(gcb,'ObjectParameters')
</code>```

you'll get a list of all the block properties.  (You may already know that since you're aware of MaskTunableValues and MaskEnables.)  Near the bottom of that list are all of the properties related to the mask.

Now manually look at each/all of those properties, e.g.

```<code>get_param(gcb,'MaskTunableValues')
</code>```

and you'll find that one of them is a structure that contains the information that you're looking for. (You may need to dig down into the structure to find the specific info.)

Body:
You're using too old a release for most people to be able to give you an exact solution, however, I'm sure (from memory) that this parameter is available.

If you click on the mask to select the block, then go to the MATLAB command line and type

get_param(gcb,'ObjectParameters')

you'll get a list of all the block properties.  (You may already know that since you're aware of MaskTunableValues and MaskEnables.)  Near the bottom of that list are all of the properties related to the mask.

Now manually look at each/all of those properties, e.g.

get_param(gcb,'MaskTunableValues')

and you'll find that one of them is a structure that contains the information that you're looking for. (You may need to dig down into the structure to find the specific info.)


问:
PHP - Copying array changes internal pointer?
Have a weird one:

This code outputs "345":

```<code>$a = array(1,2,3,4,5);
foreach ($a as $key => $input)
{
    $ab  = next($a);
    echo $ab;
}
</code>```

But this code outputs "2345":

```<code>$a = array(1,2,3,4,5);
$abc = $a;
foreach ($a as $key => $input)
{
    $ab  = next($a);
    echo $ab;
}
</code>```

The only difference between the two codes, is that in the 2nd example the array $a was duplicated into array $abc (line 2)

Does that affect the internal pointer of the array, and how?

What is the the expected behavior?

答:
It is all dependent on which PHP version you are running:

Anything lower than 7 will output 345

while version 7 will output 2345

You can test Here

Body:
Have a weird one:

This code outputs "345":

$a = array(1,2,3,4,5);
foreach ($a as $key => $input)
{
    $ab  = next($a);
    echo $ab;
}

But this code outputs "2345":

$a = array(1,2,3,4,5);
$abc = $a;
foreach ($a as $key => $input)
{
    $ab  = next($a);
    echo $ab;
}

The only difference between the two codes, is that in the 2nd example the array $a was duplicated into array $abc (line 2)

Does that affect the internal pointer of the array, and how?

What is the the expected behavior?


问:
Using System.Attribute as Route Attribute Reflection
I have attribute list but I want to get specific properties of each attribute. For examle I have action like </p>

```<code>[HttpGet, Route("/autocomplete")]
[ActionInfo(Description = "bla bla bla blac")]
// GET: AutoComplete
public ActionResult AutoComplete()
{
    return View();
 }

 private static IEnumerable<Attribute> MyMethod(IEnumerable<Attribute> attributes)
 {
    foreach (Attribute attribute in attributes)
    {
        switch (attribute.GetType().Name)
        {
            case "HttpGetAttribute":
            {
                using (attribute as HttpGetAttribute)
                {
                    // my business
                }
                break;
            }
            case "RouteAttribute":
            {
                using (attribute as RouteAttribute)
                {
                    // my business
                }
                break;
            }
            case "ActionInfoAttribute":
            {
                using (attribute as ActionInfoAttribute)
                {
                    // my business
                }
                break;
            }
        }
    }

    return null;
}
</code>```

答:
I think this is what you're trying to do:

```<code>private static IEnumerable<Attribute> MyMethod(IEnumerable<Attribute> attributes)
{
    foreach (Attribute attribute in attributes)
    {
        if (attribute is HttpGetAttribute)
        {
            // cast to HttpGetAttribute to get properties
        }
        else if (attribute is RouteAttribute)
        {
            // cast to RouteAttribute to get properties
        }
        else if (attribute is ActionInfoAttribute)
        {
            // cast to ActionInfoAttribute to get properties
        }
    }

    return null;
}
</code>```

The using keyword does not make sense in this context.  using is used with types that implement IDisposable to dispose of them at the end of the using block.

Body:
I have attribute list but I want to get specific properties of each attribute. For examle I have action like

[HttpGet, Route("/autocomplete")]
[ActionInfo(Description = "bla bla bla blac")]
// GET: AutoComplete
public ActionResult AutoComplete()
{
    return View();
 }

 private static IEnumerable<Attribute> MyMethod(IEnumerable<Attribute> attributes)
 {
    foreach (Attribute attribute in attributes)
    {
        switch (attribute.GetType().Name)
        {
            case "HttpGetAttribute":
            {
                using (attribute as HttpGetAttribute)
                {
                    // my business
                }
                break;
            }
            case "RouteAttribute":
            {
                using (attribute as RouteAttribute)
                {
                    // my business
                }
                break;
            }
            case "ActionInfoAttribute":
            {
                using (attribute as ActionInfoAttribute)
                {
                    // my business
                }
                break;
            }
        }
    }

    return null;
}

Body:
I think this is what you're trying to do:

private static IEnumerable<Attribute> MyMethod(IEnumerable<Attribute> attributes)
{
    foreach (Attribute attribute in attributes)
    {
        if (attribute is HttpGetAttribute)
        {
            // cast to HttpGetAttribute to get properties
        }
        else if (attribute is RouteAttribute)
        {
            // cast to RouteAttribute to get properties
        }
        else if (attribute is ActionInfoAttribute)
        {
            // cast to ActionInfoAttribute to get properties
        }
    }

    return null;
}

The using keyword does not make sense in this context.  using is used with types that implement IDisposable to dispose of them at the end of the using block.


问:
Are the tiles and custom views in OMS dashboard updated periodically whenever there is new telemetry available?
How frequently are the tiles and custom views in OMS workspace updated with new data? Also is it something that we can configure? Our customer wants to look at the most recent data (few minutes delay is also acceptable) even though there will be alerts configured for most of the scenarios.</p>

答:
I'm currently working with test data, so the auto update feature of the tiles when minutes are passing, is an answer I cannot give at this moment. But they should be auto updating.

The time span is a setting which is called the time scope. You can set this up how you like. Setup in minutes, hour and days.

The tiles are built based on queries, the aggregations, grouping and intervals are also features you can make use of it.

The tiles are giving a global info, when you click on it, another page is being openend where you can develop a report like insight.


问:
Determining the Big-O of this algorithm
I'm trying to understand what the Big-O is of the code below.

What the code is supposed to do

Essentially, I am trying to select a subset (max size = selectionSize) of random nodes and any edges that exists between them. The selection of random nodes is done in the while loop. After having done that, I want to select any edges that exist between the selected nodes.

What I think it is & why

<s>I think the running time is O = n^2 where n=selectionSize. The reason is: even though I can increase the size of the elements in nodes (e.g. make it 10000), I don't believe it can affect the algorithm since I am only looping through the maximum of selectionSize. The only reason I am a bit worried that this is wrong is because of the while loop, where I select random elements from the list up until I have enough. While this can take quite long (because it is random), I don't think it affects the overall output in terms of time.</s>
Edit: ugh on second thoughts... Nevermind... The nodes size does affect it (since node.getNeighbors()can be at most the size of the nodes).. So I think that if the selectionSize is equal to the size of nodes, the running time is O=n^2 where n=size of nodes.

Any tips/hints would be appreciated.

Code

```<code>// nodes and selectionSize are my input:
int[] nodes = {1,2,3...,1000}; // 1000 elements
int selectionSize = 500; // This can be at most the size of the elements (in this case 1000)

run_algo(nodes, selectionSize);

public void run_algo(int[] nodes, int selectionSize) {
    randomNodesList = {};

    while(randomNodesList < selectionSize) {
        randomNode = selectRandomNode(nodes); // Assume O(1)

        if(!randomNodesList.exists(randomNode)) { // Assume O(1)
            randomNodesList.push_back(randomNode); // Assume O(1)
        }
    }

    foreach(node in randomNodesList) {
        foreach(neighbor in node.getNeighbors()) { // Max. nodes size (in this case 1000)
            if (!randomNodesList.exists(neighbor)) { // Assume O(1)
                AddEdge(node, neighbor); // Takes O(1) time
            }
        }
    }
}
</code>```

答:
I am not 100% sure if I understand this right. But let's break it down:
The while-Loop runs "selectionSize"-times best case and worst case n (where n is the amount of nodes)

Therefore the size of randomNodeList is in O(n).
In a simple graph you can have O(n-1) neighbours. So the whole loop must be in O(n^2) (Because of n *(n-1))

axiom is right. It is in fact not possible to find an upper bound for this algorithm. It's nondeterministic. It depends on your random numbers.

Title: Determining the Big-O of this algorithm

Body:
I'm trying to understand what the Big-O is of the code below.

What the code is supposed to do

Essentially, I am trying to select a subset (max size = selectionSize) of random nodes and any edges that exists between them. The selection of random nodes is done in the while loop. After having done that, I want to select any edges that exist between the selected nodes.

What I think it is & why

<s>I think the running time is O = n^2 where n=selectionSize. The reason is: even though I can increase the size of the elements in nodes (e.g. make it 10000), I don't believe it can affect the algorithm since I am only looping through the maximum of selectionSize. The only reason I am a bit worried that this is wrong is because of the while loop, where I select random elements from the list up until I have enough. While this can take quite long (because it is random), I don't think it affects the overall output in terms of time.</s>
Edit: ugh on second thoughts... Nevermind... The nodes size does affect it (since node.getNeighbors()can be at most the size of the nodes).. So I think that if the selectionSize is equal to the size of nodes, the running time is O=n^2 where n=size of nodes.

Any tips/hints would be appreciated.

Code

// nodes and selectionSize are my input:
int[] nodes = {1,2,3...,1000}; // 1000 elements
int selectionSize = 500; // This can be at most the size of the elements (in this case 1000)

run_algo(nodes, selectionSize);

public void run_algo(int[] nodes, int selectionSize) {
    randomNodesList = {};

    while(randomNodesList < selectionSize) {
        randomNode = selectRandomNode(nodes); // Assume O(1)

        if(!randomNodesList.exists(randomNode)) { // Assume O(1)
            randomNodesList.push_back(randomNode); // Assume O(1)
        }
    }

    foreach(node in randomNodesList) {
        foreach(neighbor in node.getNeighbors()) { // Max. nodes size (in this case 1000)
            if (!randomNodesList.exists(neighbor)) { // Assume O(1)
                AddEdge(node, neighbor); // Takes O(1) time
            }
        }
    }
}


问:
Stanford POS tagger with nltk in arabic text
I am trying to use Stanford POS Tagger in NLTK 3.2.4 on arabic text using Python 3.6, I found a code source but I did not understand most of it because I am totally new to Stanford POS Tagger.

Code Source :

```<code>import os
java_path = "C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe"
os.environ['JAVAHOME'] = java_path

from nltk.tag.stanford import StanfordPOSTagger as POS_Tag
home = 'E:\\Asmaa\\TP python\\'
_path_to_model = home + 'stanford-arabic-corenlp-2017-06-09-models.jar'
_path_to_jar = home + 'stanford-postagger.jar'
POS_Tag.java_options='-mx4096m'
st = POS_Tag(model_filename=_path_to_model, path_to_jar=_path_to_jar)
sentence = '.شرب القط الحليب اللذيذ'
st.tag(sentence.split())
</code>```

The error I get :

```<code>Exception in thread "main" java.lang.RuntimeException: 'file' parameter must be specified
    at edu.stanford.nlp.tagger.maxent.TaggerConfig.<init>(TaggerConfig.java:87)
    at edu.stanford.nlp.tagger.maxent.MaxentTagger.main(MaxentTagger.java:273)
Traceback (most recent call last):
  File "<input>", line 8, in <module>
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 76, in tag
    return sum(self.tag_sents([tokens]), [])
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 99, in tag_sents
    stdout=PIPE, stderr=PIPE)
  File "F:\Python36\lib\site-packages\nltk\internals.py", line 136, in java
    raise OSError('Java command failed : ' + str(cmd))
OSError: Java command failed : ['C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe', '-mx1000m', '-cp', 'E:\\Asmaa\\TP python\\stanford-postagger.jar', 'edu.stanford.nlp.tagger.maxent.MaxentTagger', '-model', 'E:\\Asmaa\\TP python\\stanford-arabic-corenlp-2017-06-09-models.jar', '-textFile', 'C:\\Users\\2017\\AppData\\Local\\Temp\\tmpqajz7z6c', '-tokenize', 'false', '-outputFormatOptions', 'keepEmptySentences', '-encoding', 'utf8']
</code>```

So what goes wrong ?

答:
I found the solution in this web page, it was in the arabic model.

The right code:

```<code>import os
java_path = "C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe"
os.environ['JAVAHOME'] = java_path

from nltk.tag.stanford import StanfordPOSTagger as POS_Tag
arabic_postagger = POS_Tag('models/arabic.tagger', 'stanford-postagger.jar')
sentence = '.شرب القط الحليب اللذيذ'
print(arabic_postagger.tag(sentence.split()))
</code>```

The result:

[('', 'شرب/VBD'), ('', 'القط/DTNN'), ('', 'الحليب/DTNN'), ('', 'اللذيذ/DTJJ')]

Body:
I am trying to use Stanford POS Tagger in NLTK 3.2.4 on arabic text using Python 3.6, I found a code source but I did not understand most of it because I am totally new to Stanford POS Tagger.

Code Source :

import os
java_path = "C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe"
os.environ['JAVAHOME'] = java_path

from nltk.tag.stanford import StanfordPOSTagger as POS_Tag
home = 'E:\\Asmaa\\TP python\\'
_path_to_model = home + 'stanford-arabic-corenlp-2017-06-09-models.jar'
_path_to_jar = home + 'stanford-postagger.jar'
POS_Tag.java_options='-mx4096m'
st = POS_Tag(model_filename=_path_to_model, path_to_jar=_path_to_jar)
sentence = '.شرب القط الحليب اللذيذ'
st.tag(sentence.split())

The error I get :

Exception in thread "main" java.lang.RuntimeException: 'file' parameter must be specified
    at edu.stanford.nlp.tagger.maxent.TaggerConfig.<init>(TaggerConfig.java:87)
    at edu.stanford.nlp.tagger.maxent.MaxentTagger.main(MaxentTagger.java:273)
Traceback (most recent call last):
  File "<input>", line 8, in <module>
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 76, in tag
    return sum(self.tag_sents([tokens]), [])
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 99, in tag_sents
    stdout=PIPE, stderr=PIPE)
  File "F:\Python36\lib\site-packages\nltk\internals.py", line 136, in java
    raise OSError('Java command failed : ' + str(cmd))
OSError: Java command failed : ['C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe', '-mx1000m', '-cp', 'E:\\Asmaa\\TP python\\stanford-postagger.jar', 'edu.stanford.nlp.tagger.maxent.MaxentTagger', '-model', 'E:\\Asmaa\\TP python\\stanford-arabic-corenlp-2017-06-09-models.jar', '-textFile', 'C:\\Users\\2017\\AppData\\Local\\Temp\\tmpqajz7z6c', '-tokenize', 'false', '-outputFormatOptions', 'keepEmptySentences', '-encoding', 'utf8']

So what goes wrong ?

Body:
I found the solution in this web page, it was in the arabic model.

The right code:

import os
java_path = "C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe"
os.environ['JAVAHOME'] = java_path

from nltk.tag.stanford import StanfordPOSTagger as POS_Tag
arabic_postagger = POS_Tag('models/arabic.tagger', 'stanford-postagger.jar')
sentence = '.شرب القط الحليب اللذيذ'
print(arabic_postagger.tag(sentence.split()))

The result:

[('', 'شرب/VBD'), ('', 'القط/DTNN'), ('', 'الحليب/DTNN'), ('', 'اللذيذ/DTJJ')]


问:
Code works fine, just want to know why I don't need a set method for Perimeter and Area but for width and length
```<code>import java.util.Scanner;

public class Rectangle {

    private double length, width;

    Scanner scan = new Scanner(System.in);

    public Rectangle(double length, double width){
        this.length = length;
        this.width  = width;
    }
    public void setLength(double l){
        length = l;
    }
    public double getLength(){
        return length;
    }
    public void setWidth(double w){
        w = width;
    }
    public double getWidth(){
        return width;
    }
    public double getArea(){
        return length*width;
    }
    public double getPerimeter(){
        return ((2*length) + (2*width));`enter code here`
    }
}
</code>```

Why don't I need a set method for Area and Perimeter? Also does it matter if you make the code this.length = length as compared to length = l?

答:
Think about it this way: how would you implement a setter for the perimeter or the area property?

There is no good way of doing it that would make reasonable sense to users of your class: let's say the width is 10 and the height is 7, and a call arrives to set the perimeter to 24. Would you adjust the height, the width, or both in order to satisfy the new value of the perimeter? There is no usable solution to this problem.

Area and Perimeter are so-called calculated properties, i.e. properties computed from values of settable properties. That is why neither area nor perimeter can have a setter.

Body:
import java.util.Scanner;

public class Rectangle {

    private double length, width;

    Scanner scan = new Scanner(System.in);

    public Rectangle(double length, double width){
        this.length = length;
        this.width  = width;
    }
    public void setLength(double l){
        length = l;
    }
    public double getLength(){
        return length;
    }
    public void setWidth(double w){
        w = width;
    }
    public double getWidth(){
        return width;
    }
    public double getArea(){
        return length*width;
    }
    public double getPerimeter(){
        return ((2*length) + (2*width));`enter code here`
    }
}

Why don't I need a set method for Area and Perimeter? Also does it matter if you make the code this.length = length as compared to length = l?


问:
Use a web api from another tenant - Azure AD B2C
I’d like to use scopes in our Azure B2C instance, however all our resources are residing in a different active directory. Can I somehow also select the API instance from another Resource? Or is it possible to upgrade our main AD to an Azure B2C one? Or can we somehow move our subscription and all resources to our Azure B2C AD?</p>

答:
At this point in time, Azure AD B2C does not support multi-tenancy. You can vote and keep track of the feature in the Azure AD B2C UserVoice forum:

How to use Multitenant Applications Based on B2C

Without multitenancy, you will not be able to access resources from other tenants. It is also not possible to upgrade your main AD to an Azure AD B2C tenant, or have subscriptions within your Azure AD B2C Tenant.

Not entirely sure what your scenario is, but the recommended way to do this is by adding Azure AD as an identity provider. This currently can be done using custom policies, but I would encourage waiting until the feature is available through built-in policies.


问:
How to manipulate history in React Router v4?
I am using:

React, Redux, React-Router, Meteor

Following situation:

I have a modal with two tabs, based on the chosen tab a different list of selections will be shown in the content area, picking a selection will then give a list of subselection (all within the modal).

Desired behavior:

I want the user to be able to use the browser's back button to "undo" clicking on one of the tabs or picking a selection.

What I tried so far with no success:

use withRouter HOC to wrap my component, so that I would get access to history. I would then use history.push(currentUrl,{selectedTab:selection})
-> Problem: the state from push wasn't stored on this histories location object, but only in the state of the history object associated with my rootcomponent (way further up the tree)

(More promising so far) Simply import the history I created with createHistory in another module and put that into component state on construction.
I would then access the push method by using this.state.history.push(currentUrl,{selectedTab:selection}), which works fine and I can find the pushed state under this.state.history.location.state.selectedTab. However, using the browser's back button does not cause a rerender and therefore the selection will stay the same.

Any ideas?

Cheers

答: Another approach you could take would be to use query params with React router. And in your component change the tabs based on the query param. Since the url changed you should get the default behaviour your looking for.</p>