问:
Time for getting by comparable key from HashMap
AFAIK since java 8 bucket structure was changed from linked list to tree.

So in case hashCode() method return constant and our key class implements Comparable interface then complexity to get element from single cell will be reduced from O(n) to O(log n).

I tried to check it:

```<code> public static void main(String[] args) {
    int max = 30000;
    int times = 100;
    HashMap<MyClass, Integer> map = new HashMap<>();
    HashMap<MyComparableClass, Integer> compMap = new HashMap<>();

    for(int i = 0; i < max; i++) {
        map.put(new MyClass(i), i);
        compMap.put(new MyComparableClass(i), i);
    }

    long startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        compMap.get(new MyComparableClass(i));
    }
    System.out.println(String.format("Key is comparable:    %d", System.nanoTime() - startTime));

    startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        map.get(new MyClass(i));
    }
    System.out.println(String.format("Key isn't comparable: %d", System.nanoTime() - startTime));
}
</code>```

MyComparableClass:

```<code>public class MyComparableClass
        implements Comparable {
    public Integer value;

    public MyComparableClass(Integer value) {
        this.value = value;
    }

    @Override
    public int compareTo(Object o) {
        return this.value - ((MyComparableClass) o).value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyComparableClass myClass = (MyComparableClass) o;

        return value != null ? value.equals(myClass.value) : myClass.value == null;
    }

    @Override
    public int hashCode() {
        return 1;
    }
}
</code>```

MyClass is the same as MyComparableClass but doesn't implement Comparable interface.

And unexpectedly i always get results where time for getting value by non comparable key less than by comparable.

```<code>Key is comparable:    23380708
Key isn't comparable: 10721718
</code>```

Can someone explain?

答:
There are some flaws with your benchmark, but in this case, the tendency still can be acknowledged. The problem with your code is that you are implementing the raw type Comparable, but the HashMap implementation verifies the type compatibility before deciding to use it for resolving hash collisions.

So in your case, the natural order is never used within the HashMap implementation, but your class implementing the raw type Comparable is causing a more expensive check. Have a look at HashMap.comparableClassFor(Object x):

```<code>static Class<?> comparableClassFor(Object x) {
    if (x instanceof Comparable) {
        Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
        if ((c = x.getClass()) == String.class) // bypass checks
            return c;
        if ((ts = c.getGenericInterfaces()) != null) {
            for (int i = 0; i < ts.length; ++i) {
                if (((t = ts[i]) instanceof ParameterizedType) &&
                    ((p = (ParameterizedType)t).getRawType() ==
                     Comparable.class) &&
                    (as = p.getActualTypeArguments()) != null &&
                    as.length == 1 && as[0] == c) // type arg is c
                    return c;
            }
        }
    }
    return null;
}
</code>```

For your key class not implementing Comparable, the test is over right at x instanceof Comparable. For the other class, this rather cheap instanceof test evaluates to true and the much more complicated test for the generic type signature is made which will then fail. And the result of this test is not remembered, but repeated not only for every key:

When you look at HashMap.find:

```<code>final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
    TreeNode<K,V> p = this;
    do {
        int ph, dir; K pk;
        TreeNode<K,V> pl = p.left, pr = p.right, q;
        if ((ph = p.hash) > h)
            p = pl;
        else if (ph < h)
            p = pr;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        else if (pl == null)
            p = pr;
        else if (pr == null)
            p = pl;
        else if ((kc != null ||
                  (kc = comparableClassFor(k)) != null) &&
                 (dir = compareComparables(kc, k, pk)) != 0)
            p = (dir < 0) ? pl : pr;
        else if ((q = pr.find(h, k, kc)) != null)
            return q;
        else
            p = pl;
    } while (p != null);
    return null;
}
</code>```

you will see that after the test comparableClassFor failed, find is invoked recursively. It tries to remember the result of the test using kc and passing it down, but in the failed case it’s null and thus treated like not being made yet, in other words, the test will be repeated whenever descending into a subtree, but since the natural order is not used, this code might have to loop over the other subtree as well if the key has not been found in the first, also repeating the test in every iteration.

Or, in other words, this comparableClassFor(k) might be repeated for every element in that bucket in the worst case. And JVM optimizations might even change the result in favor of the class not implementing Comparable, as the JVM might recognize the repeated identical instanceof tests on the same key object and optimize them, whereas the test for the generic type signature is not an intrinsic JVM operation and its outcome less likely to get predicted.

Of course, the result changes dramatically when your MyComparableClass correctly implements Comparable<MyComparableClass>. Then, the natural order is used to change the time complexity from O(n) to O(log n), but also the test is only done once for each lookup, as the then-non-null result will be remembered in kc.

Body:
AFAIK since java 8 bucket structure was changed from linked list to tree.

So in case hashCode() method return constant and our key class implements Comparable interface then complexity to get element from single cell will be reduced from O(n) to O(log n).

I tried to check it:

 public static void main(String[] args) {
    int max = 30000;
    int times = 100;
    HashMap<MyClass, Integer> map = new HashMap<>();
    HashMap<MyComparableClass, Integer> compMap = new HashMap<>();

    for(int i = 0; i < max; i++) {
        map.put(new MyClass(i), i);
        compMap.put(new MyComparableClass(i), i);
    }

    long startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        compMap.get(new MyComparableClass(i));
    }
    System.out.println(String.format("Key is comparable:    %d", System.nanoTime() - startTime));

    startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        map.get(new MyClass(i));
    }
    System.out.println(String.format("Key isn't comparable: %d", System.nanoTime() - startTime));
}

MyComparableClass:

public class MyComparableClass
        implements Comparable {
    public Integer value;

    public MyComparableClass(Integer value) {
        this.value = value;
    }

    @Override
    public int compareTo(Object o) {
        return this.value - ((MyComparableClass) o).value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyComparableClass myClass = (MyComparableClass) o;

        return value != null ? value.equals(myClass.value) : myClass.value == null;
    }

    @Override
    public int hashCode() {
        return 1;
    }
}

MyClass is the same as MyComparableClass but doesn't implement Comparable interface.

And unexpectedly i always get results where time for getting value by non comparable key less than by comparable.

Key is comparable:    23380708
Key isn't comparable: 10721718

Can someone explain?

Body:
There are some flaws with your benchmark, but in this case, the tendency still can be acknowledged. The problem with your code is that you are implementing the raw type Comparable, but the HashMap implementation verifies the type compatibility before deciding to use it for resolving hash collisions.

So in your case, the natural order is never used within the HashMap implementation, but your class implementing the raw type Comparable is causing a more expensive check. Have a look at HashMap.comparableClassFor(Object x):

static Class<?> comparableClassFor(Object x) {
    if (x instanceof Comparable) {
        Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
        if ((c = x.getClass()) == String.class) // bypass checks
            return c;
        if ((ts = c.getGenericInterfaces()) != null) {
            for (int i = 0; i < ts.length; ++i) {
                if (((t = ts[i]) instanceof ParameterizedType) &&
                    ((p = (ParameterizedType)t).getRawType() ==
                     Comparable.class) &&
                    (as = p.getActualTypeArguments()) != null &&
                    as.length == 1 && as[0] == c) // type arg is c
                    return c;
            }
        }
    }
    return null;
}

For your key class not implementing Comparable, the test is over right at x instanceof Comparable. For the other class, this rather cheap instanceof test evaluates to true and the much more complicated test for the generic type signature is made which will then fail. And the result of this test is not remembered, but repeated not only for every key:

When you look at HashMap.find:

final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
    TreeNode<K,V> p = this;
    do {
        int ph, dir; K pk;
        TreeNode<K,V> pl = p.left, pr = p.right, q;
        if ((ph = p.hash) > h)
            p = pl;
        else if (ph < h)
            p = pr;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        else if (pl == null)
            p = pr;
        else if (pr == null)
            p = pl;
        else if ((kc != null ||
                  (kc = comparableClassFor(k)) != null) &&
                 (dir = compareComparables(kc, k, pk)) != 0)
            p = (dir < 0) ? pl : pr;
        else if ((q = pr.find(h, k, kc)) != null)
            return q;
        else
            p = pl;
    } while (p != null);
    return null;
}

you will see that after the test comparableClassFor failed, find is invoked recursively. It tries to remember the result of the test using kc and passing it down, but in the failed case it’s null and thus treated like not being made yet, in other words, the test will be repeated whenever descending into a subtree, but since the natural order is not used, this code might have to loop over the other subtree as well if the key has not been found in the first, also repeating the test in every iteration.

Or, in other words, this comparableClassFor(k) might be repeated for every element in that bucket in the worst case. And JVM optimizations might even change the result in favor of the class not implementing Comparable, as the JVM might recognize the repeated identical instanceof tests on the same key object and optimize them, whereas the test for the generic type signature is not an intrinsic JVM operation and its outcome less likely to get predicted.

Of course, the result changes dramatically when your MyComparableClass correctly implements Comparable<MyComparableClass>. Then, the natural order is used to change the time complexity from O(n) to O(log n), but also the test is only done once for each lookup, as the then-non-null result will be remembered in kc.


来源: stackexchange

问:
Add image data to html file?
My goal is to create one HTML file, that contains everything that it needs for it's proper functioning.

I've added my .css's content to the html head between

答:
Just upload your images to the site imageBB copy the source link paste it into your HTML file. This way the images will be loaded directly from the server and you don't need to copy the images in every system you need to load your site.

Pros:

1)You can load the image from the server directly.

2)No need to copy the images repeatedly in every system

cons

1) The system which you want to load the site needs to have an internet connection.

ContentLicense: CC BY-SA 3.0

Title: Add image data to html file?


问:
Angular inside Apache HTTPS
I have an App in Angular 4 that I built with ng build --prod command, this files are in the Apache folder and working good but when I refresh the page or I try to access for example 192.168.1.10/login, I get this error:

Not Found The requested URL /login was not found on this server.

I know that this error is because Apache try to resolve the directory throw the folders but I setup it and it dosen't still working:

```<code><VirtualHost *:443>
    ServerName  my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>
</code>```

Observation:

Before to implements HTTPS I have this configuration and working fine:

```<code><VirtualHost *:80>
    ServerName my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>
</code>```

答:
My guess is that https works through port *:443 and your config is for port *:80

Try duplicating your config for <VirtualHost *:443>

Title: Angular inside Apache HTTPS

Body:
I have an App in Angular 4 that I built with ng build --prod command, this files are in the Apache folder and working good but when I refresh the page or I try to access for example 192.168.1.10/login, I get this error:

Not Found The requested URL /login was not found on this server.

I know that this error is because Apache try to resolve the directory throw the folders but I setup it and it dosen't still working:

<VirtualHost *:443>
    ServerName  my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Observation:

Before to implements HTTPS I have this configuration and working fine:

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>


问:
when click on row showing error IndexError: list index out of range

test.py

```<code>import kivy

kivy.require('1.9.0')  # replace with your current kivy version !
import sqlite3 as lite
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty,NumericProperty
from kivy.lang import Builder
from kivy.uix.dropdown import DropDown

from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window
Window.size = (900, 500)

MAX_TABLE_COLS = 3

con = lite.connect('demo.db')
con.text_factory = str
cur = con.cursor()

class EditStatePopup(Popup):
    col_data = ListProperty(["?", "?", "?"])
    index = NumericProperty(0)

    def __init__(self, obj, **kwargs):
        super(EditStatePopup, self).__init__(**kwargs)
        self.index = obj.index
        self.col_data[0] = obj.rv_data[self.index]["Id"]
        self.col_data[1] = obj.rv_data[self.index]["Name"]
        self.col_data[2] = obj.rv_data[self.index]["Code"]

    def package_changes(self, stateName, stateCode):
        self.col_data[1] = stateName
        self.col_data[2] = stateCode

class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
                                  RecycleGridLayout):
    ''' Adds selection and focus behaviour to the view. '''

class SelectableButton(RecycleDataViewBehavior, Button):
    ''' Add selection support to the Button '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    rv_data = ObjectProperty(None)
    start_point = NumericProperty(0)

    def __init__(self, **kwargs):
        super(SelectableButton, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, .0005)

    def update(self, *args):
        self.text = self.rv_data[self.index][self.key]

    def on_press(self):
        popup = EditStatePopup(self)
        popup.open()

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableButton, self).refresh_view_attrs(rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableButton, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected
        self.rv_data = rv.data
        #print("selection changed to {0}".format(rv.data[1]))

class RV(BoxLayout):
    data_items = ListProperty([])
    col1 = ListProperty()
    col2 = ListProperty()
    col3 = ListProperty()

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.get_states()

    def update(self):
        self.col1 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Id'} for x in self.data_items]
        self.col2 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Name'} for x in self.data_items]
        self.col3 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Code'} for x in self.data_items]

    def get_states(self):

        rows = [(1, 'Yash', 'Chopra'), (2, 'amit', 'Kumar')]
        # create data_items

        i = 0
        for row in rows:
            self.data_items.append([row[0], row[1], row[2], i])
            i += 1
        self.update()

class CustDrop(DropDown):
    def __init__(self, **kwargs):
        super(CustDrop, self).__init__(**kwargs)
        self.select('')

class MainMenu(BoxLayout):
    rv = ObjectProperty(None)
    states = ObjectProperty(None)
    dropdown = ObjectProperty(None)

    def display_states(self):
        self.dropdown.dismiss()
        self.remove_widgets()
        self.rv = RV()
        self.states.add_widget(self.rv)

    def remove_widgets(self):
        for child in [child for child in self.states.children]:
            self.states.remove_widget(child)

    def update_states(self, obj):
        # update data_items
        # obj.start_point + 1 --- skip State_ID
        self.rv.data_items[obj.index] = [ obj.col_data[0], obj.col_data[1], obj.col_data[2], obj.index]
        self.rv.update()
        # update Database Table
        cur.execute("UPDATE m_state SET state_name=?, state_code=? WHERE state_id=?",
                (obj.col_data[1], obj.col_data[2], obj.col_data[0]))
        con.commit()

class TestApp(App):
    title = "test"

    def build(self):
        self.root = Builder.load_file('test.kv')
        return MainMenu()

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

test.kv

```<code>#:kivy 1.10.0
#:import CoreImage kivy.core.image.Image
#:import os os

<EditStatePopup>:
    title: "Update State"
    size_hint: None, None
    size: 300, 300
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        GridLayout:
            cols: 2
            Label:
                text: "Id"
            Label:
                id: Id
                text: root.col_data[0]
            Label:
                text: "Name"
            TextInput:
                id: Name
                text: root.col_data[1]
            Label:
                text: "Code"
            TextInput:
                id: stateCode
                text: root.col_data[2]

            Button:
                size_hint: 1, 0.4
                text: "Cancel"
                on_release: root.dismiss()

            Button:
                size_hint: 1, 0.4
                text: "Ok"
                on_release:
                    root.package_changes(Name.text, Code.text)
                    #root.obj.update_states(root.start_point, root.max_table_cols, root.new_data)
                    app.root.update_states(root)
                    root.dismiss()

<SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
        Rectangle:
            pos: self.pos
            size: self.size

<MyRV@RecycleView>:
    viewclass: 'SelectableButton'
    SelectableRecycleGridLayout:
        cols: 1
        default_size: None, dp(26)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: True
        touch_multiselect: True

<RV>:
    BoxLayout:
        orientation: "vertical"

        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 3

            Label:
                size_hint_x: .1
                text: "Id"
            Label:
                size_hint_x: .5
                text: "Name"
            Label:
                size_hint_x: .4
                text: "Code"

        BoxLayout:
            MyRV:
                size_hint_x: .1
                data: root.col1
            MyRV:
                size_hint_x: .5
                data: root.col2
            MyRV:
                size_hint_x: .4
                data: root.col3

<DropdownButton@Button>:
    border: (0, 16, 0, 16)
    text_size: self.size
    valign: "middle"
    padding_x: 5
    size_hint_y: None
    height: '30dp'
    #on_release: dropdown.select('')
    #on_release: app.root.test
    background_color: 90 , 90, 90, 90
    color: 0, 0.517, 0.705, 1

#<CustDrop>:
    #id: dropdown
    #auto_width: False
    #width: 150
    #DropdownButton:
        #text: 'Add State'
        #on_release: os.system("python m_State.py")

    #DropdownButton:
        #text: 'List State'
        #on_release: root.display_users()

<MenuButton@Button>:
    text_size: self.size
    valign: "middle"
    padding_x: 5
    size : (80,30)
    size_hint : (None, None)
    background_color: 90 , 90, 90, 90
    background_normal: ''
    color: 0, 0.517, 0.705, 1
    border: (0, 10, 0, 0)

<MainMenu>:
    states: states
    dropdown: dropdown

    BoxLayout:
        orientation: 'vertical'
        #spacing : 10

        BoxLayout:
            canvas.before:
                Rectangle:
                    pos: self.pos
                    size: self.size

            size_hint_y: 1

            MenuButton:
                id: btn
                text: 'Menu'
                size : (60,30)
                on_release: dropdown.open(self)

            CustDrop:
                id: dropdown
                auto_width: False
                width: 150

                DropdownButton:
                    text: 'user'
                    size_hint_y: None
                    height: '32dp'
                    #on_release: dropdown3.open(self)
                    on_release: root.display_states()

        BoxLayout:
            id: states
            size_hint_y: 9

        Label:
            size_hint_y: 9
</code>```

When i click on menu then show sub menu user.when click on user then show list of user when i click on any row of user then show error IndexError: list index out of range.

update_states() function does not update in database

答:
1.When i click on menu then show sub menu user.when click on user then show list of user when i click on any row of user then show error like attached image.

You are iterating over rows, you have only two rows but 3 columns

update_states() function does not update in database

I don't think that the compilator terminates that function because there are few errors in it

To get your code works I had to make many changes

First prepare the data of the rvs in the python file

```<code>...

class RV(BoxLayout):
    data_items = ListProperty([])
    col1 = ListProperty()
    col2 = ListProperty()
    col3 = ListProperty()

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.get_states()

    def update(self):
        self.col1 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Id'} for x in self.data_items]
        self.col2 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Name'} for x in self.data_items]
        self.col3 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Code'} for x in self.data_items]

    def get_states(self):

        #cur.execute("SELECT * FROM `m_state` order by state_id asc")
        #rows = cur.fetchall()
        rows = [(1, 'Yash', 'Chopra'), (2, 'amit', 'Kumar')]
        # create data_items
        '''for row in rows:
            for col in row:
                self.data_items.append(col)'''
        i = 0
        for row in rows:
            self.data_items.append([row[0], row[1], row[2], i])
            i += 1
        self.update()

...
</code>```

then in the kv replace the data of the rvs by col1, col2, col3 respectively

```<code>...

<RV>:
    BoxLayout:
        orientation: "vertical"

        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 3

            Label:
                size_hint_x: .1
                text: "Id"
            Label:
                size_hint_x: .5
                text: "Name"
            Label:
                size_hint_x: .4
                text: "Code"

        BoxLayout:
            MyRV:
                size_hint_x: .1
                data: root.col1
            MyRV:
                size_hint_x: .5
                data: root.col2
            MyRV:
                size_hint_x: .4
                data: root.col3

...
</code>```

To change automatically the text of the buttons of the rvs when you edit them I had to schedule a function

```<code>...

class SelectableButton(RecycleDataViewBehavior, Button):
    ''' Add selection support to the Button '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    rv_data = ObjectProperty(None)
    start_point = NumericProperty(0)

    def __init__(self, **kwargs):
        super(SelectableButton, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, .0005)

    def update(self, *args):
        self.text = self.rv_data[self.index][self.key]

...

    def on_press(self):
        popup = EditStatePopup(self)
        popup.open()

...
</code>```

You have also to edit the EditStatePopup, I add the index attribute because It will be much easier to make change in the mainmenu with him

```<code>...

class EditStatePopup(Popup):
    col_data = ListProperty(["?", "?", "?"])
    index = NumericProperty(0)

    def __init__(self, obj, **kwargs):
        super(EditStatePopup, self).__init__(**kwargs)
        self.index = obj.index
        self.col_data[0] = obj.rv_data[self.index]["Id"]
        self.col_data[1] = obj.rv_data[self.index]["Name"]
        self.col_data[2] = obj.rv_data[self.index]["Code"]
</code>```

Finally edit the updtate_states of the MainMenu class:

```<code>...

class MainMenu(BoxLayout):
...
    def update_states(self, obj):
        # update data_items
        # obj.start_point + 1 --- skip State_ID
        self.rv.data_items[obj.index] = [ obj.col_data[0], obj.col_data[1], obj.col_data[2], obj.index]
        self.rv.update()
        # update Database Table
        cur.execute("UPDATE m_state SET state_name=?, state_code=? WHERE state_id=?",
                (obj.col_data[1], obj.col_data[2], obj.col_data[0]))
        con.commit()
</code>```

Please be careful when making those changes. I hope this helps

Body:
test.py

import kivy

kivy.require('1.9.0')  # replace with your current kivy version !
import sqlite3 as lite
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty,NumericProperty
from kivy.lang import Builder
from kivy.uix.dropdown import DropDown

from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window
Window.size = (900, 500)

MAX_TABLE_COLS = 3

con = lite.connect('demo.db')
con.text_factory = str
cur = con.cursor()

class EditStatePopup(Popup):
    col_data = ListProperty(["?", "?", "?"])
    index = NumericProperty(0)

    def __init__(self, obj, **kwargs):
        super(EditStatePopup, self).__init__(**kwargs)
        self.index = obj.index
        self.col_data[0] = obj.rv_data[self.index]["Id"]
        self.col_data[1] = obj.rv_data[self.index]["Name"]
        self.col_data[2] = obj.rv_data[self.index]["Code"]

    def package_changes(self, stateName, stateCode):
        self.col_data[1] = stateName
        self.col_data[2] = stateCode

class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
                                  RecycleGridLayout):
    ''' Adds selection and focus behaviour to the view. '''

class SelectableButton(RecycleDataViewBehavior, Button):
    ''' Add selection support to the Button '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    rv_data = ObjectProperty(None)
    start_point = NumericProperty(0)

    def __init__(self, **kwargs):
        super(SelectableButton, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, .0005)

    def update(self, *args):
        self.text = self.rv_data[self.index][self.key]

    def on_press(self):
        popup = EditStatePopup(self)
        popup.open()

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableButton, self).refresh_view_attrs(rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableButton, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected
        self.rv_data = rv.data
        #print("selection changed to {0}".format(rv.data[1]))

class RV(BoxLayout):
    data_items = ListProperty([])
    col1 = ListProperty()
    col2 = ListProperty()
    col3 = ListProperty()

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.get_states()

    def update(self):
        self.col1 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Id'} for x in self.data_items]
        self.col2 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Name'} for x in self.data_items]
        self.col3 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Code'} for x in self.data_items]

    def get_states(self):

        rows = [(1, 'Yash', 'Chopra'), (2, 'amit', 'Kumar')]
        # create data_items

        i = 0
        for row in rows:
            self.data_items.append([row[0], row[1], row[2], i])
            i += 1
        self.update()

class CustDrop(DropDown):
    def __init__(self, **kwargs):
        super(CustDrop, self).__init__(**kwargs)
        self.select('')

class MainMenu(BoxLayout):
    rv = ObjectProperty(None)
    states = ObjectProperty(None)
    dropdown = ObjectProperty(None)

    def display_states(self):
        self.dropdown.dismiss()
        self.remove_widgets()
        self.rv = RV()
        self.states.add_widget(self.rv)

    def remove_widgets(self):
        for child in [child for child in self.states.children]:
            self.states.remove_widget(child)

    def update_states(self, obj):
        # update data_items
        # obj.start_point + 1 --- skip State_ID
        self.rv.data_items[obj.index] = [ obj.col_data[0], obj.col_data[1], obj.col_data[2], obj.index]
        self.rv.update()
        # update Database Table
        cur.execute("UPDATE m_state SET state_name=?, state_code=? WHERE state_id=?",
                (obj.col_data[1], obj.col_data[2], obj.col_data[0]))
        con.commit()

class TestApp(App):
    title = "test"

    def build(self):
        self.root = Builder.load_file('test.kv')
        return MainMenu()

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

test.kv

#:kivy 1.10.0
#:import CoreImage kivy.core.image.Image
#:import os os

<EditStatePopup>:
    title: "Update State"
    size_hint: None, None
    size: 300, 300
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        GridLayout:
            cols: 2
            Label:
                text: "Id"
            Label:
                id: Id
                text: root.col_data[0]
            Label:
                text: "Name"
            TextInput:
                id: Name
                text: root.col_data[1]
            Label:
                text: "Code"
            TextInput:
                id: stateCode
                text: root.col_data[2]

            Button:
                size_hint: 1, 0.4
                text: "Cancel"
                on_release: root.dismiss()

            Button:
                size_hint: 1, 0.4
                text: "Ok"
                on_release:
                    root.package_changes(Name.text, Code.text)
                    #root.obj.update_states(root.start_point, root.max_table_cols, root.new_data)
                    app.root.update_states(root)
                    root.dismiss()

<SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
        Rectangle:
            pos: self.pos
            size: self.size

<MyRV@RecycleView>:
    viewclass: 'SelectableButton'
    SelectableRecycleGridLayout:
        cols: 1
        default_size: None, dp(26)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: True
        touch_multiselect: True

<RV>:
    BoxLayout:
        orientation: "vertical"

        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 3

            Label:
                size_hint_x: .1
                text: "Id"
            Label:
                size_hint_x: .5
                text: "Name"
            Label:
                size_hint_x: .4
                text: "Code"

        BoxLayout:
            MyRV:
                size_hint_x: .1
                data: root.col1
            MyRV:
                size_hint_x: .5
                data: root.col2
            MyRV:
                size_hint_x: .4
                data: root.col3

<DropdownButton@Button>:
    border: (0, 16, 0, 16)
    text_size: self.size
    valign: "middle"
    padding_x: 5
    size_hint_y: None
    height: '30dp'
    #on_release: dropdown.select('')
    #on_release: app.root.test
    background_color: 90 , 90, 90, 90
    color: 0, 0.517, 0.705, 1

#<CustDrop>:
    #id: dropdown
    #auto_width: False
    #width: 150
    #DropdownButton:
        #text: 'Add State'
        #on_release: os.system("python m_State.py")

    #DropdownButton:
        #text: 'List State'
        #on_release: root.display_users()

<MenuButton@Button>:
    text_size: self.size
    valign: "middle"
    padding_x: 5
    size : (80,30)
    size_hint : (None, None)
    background_color: 90 , 90, 90, 90
    background_normal: ''
    color: 0, 0.517, 0.705, 1
    border: (0, 10, 0, 0)

<MainMenu>:
    states: states
    dropdown: dropdown

    BoxLayout:
        orientation: 'vertical'
        #spacing : 10

        BoxLayout:
            canvas.before:
                Rectangle:
                    pos: self.pos
                    size: self.size

            size_hint_y: 1

            MenuButton:
                id: btn
                text: 'Menu'
                size : (60,30)
                on_release: dropdown.open(self)

            CustDrop:
                id: dropdown
                auto_width: False
                width: 150

                DropdownButton:
                    text: 'user'
                    size_hint_y: None
                    height: '32dp'
                    #on_release: dropdown3.open(self)
                    on_release: root.display_states()

        BoxLayout:
            id: states
            size_hint_y: 9

        Label:
            size_hint_y: 9

When i click on menu then show sub menu user.when click on user then show list of user when i click on any row of user then show error IndexError: list index out of range.

update_states() function does not update in database

Body:
1.When i click on menu then show sub menu user.when click on user then show list of user when i click on any row of user then show error like attached image.

You are iterating over rows, you have only two rows but 3 columns

update_states() function does not update in database

I don't think that the compilator terminates that function because there are few errors in it

To get your code works I had to make many changes

First prepare the data of the rvs in the python file

...

class RV(BoxLayout):
    data_items = ListProperty([])
    col1 = ListProperty()
    col2 = ListProperty()
    col3 = ListProperty()

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.get_states()

    def update(self):
        self.col1 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Id'} for x in self.data_items]
        self.col2 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Name'} for x in self.data_items]
        self.col3 = [{'Id': str(x[0]), 'Name': x[1], 'Code': x[2], 'key': 'Code'} for x in self.data_items]

    def get_states(self):

        #cur.execute("SELECT * FROM `m_state` order by state_id asc")
        #rows = cur.fetchall()
        rows = [(1, 'Yash', 'Chopra'), (2, 'amit', 'Kumar')]
        # create data_items
        '''for row in rows:
            for col in row:
                self.data_items.append(col)'''
        i = 0
        for row in rows:
            self.data_items.append([row[0], row[1], row[2], i])
            i += 1
        self.update()

...

then in the kv replace the data of the rvs by col1, col2, col3 respectively

...

<RV>:
    BoxLayout:
        orientation: "vertical"

        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 3

            Label:
                size_hint_x: .1
                text: "Id"
            Label:
                size_hint_x: .5
                text: "Name"
            Label:
                size_hint_x: .4
                text: "Code"

        BoxLayout:
            MyRV:
                size_hint_x: .1
                data: root.col1
            MyRV:
                size_hint_x: .5
                data: root.col2
            MyRV:
                size_hint_x: .4
                data: root.col3

...

To change automatically the text of the buttons of the rvs when you edit them I had to schedule a function

...

class SelectableButton(RecycleDataViewBehavior, Button):
    ''' Add selection support to the Button '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    rv_data = ObjectProperty(None)
    start_point = NumericProperty(0)

    def __init__(self, **kwargs):
        super(SelectableButton, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, .0005)

    def update(self, *args):
        self.text = self.rv_data[self.index][self.key]

...

    def on_press(self):
        popup = EditStatePopup(self)
        popup.open()

...

You have also to edit the EditStatePopup, I add the index attribute because It will be much easier to make change in the mainmenu with him

...

class EditStatePopup(Popup):
    col_data = ListProperty(["?", "?", "?"])
    index = NumericProperty(0)

    def __init__(self, obj, **kwargs):
        super(EditStatePopup, self).__init__(**kwargs)
        self.index = obj.index
        self.col_data[0] = obj.rv_data[self.index]["Id"]
        self.col_data[1] = obj.rv_data[self.index]["Name"]
        self.col_data[2] = obj.rv_data[self.index]["Code"]

Finally edit the updtate_states of the MainMenu class:

...

class MainMenu(BoxLayout):
...
    def update_states(self, obj):
        # update data_items
        # obj.start_point + 1 --- skip State_ID
        self.rv.data_items[obj.index] = [ obj.col_data[0], obj.col_data[1], obj.col_data[2], obj.index]
        self.rv.update()
        # update Database Table
        cur.execute("UPDATE m_state SET state_name=?, state_code=? WHERE state_id=?",
                (obj.col_data[1], obj.col_data[2], obj.col_data[0]))
        con.commit()

Please be careful when making those changes. I hope this helps


问:
Getting additional input from SlackClient using python
One of the issues is I’m running into is getting additional data from a command in slack. I don’t want to use Slash commands because I can’t expose my localhost to the world.

Example:

```<code>@mybot do
</code>```

Will return, let’s say “I’m doing something”. However I want to be able to do something like

```<code>@mybot do 2
</code>```

Where 2 is a parameter in the back end. Basically what I’m trying to do is have it where the user can say @mybot do 2 and it will get data from the database where the ID is 2. You could make it a 3, 4, 5 etc and the command will pull the information from the database. I have found where I can make it match the exact “do” command, though I can’t get it to read the follow on data. I was following this tutorial. Any help will be great.

if you see weird symbols it’s because I’m doing this from an iPhone and I have that stupid bug where the turns I (eye) into I

答:
You need to use regular expressions to extract arguments from text. I hope this will help.</p>

```<code>import re

def handle_command(command, channel):
    response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
               "* command with numbers, delimited by spaces."

    match = re.match("do (?P<arg>\S+)", command)
    if match:
        arg = match.groupdict('arg')
        response = "Wow! My argument is: " + arg

    slack_client.api_call("chat.postMessage", channel=channel,
                          text=response, as_user=True)
</code>```

Body:
One of the issues is I’m running into is getting additional data from a command in slack. I don’t want to use Slash commands because I can’t expose my localhost to the world.

Example:

@mybot do

Will return, let’s say “I’m doing something”. However I want to be able to do something like

@mybot do 2

Where 2 is a parameter in the back end. Basically what I’m trying to do is have it where the user can say @mybot do 2 and it will get data from the database where the ID is 2. You could make it a 3, 4, 5 etc and the command will pull the information from the database. I have found where I can make it match the exact “do” command, though I can’t get it to read the follow on data. I was following this tutorial. Any help will be great.

if you see weird symbols it’s because I’m doing this from an iPhone and I have that stupid bug where the turns I (eye) into I

Body:
You need to use regular expressions to extract arguments from text. I hope this will help.

import re

def handle_command(command, channel):
    response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
               "* command with numbers, delimited by spaces."

    match = re.match("do (?P<arg>\S+)", command)
    if match:
        arg = match.groupdict('arg')
        response = "Wow! My argument is: " + arg

    slack_client.api_call("chat.postMessage", channel=channel,
                          text=response, as_user=True)


问:
Visual studio doesn't let compile "Sgen could not be run"
Getting the error:

```<code>"The specified task executable "sgen.exe" could not be run. The filename or extension is too long F:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets   3408"
</code>```

And Warning:

```<code>"The command-line for the "SGen" task is too long. Command-lines longer than 32000 characters are likely to fail. Try reducing the length of the command-line by breaking down the call to "SGen" into multiple calls with fewer parameters per call.   DAYAnalytics    F:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets 3408"
</code>```

At this part of Microsoft.Common.CurrentVersion.targets :

```<code><SGen
    BuildAssemblyName="$(TargetFileName)"
    BuildAssemblyPath="$(IntermediateOutputPath)"
    References="@(ReferencePath)"
    ShouldGenerateSerializer="$(SGenShouldGenerateSerializer)"
    UseProxyTypes="$(SGenUseProxyTypes)"
    UseKeep="$(SGenUseKeep)"
    KeyContainer="$(KeyContainerName)"
    KeyFile="$(KeyOriginatorFile)"
    DelaySign="$(DelaySign)"
    ToolPath="$(SGenToolPath)"
    SdkToolsPath="$(TargetFrameworkSDKToolsDirectory)"
    EnvironmentVariables="$(SGenEnvironment)"
    MSBuildArchitecture="$(SGenMSBuildArchitecture)"
    SerializationAssembly="$(IntermediateOutputPath)$(_SGenDllName)"
    Platform="$(SGenPlatformTarget)"
    Types="$(SGenSerializationTypes)">
</code>```

The explanation is pretty straightforward, But I don't understand how to fix it.
How do I reduce the command line length?

答: Set the "Generate serialization assembly" option in the Build options to "Auto" or "Off", unless you need them (that is, you make extensive use of the XmlSerializer), in which case you'll find more info here: Generating an Xml Serialization assembly as part of my build</p>

Body:
Getting the error:

"The specified task executable "sgen.exe" could not be run. The filename or extension is too long F:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets   3408"

And Warning:

"The command-line for the "SGen" task is too long. Command-lines longer than 32000 characters are likely to fail. Try reducing the length of the command-line by breaking down the call to "SGen" into multiple calls with fewer parameters per call.   DAYAnalytics    F:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets 3408"

At this part of Microsoft.Common.CurrentVersion.targets :

<SGen
    BuildAssemblyName="$(TargetFileName)"
    BuildAssemblyPath="$(IntermediateOutputPath)"
    References="@(ReferencePath)"
    ShouldGenerateSerializer="$(SGenShouldGenerateSerializer)"
    UseProxyTypes="$(SGenUseProxyTypes)"
    UseKeep="$(SGenUseKeep)"
    KeyContainer="$(KeyContainerName)"
    KeyFile="$(KeyOriginatorFile)"
    DelaySign="$(DelaySign)"
    ToolPath="$(SGenToolPath)"
    SdkToolsPath="$(TargetFrameworkSDKToolsDirectory)"
    EnvironmentVariables="$(SGenEnvironment)"
    MSBuildArchitecture="$(SGenMSBuildArchitecture)"
    SerializationAssembly="$(IntermediateOutputPath)$(_SGenDllName)"
    Platform="$(SGenPlatformTarget)"
    Types="$(SGenSerializationTypes)">

The explanation is pretty straightforward, But I don't understand how to fix it.
How do I reduce the command line length?


问:
Is it possible to find maximum value of 2 or more column in a table?
for example : I have a table as follows

```<code>    id     math     science     english     history
    1       80        90           90         90
    2       70        60           81         78
    3       69        50           45         80
    4       30        40           10         80
</code>```

i only want to find the maximum value in column math and science.
Is it possible?

答:
Simply use this :</p>

```<code>select max(science),max(math) from your_table
</code>```

Body:
for example : I have a table as follows

    id     math     science     english     history
    1       80        90           90         90
    2       70        60           81         78
    3       69        50           45         80
    4       30        40           10         80

i only want to find the maximum value in column math and science.
Is it possible?

Body:
Simply use this :

select max(science),max(math) from your_table


问:
SQL where condition in Codeigniter
I want to check if booking exists or not.  I have checkin date, checkout date, and room number. I tried below query but it gives all the data which is not of that room id also. What am I doing wrong?</p>

```<code>$array = array('checkin_date' => $checkin, 'checkout_date' => $checkin);
$array1 = array('checkin_date >' => $checkin, 'checkout_date <' => $checkin);
$array2 = array('checkin_date <' => $checkin, 'checkout_date >' => $checkin);
$array3 = array('checkin_date <' => $checkin, 'checkout_date <' => $checkin);
$array4 = array('checkin_date >=' => $checkin, 'checkout_date <=' => $checkin);
$array5 = array('checkin_date >=' => $checkout, 'checkout_date <=' => $checkout);

$this->db->select('*');
$this->db->from('igc_room_booking');
$this->db->where('delete_status', 0);
$this->db->where('cancel_status', 0);
$this->db->where('room_id', $val->room_id);
$this->db->where($array);
$this->db->or_where($array2);
$this->db->or_where($array3);
$this->db->or_where($array);
$this->db->or_where($array4);
$this->db->or_where($array5);
$bookingss = $this->db->get()->result();
</code>```

答:
I think the problem is that your query is wrong....you should remove

$this->db->select(*) and $this->db->from('igc_room_booking')

and instead after all your where clauses you should have

$this->db->get('igc_room_booking');

Title: SQL where condition in Codeigniter

Body:
I want to check if booking exists or not.  I have checkin date, checkout date, and room number. I tried below query but it gives all the data which is not of that room id also. What am I doing wrong?

$array = array('checkin_date' => $checkin, 'checkout_date' => $checkin);
$array1 = array('checkin_date >' => $checkin, 'checkout_date <' => $checkin);
$array2 = array('checkin_date <' => $checkin, 'checkout_date >' => $checkin);
$array3 = array('checkin_date <' => $checkin, 'checkout_date <' => $checkin);
$array4 = array('checkin_date >=' => $checkin, 'checkout_date <=' => $checkin);
$array5 = array('checkin_date >=' => $checkout, 'checkout_date <=' => $checkout);

$this->db->select('*');
$this->db->from('igc_room_booking');
$this->db->where('delete_status', 0);
$this->db->where('cancel_status', 0);
$this->db->where('room_id', $val->room_id);
$this->db->where($array);
$this->db->or_where($array2);
$this->db->or_where($array3);
$this->db->or_where($array);
$this->db->or_where($array4);
$this->db->or_where($array5);
$bookingss = $this->db->get()->result();


问:
SAS how do I change value labels in sgplot
I have a problem with changing value labels of xaxis in proc sgplot (see graph). I want to change x value labels 0 to 'female' and 1 to 'male', what should I do?

Many thanks in advance!

this is a box plot, label of x is gender, and I want the value labels displaying female instead of "0" and male instead of '1'

答:
You should change the value before creating your GPLOT.
Following this example :
http://documentation.sas.com/?docsetId=graphref&docsetTarget=n0zqluxg8kkrign1t1t727dis8ea.htm&docsetVersion=9.4&locale=en

First prepare your data :

```<code>data work.classtemp (drop=name );
   length Gender $ 6;
   set sashelp.class;
   if sex="F" then Gender="Female";
      else Gender="Male";
run;
proc sort data=work.classtemp out=work.class;
   by weight height;
run;
</code>```

After, label defintion :

```<code>legend1 label=none value=("Male" "Female") Position=(right middle outside)
across=1;
legend2 label=none value=("Male" "Female");
</code>```

In your case you have to prepare your data before the GPLOT by changing the 1 to Male and 0 to Female.

With something like this :

```<code>data want;
set mydata;
if value=0 then Gender="Female";
else Gender="Male";
run;
</code>```

Regards

Body:
You should change the value before creating your GPLOT.
Following this example :
http://documentation.sas.com/?docsetId=graphref&docsetTarget=n0zqluxg8kkrign1t1t727dis8ea.htm&docsetVersion=9.4&locale=en

First prepare your data :

data work.classtemp (drop=name );
   length Gender $ 6;
   set sashelp.class;
   if sex="F" then Gender="Female";
      else Gender="Male";
run;
proc sort data=work.classtemp out=work.class;
   by weight height;
run;

After, label defintion :

legend1 label=none value=("Male" "Female") Position=(right middle outside)
across=1;
legend2 label=none value=("Male" "Female");

In your case you have to prepare your data before the GPLOT by changing the 1 to Male and 0 to Female.

With something like this :

data want;
set mydata;
if value=0 then Gender="Female";
else Gender="Male";
run;

Regards


问:
Parse 2D Array in Kotlin
I have created a 2D array named squareData as shown below:

```<code> private lateinit var squareData: Array<Array<String>>

 squareData = Array(3, {Array(3, {""})})
</code>```

Also, I initialized this array with some random values. Now I want to fetch this values one by one. How can I do it using for or forEachIndexed loop?

答:
You can iterate in the array like this :

```<code>for (strings in squareData) {
    for (string in strings) {
        Your code here
    }
}
</code>```

The first for iterate through the first dimension so it has string arrays and the second one through the second dimension so it has the string values

Title: Parse 2D Array in Kotlin

Body:
I have created a 2D array named squareData as shown below:

 private lateinit var squareData: Array<Array<String>>

 squareData = Array(3, {Array(3, {""})})

Also, I initialized this array with some random values. Now I want to fetch this values one by one. How can I do it using for or forEachIndexed loop?

Body:
You can iterate in the array like this :

for (strings in squareData) {
    for (string in strings) {
        Your code here
    }
}

The first for iterate through the first dimension so it has string arrays and the second one through the second dimension so it has the string values


问:
How can I show the "Open with" file dialog?
Is there any simple way to open the "Open with" file dialog?</p>

答:
Using

```<code>System.Diagnostics.Process.Start(path);
</code>```

The file will be openened with the default program, if no default program is defined the open with dialog will be shown.

You can use the the function:

```<code>[DllImport("shell32.dll", SetLastError = true)]
extern public static bool
       ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);
</code>```

You have an example to use this function on: this link

Body:
Using

System.Diagnostics.Process.Start(path);

The file will be openened with the default program, if no default program is defined the open with dialog will be shown.

You can use the the function:

[DllImport("shell32.dll", SetLastError = true)]
extern public static bool
       ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);

You have an example to use this function on: this link

ContentLicense: CC BY-SA 2.5


问:
Add dynamic textbox in canvas
I want to achieve a functionality in which, if I click on the canvas, a textbox should appear. After entering the text and click save button, it should save that text on a canvas. Again if I click on canvas somewhere else, it should again add a new textbox. In short, I want to add a new text box on click of canvas and want to save the textbox value.
Give me any good reference where I can learn canvas. I am asking for good tutorial in order to achieve specified functionality.</p>

答:
You can give coordinates of canvas or id where you click. Also have a variable to set it as {0 if text box available, so have to save. 1 if text box not available so have to add text box}. Swap them and add text box or save them accordingly.

If you have a large are where you have to find clicked or not, you can add as

$("#canvasid").click(function(){
    var $this = $(this);
    if($this.data('clicked')) {
         var table = $(this).closest('sometablewhereiwanttextbox');
    if (table.find('input:text').length < 7) {
        table.append('
Name  <input type="text" id="current Name" value="" />
');
    }
});```

Alter the code as needed.

Saving to DB depends on the technology you use. If its MVC or asp.net, then use AJAX calls to pass the data to back end and save them using web method.

Title: Add dynamic textbox in canvas

Body:
You can give coordinates of canvas or id where you click. Also have a variable to set it as {0 if text box available, so have to save. 1 if text box not available so have to add text box}. Swap them and add text box or save them accordingly.

If you have a large are where you have to find clicked or not, you can add as

$("#canvasid").click(function(){
    var $this = $(this);
    if($this.data('clicked')) {
         var table = $(this).closest('sometablewhereiwanttextbox');
    if (table.find('input:text').length < 7) {
        table.append('<tr><td style="width:200px;" align="right">Name <td> <input type="text" id="current Name" value="" /> </td></tr>');
    }
});

Alter the code as needed.

Saving to DB depends on the technology you use. If its MVC or asp.net, then use AJAX calls to pass the data to back end and save them using web method.


问:
Image deduction with Pillow and Numpy
I have two images:

and

I want to export an image that just has the red "Hello" like:

So I am running a simple deduction python script:

```<code>from PIL import Image
import numpy as np

root = '/root/'
im1 = np.asarray(Image.open(root+'1.jpg'))
im2 = np.asarray(Image.open(root+'2.jpg'))

deducted_image = np.subtract(im1, im2)

im = Image.fromarray(np.uint8(deducted_image))
im.save(root+"deduction.jpg")
</code>```

But this returns:

rather than the above. What am I doing wrong? Also do I need numpy or can I do this with just the Pillow Library?

Edit:

It should also work with images like this:

which my code returns:

Confused as to why it is so pixelated around the edges!

答:
It is perhaps easier just to set the pixels you don't want in the second image to 0?

```<code>im = im2.copy()
im[im1 == im2] = 0
im = Image.fromarray(im)
</code>```

seems to work for me (obviously just with bigger artifacts because I used your uploaded JPGs)

It is also possible to do this without numpy:

```<code>from PIL import ImageChops
from PIL import Image

root = '/root/'
im1 = Image.open(root + '1.jpg')
im2 = Image.open(root + '2.jpg')

def nonzero(a):
    return 0 if a < 10 else 255

mask = Image.eval(ImageChops.difference(im1, im2), nonzero).convert('1')

im = Image.composite(im2, Image.eval(im2, lambda x: 0), mask)
</code>```

Title: Image deduction with Pillow and Numpy

Body:
I have two images:

and

I want to export an image that just has the red "Hello" like:

So I am running a simple deduction python script:

from PIL import Image
import numpy as np

root = '/root/'
im1 = np.asarray(Image.open(root+'1.jpg'))
im2 = np.asarray(Image.open(root+'2.jpg'))

deducted_image = np.subtract(im1, im2)

im = Image.fromarray(np.uint8(deducted_image))
im.save(root+"deduction.jpg")

But this returns:

rather than the above. What am I doing wrong? Also do I need numpy or can I do this with just the Pillow Library?

Edit:

It should also work with images like this:

which my code returns:

Confused as to why it is so pixelated around the edges!

Body:
It is perhaps easier just to set the pixels you don't want in the second image to 0?

im = im2.copy()
im[im1 == im2] = 0
im = Image.fromarray(im)

seems to work for me (obviously just with bigger artifacts because I used your uploaded JPGs)

It is also possible to do this without numpy:

from PIL import ImageChops
from PIL import Image

root = '/root/'
im1 = Image.open(root + '1.jpg')
im2 = Image.open(root + '2.jpg')

def nonzero(a):
    return 0 if a < 10 else 255

mask = Image.eval(ImageChops.difference(im1, im2), nonzero).convert('1')

im = Image.composite(im2, Image.eval(im2, lambda x: 0), mask)


问:
After restoring ML db, do I need to reindex the MarkLogic DB?
A database is attached to 3 forests.
The total size of the database is approx 300 GB including indexes (created lot of indexes).

I have to migrate the data to another server, To do this I am just taking the backup of the entire database and restoring it to another db in another MarkLogic instance.

My question is after restoring, is it required to Re-index the DB? if yes, is there any way to avoid Re-indexing as re-indexing is taking a lot of time (approx 15 hours)

答:
A restore does not in itself necessitate a reindex. But restoring to a database with a different configuration would be cause for a reindex. </p>

<p>You can turn reindexing on and off in the database configuration or (better) set it to throttle itself to work less aggressively. </p>

Body:
A restore does not in itself necessitate a reindex. But restoring to a database with a different configuration would be cause for a reindex.

You can turn reindexing on and off in the database configuration or (better) set it to throttle itself to work less aggressively.


问:
Instagram Media/Feed API
I am currently looking at Instagram feed integration in a web app.
The offical APIs are: Instagram Graph API and Instagram Platform API.

And then I found one endpoint like https://www.instagram.com/instagram/media/ on SO, here and here, which seems an undocumented (at least I haven't seen it on facebook/instagram document).
It's publicly accessible and you can get a lot of information about the posts including likes and comments.

So my questions are:

Is the https://www.instagram.com/{username}/media/ documented some where?

Is it widely used on the internet?

答:
This endpoint has stopped working on November 7 2017. But you can use this other endpoint to get the same results:

```<code>GET /users/user-id/media/recent
https://api.instagram.com/v1/users/{user-id}/media/recent/?access_token=ACCESS-TOKEN

Get the most recent media published by a user.
The public_content scope is required if the user is not the owner of the access_token.

REQUIREMENTS
Scope: public_content

PARAMETERS
ACCESS_TOKEN    A valid access token.
MAX_ID  Return media earlier than this max_id.
MIN_ID  Return media later than this min_id.
COUNT   Count of media to return.
</code>```

https://www.instagram.com/developer/endpoints/users/#get_users_media_recent

Title: Instagram Media/Feed API

Body:
This endpoint has stopped working on November 7 2017. But you can use this other endpoint to get the same results:

GET /users/user-id/media/recent
https://api.instagram.com/v1/users/{user-id}/media/recent/?access_token=ACCESS-TOKEN

Get the most recent media published by a user.
The public_content scope is required if the user is not the owner of the access_token.

REQUIREMENTS
Scope: public_content

PARAMETERS
ACCESS_TOKEN    A valid access token.
MAX_ID  Return media earlier than this max_id.
MIN_ID  Return media later than this min_id.
COUNT   Count of media to return.

https://www.instagram.com/developer/endpoints/users/#get_users_media_recent


问:
What is the best way to authenticate Express api?
I use Angular 4 as a front end and MongoDB for database. I used Express to create API. Now I need to authenticate every API except login and register to prevent unauthorized users to hit API.

I am new to this kind of authentication and I found lot of methods available such as passport.js, jwt etc. I am very confused to choose the best method for authenticating. So please give some inputs to choose the best.

Note: The application is not related to financial projects. So it doesn't require high level of safety.

答:
You could try to implement Json Web Tokens

For NodeJS, there is a npm Package available called nJwt. You can install it with npm.

Usage example (shortened):

```<code>var njwt = require('njwt');
if (loginSuccessful) {
    var payload = {
                        iss: 'your_domain_name',
                        iat: Math.round((Date.now() / 1000)),
                        // Set expiration date to now +7200 seconds
                        exp: Math.round((Date.now() / 1000)) + 7200,
                        username: username,
                        ip: ip
                }
   var token = njwt.create(payload,your_super_secret_key,'HS512').compact());
} else {
// Login not successful, don't give key
}
</code>```

You can send the token to the user, and then they use it with every request (for example).

With this configuration the token will be valid for 7200 seconds, or 2 hours.

Body:
You could try to implement Json Web Tokens

For NodeJS, there is a npm Package available called nJwt. You can install it with npm.

Usage example (shortened):

var njwt = require('njwt');
if (loginSuccessful) {
    var payload = {
                        iss: 'your_domain_name',
                        iat: Math.round((Date.now() / 1000)),
                        // Set expiration date to now +7200 seconds
                        exp: Math.round((Date.now() / 1000)) + 7200,
                        username: username,
                        ip: ip
                }
   var token = njwt.create(payload,your_super_secret_key,'HS512').compact());
} else {
// Login not successful, don't give key
}

You can send the token to the user, and then they use it with every request (for example).

With this configuration the token will be valid for 7200 seconds, or 2 hours.


问:
How to read this from file and get each value alone
I have this text file and I need to extract it to a Java program to determine array sizes and its values I can read each line alone but I can't get the value for lines that contains many numbers. Plus, how to count element in the third line.( 0 2 ) </p>

```<code>4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3
</code>```

<p>this code that I'm using: </p>

```<code> List<Integer> list = new ArrayList<Integer>();
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
        BufferedReader reader = null;
         List<Double> ints = new ArrayList<Double>();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (text.length() == 1) {
                    list.add(Integer.parseInt(text));
                } else {

                    String[] strs = text.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        ints.add(Double.parseDouble(strs[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }

//print out the list
        System.out.println(list);

        System.out.println(ints);
</code>```

答:
It looks like you are using doubles mixed with int so Integer.parseInt() will not work.

What you could do is to split the line, separated by a space into an array, and put each of those elements into list. Note that this will print 0 as 0.0.

```<code>while ((text = reader.readLine()) != null) {
      String[] numbers = text.split(" ");
      for (String number : numbers) {
           list.add(Double.valueOf(number));
      }
}
</code>```

Also, did you just copy this answer for your code?

Body:
I have this text file and I need to extract it to a Java program to determine array sizes and its values I can read each line alone but I can't get the value for lines that contains many numbers. Plus, how to count element in the third line.( 0 2 )

4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3

this code that I'm using:

 List<Integer> list = new ArrayList<Integer>();
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
        BufferedReader reader = null;
         List<Double> ints = new ArrayList<Double>();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (text.length() == 1) {
                    list.add(Integer.parseInt(text));
                } else {

                    String[] strs = text.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        ints.add(Double.parseDouble(strs[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }

//print out the list
        System.out.println(list);

        System.out.println(ints);

Body:
It looks like you are using doubles mixed with int so Integer.parseInt() will not work.

What you could do is to split the line, separated by a space into an array, and put each of those elements into list. Note that this will print 0 as 0.0.

while ((text = reader.readLine()) != null) {
      String[] numbers = text.split(" ");
      for (String number : numbers) {
           list.add(Double.valueOf(number));
      }
}

Also, did you just copy this answer for your code?


问:
CruiseControl.NET: Building a project in Debug and Release configurations
I am using CruiseControl.NET to build a C# project. I am using an msbuild task to achieve this. I want to build the project in both Debug and Release mode irrespective of whether either mode fails. But If I put these as two msbuild tasks in the 'tasks' section of the project and if the first task fails, the second is not executed.

I could define them as two projects, but I want the Label to be synchronized across both the projects. Is there a way to do this?

One solution I have is make the 'Release' config project to trigger a build whenever the 'Debug' config project is built. But in that case, If someone force builds the 'Debug' config project then, the labels will get out of sync.

答:
Use multiple  tasks for the project.

Note: See CC.NET preprocessor if you want to reduce tags duplication.


问:
C program: pass function as parameter to another function to create thread
I would need some help. I been doing it for hours and is not able to get it to work. Generally, I have a function which access a kernel Driver and I would like to pass that function as a parameter to another function that include some pthread code. I researched and found out that I may need a function pointer.

Here is the function which I want to pass as a parameter.

```<code>static void kernelTest(char Send[BUFFER_LENGTH])
{
    int fd = open("/dev/kernelTest", O_RDWR);
}
</code>```

Here is the function which I want to pass in:

```<code>static void createKThread(void (*f)(char *))
{
  pthread_t t1;
  int ret;
  ret =  pthread_create(&t1, NULL, (*f)(char), NULL);
  pthread_join(t1, NULL);
}
</code>```

I attempted the function pointer but it is giving me error.

```<code> error: expected expression before ‘char’
</code>```

I greatly appreciate any help rendered. Thank You!

答:
(*f)(char) is invalid syntax.  It looks like you're attempting to call the function f and passing char as a parameter, which you can't do.

Since you're not actually calling f, just pass it to pthread_create directly:

```<code>ret =  pthread_create(&t1, NULL, f, NULL);
</code>```

There's still a problem with this, however.  The third parameter to pthread_create is expected to be of type void *(*)(void *), i.e. a pointer to a function that has a void * parameter and returns a void *.  Your function has type void (*)(char *), so the parameters are incompatible.

You need to either change the signature of kernelTest to match what pthread_create expects:

```<code>static void *kernelTest(void *param)
{
    char *send = param;
    int fd = open("/dev/kernelTest", O_RDWR);
    return NULL;
}
</code>```

Or you need to create a wrapper function which matches pthread_create:

```<code>static void *kernelTest_wrapper(void *param)
{
    char *send = param;
    kernelTest(send);
    return NULL;
}
</code>```

Body:
I would need some help. I been doing it for hours and is not able to get it to work. Generally, I have a function which access a kernel Driver and I would like to pass that function as a parameter to another function that include some pthread code. I researched and found out that I may need a function pointer.

Here is the function which I want to pass as a parameter.

static void kernelTest(char Send[BUFFER_LENGTH])
{
    int fd = open("/dev/kernelTest", O_RDWR);
}

Here is the function which I want to pass in:

static void createKThread(void (*f)(char *))
{
  pthread_t t1;
  int ret;
  ret =  pthread_create(&t1, NULL, (*f)(char), NULL);
  pthread_join(t1, NULL);
}

I attempted the function pointer but it is giving me error.

 error: expected expression before ‘char’

I greatly appreciate any help rendered. Thank You!

Body:
(*f)(char) is invalid syntax.  It looks like you're attempting to call the function f and passing char as a parameter, which you can't do.

Since you're not actually calling f, just pass it to pthread_create directly:

ret =  pthread_create(&t1, NULL, f, NULL);

There's still a problem with this, however.  The third parameter to pthread_create is expected to be of type void *(*)(void *), i.e. a pointer to a function that has a void * parameter and returns a void *.  Your function has type void (*)(char *), so the parameters are incompatible.

You need to either change the signature of kernelTest to match what pthread_create expects:

static void *kernelTest(void *param)
{
    char *send = param;
    int fd = open("/dev/kernelTest", O_RDWR);
    return NULL;
}

Or you need to create a wrapper function which matches pthread_create:

static void *kernelTest_wrapper(void *param)
{
    char *send = param;
    kernelTest(send);
    return NULL;
}


问:
Stripe php : How to managed custom amount based plans?
How to managed custom amount based plans code in stripe payment?

Plan id : basic-{interval}-{amount}

1) Check plan exits or not ?

if : exits then assign to subscriber

not - Create a new plan.

```<code>if(!empty($recurring_duration)){
                                try {
                                    $plan = \Stripe\Plan::retrieve($planname);
                                } catch (Error\InvalidRequest $exception) {
                                    $plan = \Stripe\Plan::create(array(
                                        "name" => "Basic Plan",
                                        "id" => $planname,
                                        "interval" => "$recurring_duration",
                                        "currency" => strtolower($currency),
                                        "amount" => $amount,
                                    ));
                                }

                                $plan = \Stripe\Plan::create(array(
                                        "name" => "Basic Plan",
                                        "id" => $planname,
                                        "interval" => "$recurring_duration",
                                        "currency" => strtolower($currency),
                                        "amount" => $amount,
                                ));
                            }

$customer = \Stripe\Customer::create(array(
                                'email'     => $email,
                                'source'    => $token
                            ));

                            if(!empty($recurring_duration)){

                                $charge = \Stripe\Subscription::create(array(
                                    "customer" => $customer->id,
                                    "items" => array(
                                      array(
                                        "plan" => $planname,
                                      ),
                                    ),
                                ));

                            }else{

                                $charge = \Stripe\Charge::create(array(
                                                'customer'    => $customer->id,
                                                'amount'      => $amount,
                                                'currency'    => strtolower($currency),
                                                'description' => '',
                                        )
                                );

                            }

                            $val = BSP_add_form_data($charge);
</code>```

答:
First Need to get all plans & check with your values.</p>

```<code><?php
$recurring_duration  = $_POST['recurring_duration'];
$planname = "plan value";
$last_customer = NULL;
while (true) {
    $plan_list = \Stripe\Plan::all(array("limit" => 100, "starting_after" => $last_plan));
    foreach ($plan_list->autoPagingIterator() as $plan) {
        if ($plan->id == $planname) {
            $planlookfor = $plan;
            break 2;
        }
    }
    if (!$plan->has_more) {
        break;
    }
    $last_plan = end($plan_list->data);
}

if(!empty($recurring_duration)){
    if(isset($planlookfor) && $planlookfor->id==$planname){

    }else{
        $plan = \Stripe\Plan::create(array(
            "name" => 'Basic Plan'.' '.$recurring_duration_text.' '.$amount/100,
            "id" => $planname,
            "interval" => "$recurring_duration",
            "currency" => strtolower($currency),
            "amount" => $amount,
        ));
    }
}
</code>```

Body:
How to managed custom amount based plans code in stripe payment?

Plan id : basic-{interval}-{amount}

1) Check plan exits or not ?

if : exits then assign to subscriber

not - Create a new plan.

if(!empty($recurring_duration)){
                                try {
                                    $plan = \Stripe\Plan::retrieve($planname);
                                } catch (Error\InvalidRequest $exception) {
                                    $plan = \Stripe\Plan::create(array(
                                        "name" => "Basic Plan",
                                        "id" => $planname,
                                        "interval" => "$recurring_duration",
                                        "currency" => strtolower($currency),
                                        "amount" => $amount,
                                    ));
                                }

                                $plan = \Stripe\Plan::create(array(
                                        "name" => "Basic Plan",
                                        "id" => $planname,
                                        "interval" => "$recurring_duration",
                                        "currency" => strtolower($currency),
                                        "amount" => $amount,
                                ));
                            }

$customer = \Stripe\Customer::create(array(
                                'email'     => $email,
                                'source'    => $token
                            ));

                            if(!empty($recurring_duration)){

                                $charge = \Stripe\Subscription::create(array(
                                    "customer" => $customer->id,
                                    "items" => array(
                                      array(
                                        "plan" => $planname,
                                      ),
                                    ),
                                ));

                            }else{

                                $charge = \Stripe\Charge::create(array(
                                                'customer'    => $customer->id,
                                                'amount'      => $amount,
                                                'currency'    => strtolower($currency),
                                                'description' => '',
                                        )
                                );

                            }

                            $val = BSP_add_form_data($charge);

Body:
First Need to get all plans & check with your values.

<?php
$recurring_duration  = $_POST['recurring_duration'];
$planname = "plan value";
$last_customer = NULL;
while (true) {
    $plan_list = \Stripe\Plan::all(array("limit" => 100, "starting_after" => $last_plan));
    foreach ($plan_list->autoPagingIterator() as $plan) {
        if ($plan->id == $planname) {
            $planlookfor = $plan;
            break 2;
        }
    }
    if (!$plan->has_more) {
        break;
    }
    $last_plan = end($plan_list->data);
}

if(!empty($recurring_duration)){
    if(isset($planlookfor) && $planlookfor->id==$planname){

    }else{
        $plan = \Stripe\Plan::create(array(
            "name" => 'Basic Plan'.' '.$recurring_duration_text.' '.$amount/100,
            "id" => $planname,
            "interval" => "$recurring_duration",
            "currency" => strtolower($currency),
            "amount" => $amount,
        ));
    }
}


问:
Fitting user defined function with MPFIT in IDL
I am trying to fit a decaying exponential function of the form: A1 - A1exp(-x/A2) to a set of (x,y) values with error bars on y values. I am using the IDL MPFIT function to perform this non linear fit.

```<code>function gfunct, xsig, A
return, A[0] - A[0]*exp(-xsig/A[1])
end

pro makeit

xsig=[0d0,4d0,12d0,48d0]
ysig=[0d0,19d0,30d0,36d0]
err=dblarr(1,4)
err[0]=0.000001d0
err[1]=0.5d0*0.4219d0*19d0
err[2]=0.5d0*0.2154d0*30d0
err[3]=0.5d0*0.1279d0*36d0

A = [39d0,10.96d0]
result = MPFITFUN('gfunct', xsig, ysig, err, start)
end
</code>```

But this code gives me an error:

```<code> MPFITFUN: ERROR: must pass parameters in P or PARINFO
</code>```

Can someone help me identify the correct syntax for the function block? I tried using svdfit but it cannot be used for a function like this, with A[1] in the exponential.
Thanks!

答:
The calling sequence for MPFITFUN is

parms = MPFITFUN(MYFUNCT, X, Y, ERR, start_params, ...);

This means you should call it like this:

```<code>result = MPFITFUN('gfunct', xsig, ysig, err, A)
</code>```

Since "A" contains your initial guesses.

Body:
I am trying to fit a decaying exponential function of the form: A1 - A1exp(-x/A2) to a set of (x,y) values with error bars on y values. I am using the IDL MPFIT function to perform this non linear fit.

function gfunct, xsig, A
return, A[0] - A[0]*exp(-xsig/A[1])
end

pro makeit

xsig=[0d0,4d0,12d0,48d0]
ysig=[0d0,19d0,30d0,36d0]
err=dblarr(1,4)
err[0]=0.000001d0
err[1]=0.5d0*0.4219d0*19d0
err[2]=0.5d0*0.2154d0*30d0
err[3]=0.5d0*0.1279d0*36d0

A = [39d0,10.96d0]
result = MPFITFUN('gfunct', xsig, ysig, err, start)
end

But this code gives me an error:

 MPFITFUN: ERROR: must pass parameters in P or PARINFO

Can someone help me identify the correct syntax for the function block? I tried using svdfit but it cannot be used for a function like this, with A[1] in the exponential.
Thanks!

Body:
The calling sequence for MPFITFUN is

parms = MPFITFUN(MYFUNCT, X, Y, ERR, start_params, ...);

This means you should call it like this:

result = MPFITFUN('gfunct', xsig, ysig, err, A)

Since "A" contains your initial guesses.


问:
SDWebImage and setting custom HTTP headers?
I´ve just changed my code for caching images away from EGOImageCache to SDWebView. Unfortunately i don´t know how to set custom HTTP headers as i have to send authentification to be able to fetch images. It was easy done with EGOImageCache as i´ve extended the NSURLRequest at the appropriate place. But i don´t know how to do that with the SDWebView.framework. I see the headers and i´ve found methods in SDWebImageDownloader.h containing

```<code>    /**
 * Set a value for a HTTP header to be appended to each download HTTP request.
 *
 * @param value The value for the header field. Use `nil` value to remove the header.
 * @param field The name of the header field to set.
 */
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

/**
 * Returns the value of the specified HTTP header field.
 *
 * @return The value associated with the header field field, or `nil` if there is no corresponding header field.
 */
- (NSString *)valueForHTTPHeaderField:(NSString *)field;
</code>```

It seems that the lib does support HTTP headers. But as i use UIImageView+WebCache.h i can´t see there an option for setting the headers. In my code i call

```<code>[self.imageView setImageWithURL:[NSURL URLWithString:themeImageURL] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
</code>```

Can anybody tell me how to set HTTP headers?

答:
Swift Version

```<code>let imageDownloader = SDWebImageDownloader.shared()
imageDownloader.setValue("Username", forHTTPHeaderField: "X-Oauth-Username")
</code>```

Body:
I´ve just changed my code for caching images away from EGOImageCache to SDWebView. Unfortunately i don´t know how to set custom HTTP headers as i have to send authentification to be able to fetch images. It was easy done with EGOImageCache as i´ve extended the NSURLRequest at the appropriate place. But i don´t know how to do that with the SDWebView.framework. I see the headers and i´ve found methods in SDWebImageDownloader.h containing

    /**
 * Set a value for a HTTP header to be appended to each download HTTP request.
 *
 * @param value The value for the header field. Use `nil` value to remove the header.
 * @param field The name of the header field to set.
 */
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

/**
 * Returns the value of the specified HTTP header field.
 *
 * @return The value associated with the header field field, or `nil` if there is no corresponding header field.
 */
- (NSString *)valueForHTTPHeaderField:(NSString *)field;

It seems that the lib does support HTTP headers. But as i use UIImageView+WebCache.h i can´t see there an option for setting the headers. In my code i call

[self.imageView setImageWithURL:[NSURL URLWithString:themeImageURL] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Can anybody tell me how to set HTTP headers?

Body:
Swift Version

let imageDownloader = SDWebImageDownloader.shared()
imageDownloader.setValue("Username", forHTTPHeaderField: "X-Oauth-Username")


问:
How to get rid of unwanted tooltips in Excel 2013 addin ribbon
I have written an Excel VSTO Addin with C# that is compatible with Excel 2013 as well as Excel 2016/365.
In Excel 2013, I see a tooltip window for every ribbon button, that contains my addin's name and a link to more information, which simply opens a help topic about addins.
I don't want either. If I add a "ScreenTip" or a "SuperTip" to my ribbon buttons, they will be added on top of this unwanted tooltip, but they don't replace it.
Excel 2016 does not show such tooltips.
How can I get rid of them? I only want my own ScreenTips and SuperTips

Since I am using the VS Ribbon designer, I have no, and don't want to have, access to the underlying ribbon XML.

答: You can't get rid of them, that part is controlled by Microsoft. Assumedly it was part of Microsoft's goal of helping to inform users that a control is not a Standard Office control, so that when it breaks, they don't blame MS for it, but instead recognize the identifier listed there and then seek support from whoever made the Add-In.</p>


问:
Plot a density function above a histogram
In Python, I have estimated the parameters for the density of a model of my distribution and I would like to plot the density function above the histogram of the distribution. In R it is similar to using the option prop=TRUE.

```<code>import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# initialization of the list "data"
# estimation of the parameter, in my case, mean and variance of a normal distribution

plt.hist(data, bins="auto") # data is the list of data
# here I would like to draw the density above the histogram
plt.show()
</code>```

I guess the trickiest part is to make it fit.

Edit: I have tried this according to the first answer:

```<code>mean = np.mean(logdata)
var  = np.var(logdata)
std  = np.sqrt(var) # standard deviation, used by numpy as a replacement of the variance
plt.hist(logdata, bins="auto", alpha=0.5, label="données empiriques")
x = np.linspace(min(logdata), max(logdata), 100)
plt.plot(x, mlab.normpdf(x, mean, std))
plt.xlabel("log(taille des fichiers)")
plt.ylabel("nombre de fichiers")
plt.legend(loc='upper right')
plt.grid(True)
plt.show()
</code>```

But it doesn't fit the graph, here is how it looks:

** Edit 2 ** Works with the option normed=True in the histogram function.

答:
All what you are looking for, already are in seaborn.

You just have to use distplot

```<code>import seaborn as sns
import numpy as np

data = np.random.normal(5, 2, size=1000)
sns.distplot(data)
</code>```

Body:
In Python, I have estimated the parameters for the density of a model of my distribution and I would like to plot the density function above the histogram of the distribution. In R it is similar to using the option prop=TRUE.

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# initialization of the list "data"
# estimation of the parameter, in my case, mean and variance of a normal distribution

plt.hist(data, bins="auto") # data is the list of data
# here I would like to draw the density above the histogram
plt.show()

I guess the trickiest part is to make it fit.

Edit: I have tried this according to the first answer:

mean = np.mean(logdata)
var  = np.var(logdata)
std  = np.sqrt(var) # standard deviation, used by numpy as a replacement of the variance
plt.hist(logdata, bins="auto", alpha=0.5, label="données empiriques")
x = np.linspace(min(logdata), max(logdata), 100)
plt.plot(x, mlab.normpdf(x, mean, std))
plt.xlabel("log(taille des fichiers)")
plt.ylabel("nombre de fichiers")
plt.legend(loc='upper right')
plt.grid(True)
plt.show()

But it doesn't fit the graph, here is how it looks:

** Edit 2 ** Works with the option normed=True in the histogram function.

Body:
All what you are looking for, already are in seaborn.

You just have to use distplot

import seaborn as sns
import numpy as np

data = np.random.normal(5, 2, size=1000)
sns.distplot(data)

ContentLicense: CC BY-SA 4.0


问:
Can I define a const static instance of a class in the class header file
Is it possible to declare and define a const static instance of a class in the class header file.

I want to do something like this (from this similar question):

```<code>class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE;

private:
    std::string mPlaceName;
};

const PlaceID PlaceID::OUTSIDE = PlaceID("");
</code>```

This would work if the definition of PlaceID::OUTSIDE was in a source file, but if it's in a header file that is include in multiple location it causes an link error because PlaceID::OUTSIDE is then defined multiple times.

I'd like to define it in the header file for two reasons. First, this will be part of a library and I'd like the library to be header file only.

Second and this is the most important one I want the compiler to be allowed to "inline" the uses of this instance. The class in question (not the one used as an example here) is a wrapper around a primitive type with all methods inlined in order to offer the same performance as the primitive type would. If I place the definition of this instance in a source file, the compiler will not know it's value at compilation time and won't be able to apply some optimisations.

Thanks.

答:
In C++17, variables can be marked as inline:

```<code>class PlaceID
{
    inline const static PlaceID OUTSIDE{""};
    // ...
};
</code>```

Before C++14, you can use a function instead:

```<code>class PlaceID
{
    static PlaceID OUTSIDE() { return PlaceID{""}; }
    // ...
};
</code>```

...or...

```<code>class PlaceID
{
    static PlaceID OUTSIDE()
    {
        static PlaceID result{""};
        return result;
    }

    // ...
};
</code>```

...depending on whether or not you want a single PlaceID instance.

Alternatively, you can templatize PlaceID over a dummy parameter in order to inline the definition of OUTSIDE in an header:

```<code>template <typename>
struct PlaceID_
{
    inline PlaceID_(const char*) { }
    const static PlaceID_ OUTSIDE;
};

template <typename T>
const PlaceID_<T> PlaceID_<T>::OUTSIDE{""};

using PlaceID = PlaceID_<void>;
</code>```

This works because templates are implicitly inline. See How do inline variables work? for more details.

live example on wandbox.org

Also consider marking PlaceID::PlaceID(const char*) as constexpr if possible so that OUTSIDE can be marked constexpr as well. Obviously this will not work if you decide to use std::string.

Body:
Is it possible to declare and define a const static instance of a class in the class header file.

I want to do something like this (from this similar question):

class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE;

private:
    std::string mPlaceName;
};

const PlaceID PlaceID::OUTSIDE = PlaceID("");

This would work if the definition of PlaceID::OUTSIDE was in a source file, but if it's in a header file that is include in multiple location it causes an link error because PlaceID::OUTSIDE is then defined multiple times.

I'd like to define it in the header file for two reasons. First, this will be part of a library and I'd like the library to be header file only.

Second and this is the most important one I want the compiler to be allowed to "inline" the uses of this instance. The class in question (not the one used as an example here) is a wrapper around a primitive type with all methods inlined in order to offer the same performance as the primitive type would. If I place the definition of this instance in a source file, the compiler will not know it's value at compilation time and won't be able to apply some optimisations.

Thanks.

Body:
In C++17, variables can be marked as inline:

class PlaceID
{
    inline const static PlaceID OUTSIDE{""};
    // ...
};

Before C++14, you can use a function instead:

class PlaceID
{
    static PlaceID OUTSIDE() { return PlaceID{""}; }
    // ...
};

...or...

class PlaceID
{
    static PlaceID OUTSIDE()
    {
        static PlaceID result{""};
        return result;
    }

    // ...
};

...depending on whether or not you want a single PlaceID instance.

Alternatively, you can templatize PlaceID over a dummy parameter in order to inline the definition of OUTSIDE in an header:

template <typename>
struct PlaceID_
{
    inline PlaceID_(const char*) { }
    const static PlaceID_ OUTSIDE;
};

template <typename T>
const PlaceID_<T> PlaceID_<T>::OUTSIDE{""};

using PlaceID = PlaceID_<void>;

This works because templates are implicitly inline. See How do inline variables work? for more details.

live example on wandbox.org

Also consider marking PlaceID::PlaceID(const char*) as constexpr if possible so that OUTSIDE can be marked constexpr as well. Obviously this will not work if you decide to use std::string.