问:
time.sleep blocks pressing tkinter.Button
I am trying to implement an app to show image for 6s and then jump to another page with radio buttons to let them rate their own feeling about the images (give 15s for rating) and then show the next image. However, for counting down 15s, I used time.sleep() function, which make the program very slow for pressing radiobuttons (but my clicking, the button can still be pressed). I am wondering whether there is a way that the count down will not influence the program but just let the program jump to the next page when time up. Here is my code :</p>

```<code>class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry('1800x970+15+5')
        self.title('Emotion Test')
        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, Show_image, Rate_e, EndPage):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")
    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
        frame.execute()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text=instructions, width=1500, height=700, font=TITLE_FONT)
        label.pack(side="top")
        label.place(x=100, y=40, width=1500, height=700)
        button1 = tk.Button(self, text="Start", height = 5, width = 10,
                            command=lambda: controller.show_frame("Show_image"))
        button1.pack(side="bottom")

    def execute(self):
        current = -1

class EndPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text=instructions, width=1500, height=700,
        font=TITLE_FONT)
        label.pack(side="top")
        label.place(x=100, y=40, width=1500, height=700)

    def execute(self):
        current = -1

class Show_image(tk.Frame):

    def __init__(self, parent, controller):
        global seconds
        tk.Frame.__init__(self, parent)
        self.controller = controller
        global lbPic
        global timer1
        lbPic = tk.Label(self, text='Image System', width=1200, height=900)
        lbPic.place(x=20, y=50, width=1200, height=900)
        lbPic.pack(side="top", fill="both", expand=True)
        timer1 = tk.Label(self, text='timer', width=50, height=10)
        timer1.place(x=1325, y=2, width=50, height=10)
        timer1.pack(side="bottom", fill="both", expand=True)
    def execute(self):
        if (self.changePic(1)):
           for k in range(seconds, 0, -1):
               timer1["text"] = "Time left : " + str(k) + " s"
               self.update()
               time.sleep(1)
           self.controller.show_frame("Rate_e")
        else:
           self.controller.show_frame("EndPage")

    def changePic(self, flag):
        global current

        new = current + flag
        if new<0:
           #tkMessageBox.showerror('', 'last picture')
           return 0
        elif new>=len(pics):
             #tkMessageBox.showerror('', 'last picture')
             return 0
        else:
             #get the next picture
             pic = pics[new]
             im = Image.open(pic)
             w, h = im.size
             if w>1200:
                h = int(h*1200/w)
                w = 1200
             if h>800:
                w = int(w*800/h)
                h = 800
             im = im.resize((w,h))
             im1 = ImageTk.PhotoImage(im)
             lbPic['image'] = im1
             lbPic.image = im1
             current = new
             return 1

class Rate_e(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        global wait
        self.controller = controller
        global lbrate1
        global lbrate2
        global lbrate3
        global timer2
        lbrate1 = tk.Label(self, text='Pleasure', width=1400, height=260)
        lbrate1.place(x=50, y=10, width=1400, height=260)
        lbrate1.pack(side="top", fill="both", expand=True)
        lbrate2 = tk.Label(self, text='Excited', width=1400, height=260)
        lbrate2.place(x=50, y=230, width=1400, height=260)
        lbrate2.pack(side="top", fill="both", expand=True)
        lbrate3 = tk.Label(self, text='Controlled', width=1400, height=260)
        lbrate3.place(x=50, y=650, width=1400, height=260)
        lbrate3.pack(side="top", fill="both", expand=True)
        timer2 = tk.Label(self, text='timer', width=50, height=10)
        timer2.place(x=800, y=850, width=50, height=10)
        timer2.pack(side="bottom", fill="both", expand=True)

        MODES = [
            ("1", 1),
            ("2", 2),
            ("3", 3),
            ("4", 4),
            ("5", 5),
            ("6", 6),
            ("7", 7),
            ("8", 8),
            ("9", 9)
        ]
        global v1
        v1 = tk.StringVar()
        v1.set("score1") # initialize
        xaxis = 0
        for text, mode in MODES:
            b1 = tk.Radiobutton(self, text=text,
                        variable=v1, value=mode)
            b1.config(indicatoron=False,width=10,height=2)
            b1.place(x=140 + xaxis*127, y=240 , width=100, height=30)
            #b.pack(side="left")
            xaxis = xaxis + 1
        global v2
        v2 = tk.StringVar()
        v2.set("score2") # initialize
        xaxis = 0
        for text, mode in MODES:
            b2 = tk.Radiobutton(self, text=text,
                        variable=v2, value=mode)
            b2.config(indicatoron=False,width=10,height=2)
            b2.place(x=140 + xaxis*128, y=510 , width=100, height=30)
            #b.pack(side="left")
            xaxis = xaxis + 1
        global v3
        v3 = tk.StringVar()
        v3.set("score3") # initialize
        xaxis = 0
        for text, mode in MODES:
            b3 = tk.Radiobutton(self, text=text,
                        variable=v3, value=mode)
            b3.config(indicatoron=False,width=10,height=2)
            b3.place(x=140 + xaxis*125, y=800 , width=100, height=30)
            #b.pack(side="left")
            xaxis = xaxis + 1

    def execute(self):
        for k in range(wait, 0, -1):
            timer2["text"] = "Time left : " + str(k) + " s"
            self.update()
            time.sleep(1)
        Pleasure = v1.get()
        Excited = v2.get()
        Control = v3.get()
        print(Pleasure)
        print(Excited)
        print(Control)
        self.controller.show_frame("Show_image")

if __name__ == "__main__":
    suffix = ('.jpg', '.bmp', '.png')
    pics = [image_path + p for p in os.listdir(image_path) if p.endswith(suffix)]
    seconds = 2
    wait = 6
    current = -1
    app = SampleApp()
    app.mainloop()
</code>```

答:
Using time.sleep() in a tkinter program will make it unresponsive since it keeps the mainloop() from executing and able to respond to events.

To void that use the universal widget method after().

So, in your case use:

```<code>self.after(1000)  # 1000 ms = 1 sec
</code>```

instead of

```<code>time.sleep(1)
</code>```

Here's some documentation I found about it.

Body:
I am trying to implement an app to show image for 6s and then jump to another page with radio buttons to let them rate their own feeling about the images (give 15s for rating) and then show the next image. However, for counting down 15s, I used time.sleep() function, which make the program very slow for pressing radiobuttons (but my clicking, the button can still be pressed). I am wondering whether there is a way that the count down will not influence the program but just let the program jump to the next page when time up. Here is my code :

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry('1800x970+15+5')
        self.title('Emotion Test')
        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, Show_image, Rate_e, EndPage):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")
    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
        frame.execute()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text=instructions, width=1500, height=700, font=TITLE_FONT)
        label.pack(side="top")
        label.place(x=100, y=40, width=1500, height=700)
        button1 = tk.Button(self, text="Start", height = 5, width = 10,
                            command=lambda: controller.show_frame("Show_image"))
        button1.pack(side="bottom")

    def execute(self):
        current = -1

class EndPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text=instructions, width=1500, height=700,
        font=TITLE_FONT)
        label.pack(side="top")
        label.place(x=100, y=40, width=1500, height=700)

    def execute(self):
        current = -1

class Show_image(tk.Frame):

    def __init__(self, parent, controller):
        global seconds
        tk.Frame.__init__(self, parent)
        self.controller = controller
        global lbPic
        global timer1
        lbPic = tk.Label(self, text='Image System', width=1200, height=900)
        lbPic.place(x=20, y=50, width=1200, height=900)
        lbPic.pack(side="top", fill="both", expand=True)
        timer1 = tk.Label(self, text='timer', width=50, height=10)
        timer1.place(x=1325, y=2, width=50, height=10)
        timer1.pack(side="bottom", fill="both", expand=True)
    def execute(self):
        if (self.changePic(1)):
           for k in range(seconds, 0, -1):
               timer1["text"] = "Time left : " + str(k) + " s"
               self.update()
               time.sleep(1)
           self.controller.show_frame("Rate_e")
        else:
           self.controller.show_frame("EndPage")

    def changePic(self, flag):
        global current

        new = current + flag
        if new<0:
           #tkMessageBox.showerror('', 'last picture')
           return 0
        elif new>=len(pics):
             #tkMessageBox.showerror('', 'last picture')
             return 0
        else:
             #get the next picture
             pic = pics[new]
             im = Image.open(pic)
             w, h = im.size
             if w>1200:
                h = int(h*1200/w)
                w = 1200
             if h>800:
                w = int(w*800/h)
                h = 800
             im = im.resize((w,h))
             im1 = ImageTk.PhotoImage(im)
             lbPic['image'] = im1
             lbPic.image = im1
             current = new
             return 1

class Rate_e(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        global wait
        self.controller = controller
        global lbrate1
        global lbrate2
        global lbrate3
        global timer2
        lbrate1 = tk.Label(self, text='Pleasure', width=1400, height=260)
        lbrate1.place(x=50, y=10, width=1400, height=260)
        lbrate1.pack(side="top", fill="both", expand=True)
        lbrate2 = tk.Label(self, text='Excited', width=1400, height=260)
        lbrate2.place(x=50, y=230, width=1400, height=260)
        lbrate2.pack(side="top", fill="both", expand=True)
        lbrate3 = tk.Label(self, text='Controlled', width=1400, height=260)
        lbrate3.place(x=50, y=650, width=1400, height=260)
        lbrate3.pack(side="top", fill="both", expand=True)
        timer2 = tk.Label(self, text='timer', width=50, height=10)
        timer2.place(x=800, y=850, width=50, height=10)
        timer2.pack(side="bottom", fill="both", expand=True)

        MODES = [
            ("1", 1),
            ("2", 2),
            ("3", 3),
            ("4", 4),
            ("5", 5),
            ("6", 6),
            ("7", 7),
            ("8", 8),
            ("9", 9)
        ]
        global v1
        v1 = tk.StringVar()
        v1.set("score1") # initialize
        xaxis = 0
        for text, mode in MODES:
            b1 = tk.Radiobutton(self, text=text,
                        variable=v1, value=mode)
            b1.config(indicatoron=False,width=10,height=2)
            b1.place(x=140 + xaxis*127, y=240 , width=100, height=30)
            #b.pack(side="left")
            xaxis = xaxis + 1
        global v2
        v2 = tk.StringVar()
        v2.set("score2") # initialize
        xaxis = 0
        for text, mode in MODES:
            b2 = tk.Radiobutton(self, text=text,
                        variable=v2, value=mode)
            b2.config(indicatoron=False,width=10,height=2)
            b2.place(x=140 + xaxis*128, y=510 , width=100, height=30)
            #b.pack(side="left")
            xaxis = xaxis + 1
        global v3
        v3 = tk.StringVar()
        v3.set("score3") # initialize
        xaxis = 0
        for text, mode in MODES:
            b3 = tk.Radiobutton(self, text=text,
                        variable=v3, value=mode)
            b3.config(indicatoron=False,width=10,height=2)
            b3.place(x=140 + xaxis*125, y=800 , width=100, height=30)
            #b.pack(side="left")
            xaxis = xaxis + 1

    def execute(self):
        for k in range(wait, 0, -1):
            timer2["text"] = "Time left : " + str(k) + " s"
            self.update()
            time.sleep(1)
        Pleasure = v1.get()
        Excited = v2.get()
        Control = v3.get()
        print(Pleasure)
        print(Excited)
        print(Control)
        self.controller.show_frame("Show_image")

if __name__ == "__main__":
    suffix = ('.jpg', '.bmp', '.png')
    pics = [image_path + p for p in os.listdir(image_path) if p.endswith(suffix)]
    seconds = 2
    wait = 6
    current = -1
    app = SampleApp()
    app.mainloop()

Body:
Using time.sleep() in a tkinter program will make it unresponsive since it keeps the mainloop() from executing and able to respond to events.

To void that use the universal widget method after().

So, in your case use:

self.after(1000)  # 1000 ms = 1 sec

instead of

time.sleep(1)

Here's some documentation I found about it.


来源: stackexchange

问:
Are there no built in C# GUI Layouts?
I'm used to the GUI frameworks in Java as well as the QT GUI framework, and I'm used to the various layout managers. It doesn't seem that C# has any layout managers built in, or am I missing something?

2 Year Later Edit

I just want to point out to any readers of this question that in hind-sight, my question was misplaced. With proper anchoring and docking of child controls, having a need for the layout managers of Java and QT4 is nearly non-existent.

答:
chibacity is right, WPF is loaded with layout managers, all of them are very good.

However if you're going down the WinForms route, you're stuck with TableLayoutPanel, FlowLayoutPanel and SplitContainer. As well as the usual manual Panel and GroupBox controls.

ContentLicense: CC BY-SA 3.0

Title: Are there no built in C# GUI Layouts?

ContentLicense: CC BY-SA 2.5


问:
C opening file from console
I have a simple code that opens a file from hdd in read mode, but the path of the file is already given in the code.I want the user to manually provide the file name,path and file open type through console. What do I have to do for that? </p>

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

int main() {
   FILE *fp;
   fp = fopen("D:\\samplefile.txt","r");
   if(fp != NULL) {
      printf("File has been opened");
      fclose(fp);
   }
   else printf("File not found");
   return 0;
}
</code>```

答:
```<code>#include <stdio.h>

int main()
{
  FILE *fp;
  char filePath[100],filePermission[10];
  printf("Enter Path name: ");
  scanf("%s", filePath);
  printf("Enter file permission parameters: ");
  scanf("%s", filePermission);

   fp = fopen(filePath,filePermission);
   if(fp != NULL) {
      printf("File has been opened");
      fclose(fp);
   }
   else printf("File not found");
   return 0;

}
</code>```

Title: C opening file from console

Body:
I have a simple code that opens a file from hdd in read mode, but the path of the file is already given in the code.I want the user to manually provide the file name,path and file open type through console. What do I have to do for that?

#include<stdio.h>

int main() {
   FILE *fp;
   fp = fopen("D:\\samplefile.txt","r");
   if(fp != NULL) {
      printf("File has been opened");
      fclose(fp);
   }
   else printf("File not found");
   return 0;
}


问:
GMAP.NET WPF - Center Shape Around Point
I'm adding shapes to my WPF GMap.NET control with code such as the following:

```<code>System.Windows.Point p = e.GetPosition(gMapControl1);
var point = gMapControl1.FromLocalToLatLng((int)p.X, (int)p.Y);
GMapMarker m = new GMapMarker(point);
m.Shape = new Rectangle
{
    Width = 10,
    Height = 10,
    Fill = System.Windows.Media.Brushes.Red

};
m.Tag = "PolyDot";
gMapControl1.Markers.Add(m);
</code>```

A problem that I'm experiencing is the shape is not centered on the point.  The shape's top left corner is normally where the point is.  How can I center the shape around the point?

答:
Figured it out.  Actually super easy</p>

```<code>GMapMarker m = new GMapMarker(point);
Rectangle recShape = new Rectangle
{
    Width = 100,
    Height = 100,
    Fill = System.Windows.Media.Brushes.Red

};
m.Shape = recShape;
m.Tag = "PolyDot";
m.Offset = new Point(-recShape.Width / 2, -recShape.Height/2);
gMapControl1.Markers.Add(m);
</code>```

Body:
I'm adding shapes to my WPF GMap.NET control with code such as the following:

System.Windows.Point p = e.GetPosition(gMapControl1);
var point = gMapControl1.FromLocalToLatLng((int)p.X, (int)p.Y);
GMapMarker m = new GMapMarker(point);
m.Shape = new Rectangle
{
    Width = 10,
    Height = 10,
    Fill = System.Windows.Media.Brushes.Red

};
m.Tag = "PolyDot";
gMapControl1.Markers.Add(m);

A problem that I'm experiencing is the shape is not centered on the point.  The shape's top left corner is normally where the point is.  How can I center the shape around the point?

Body:
Figured it out.  Actually super easy

GMapMarker m = new GMapMarker(point);
Rectangle recShape = new Rectangle
{
    Width = 100,
    Height = 100,
    Fill = System.Windows.Media.Brushes.Red

};
m.Shape = recShape;
m.Tag = "PolyDot";
m.Offset = new Point(-recShape.Width / 2, -recShape.Height/2);
gMapControl1.Markers.Add(m);


问:
coroutines in python using yield
I am trying to understand coroutines in python with yield operator.

```<code>def minimize():
    current = yield
    while True:
        value = yield current
        current = min(value, current)
</code>```

I have the function minimize() which returns the minimum value of the all the values that has been sent to the function till that point.

```<code>it = minimize()
next(it)
print(it.send(10))
print(it.send(4))
print(it.send(22))
print(it.send(-1))

>>>
10
4
4
-1
</code>```

I have a question regarding the function.

what does current = yeild achieve. From what I understood of yield in a generator context, yeild returns the next value when you use next() on the generator object.

答:
Let's follow the flow control, indented items are the minimize() generator:

```<code>it = minimize()   # Creates generator
next(it)
    current = yield       # suspends on yield (implicit None)
print(it.send(10))
    current = 10          # resumes
    while True:
        value = yield 10  # suspends on yield
# Output: 10
print(it.send(4))
        value = 4         # resumes
        current = min(4, 10)
    while True:
        current = yield 4
# Output: 4
print(it.send(22))
        value = 22
        current = min(22, 4)
    while True:
        current = yield 4
# Output: 4
print(it.send(-1))
        value = -1
        current = min(-1, 4)
    while True:
        current = yield -1
# Output: -1
</code>```

Title: coroutines in python using yield

Body:
I am trying to understand coroutines in python with yield operator.

def minimize():
    current = yield
    while True:
        value = yield current
        current = min(value, current)

I have the function minimize() which returns the minimum value of the all the values that has been sent to the function till that point.

it = minimize()
next(it)
print(it.send(10))
print(it.send(4))
print(it.send(22))
print(it.send(-1))

>>>
10
4
4
-1

I have a question regarding the function.

what does current = yeild achieve. From what I understood of yield in a generator context, yeild returns the next value when you use next() on the generator object.

Body:
Let's follow the flow control, indented items are the minimize() generator:

it = minimize()   # Creates generator
next(it)
    current = yield       # suspends on yield (implicit None)
print(it.send(10))
    current = 10          # resumes
    while True:
        value = yield 10  # suspends on yield
# Output: 10
print(it.send(4))
        value = 4         # resumes
        current = min(4, 10)
    while True:
        current = yield 4
# Output: 4
print(it.send(22))
        value = 22
        current = min(22, 4)
    while True:
        current = yield 4
# Output: 4
print(it.send(-1))
        value = -1
        current = min(-1, 4)
    while True:
        current = yield -1
# Output: -1


问:
if an a link contain something in the href change the href to this
i want to check if the href contains 'coming-soon' if it does change the href to go to my products page:

```<code>$('a[href$="coming-soon"]').attr('href', '/products.aspx');
</code>```

cant work this out.

答:
Use the contains selector.

```<code>$(document).ready(function(){
   $("a[href*='coming-soon']").attr('href', '/products.aspx');
});
</code>```

Try it here!

Body:
i want to check if the href contains 'coming-soon' if it does change the href to go to my products page:

$('a[href$="coming-soon"]').attr('href', '/products.aspx');

cant work this out.

Body:
Use the contains selector.

$(document).ready(function(){
   $("a[href*='coming-soon']").attr('href', '/products.aspx');
});

Try it here!


问:
what does '%%file test.py' mean in python?
Just as the title said. I'm trying to figure out what does the '%%' mean. It seems to be not a Placeholder here?</p>

```<code>%%file test_theano.py
from theano import config
print 'using device:', config.device
</code>```

答:
That %%file command is not Python, but rather an IPython "magic" command.  It puts the content which follows into a file named by its parameter.

Some time ago it was renamed %%writefile, but the old name is still supported, though no longer documented.  You can find the documentation for %%writefile here: https://ipython.org/ipython-doc/3/interactive/magics.html

If you try it in an IPython shell it will be quite clear what it does - it creates a file called test_theano.py in the current directory.

See also: How to load/edit/run/save text files (.py) into an IPython notebook cell?

Body:
Just as the title said. I'm trying to figure out what does the '%%' mean. It seems to be not a Placeholder here?

%%file test_theano.py
from theano import config
print 'using device:', config.device


问:
global function in Ionic 2 / Angular 2
How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

```<code>  openShare() {console.log("button clicked")}
</code>```

and then in my nav I have

```<code>  <button ion-button right (click)="openShare()">
  <ion-icon name="md-share"></ion-icon>
</button>
</code>```

When I try to access this from any page I get the following.

```<code>self.context.openShare is not a function
</code>```

It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.

Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.

Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.

Any help would be appreciated, still figuring Ionic 2 out.

答:
You can easily do that using Providers.When you need to use that functionality (or provider), you just need to inject it into your related component.That is it.

Method 1:

You can create a Provider using CLI.

```<code>> ionic g provider YourProvider
</code>```

your-provider.ts

```<code> import { Injectable } from '@angular/core';

    @Injectable()
    export class YourProvider {

      constructor() {
      }

       openShare() {console.log("button clicked")}
    }
</code>```

app.module.ts

```<code>import { YourProvider } from "../pages/path";

    @NgModule({
      declarations: [
        MyApp,
      ],
      imports: [
        IonicModule.forRoot(MyApp),
       ],
      bootstrap: [IonicApp],
      entryComponents: [
        MyApp,
        ],
      providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler },YourProvider  ]
    })

    export class AppModule { }
</code>```

your-view.ts

```<code>       import { YourProvider } from '../../providers/your-provider';

        export class YourViewPage{

          constructor(public yourProvider : YourProvider) {

          }

        openShare(){
           this.yourProvider.openShare();
        }
</code>```

Method 2: Creat an abstract base class.

my-base-class.ts

```<code>export abstract class MyBaseClass {

  constructor() {
  }

  protected openShare():void {
    console.log("button clicked");
  }

}
</code>```

my-view.ts

```<code>export class MyViewPage extends MyBaseClass {
  constructor()
  {
     super();
  }

       openShare(){
               super.openShare();
            }
  }
</code>```

Title: global function in Ionic 2 / Angular 2

Body:
How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

  openShare() {console.log("button clicked")}

and then in my nav I have

  <button ion-button right (click)="openShare()">
  <ion-icon name="md-share"></ion-icon>
</button>

When I try to access this from any page I get the following.

self.context.openShare is not a function

It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.

Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.

Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.

Any help would be appreciated, still figuring Ionic 2 out.

Body:
You can easily do that using Providers.When you need to use that functionality (or provider), you just need to inject it into your related component.That is it.

Method 1:

You can create a Provider using CLI.

> ionic g provider YourProvider

your-provider.ts

 import { Injectable } from '@angular/core';

    @Injectable()
    export class YourProvider {

      constructor() {
      }

       openShare() {console.log("button clicked")}
    }

app.module.ts

import { YourProvider } from "../pages/path";

    @NgModule({
      declarations: [
        MyApp,
      ],
      imports: [
        IonicModule.forRoot(MyApp),
       ],
      bootstrap: [IonicApp],
      entryComponents: [
        MyApp,
        ],
      providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler },YourProvider  ]
    })

    export class AppModule { }

your-view.ts

       import { YourProvider } from '../../providers/your-provider';

        export class YourViewPage{

          constructor(public yourProvider : YourProvider) {

          }

        openShare(){
           this.yourProvider.openShare();
        }

Method 2: Creat an abstract base class.

my-base-class.ts

export abstract class MyBaseClass {

  constructor() {
  }

  protected openShare():void {
    console.log("button clicked");
  }

}

my-view.ts

export class MyViewPage extends MyBaseClass {
  constructor()
  {
     super();
  }

       openShare(){
               super.openShare();
            }
  }


问:
How can I prevent data loss when saving web socket messages to mysql?
I am trying to implement a websocket realtime chat system in nodejs. I already have a login system in place and the websocket chat system. The only thing I'm stuck on is saving the messages to MySQL so that the user can access their chat history. The problem is that I don't want to send a web socket message to the recipient then have the MySQL insert fail for whatever reason.

A possible solution:
The obvious solution is to save the message data in MySQL then send the web socket message to the recipient. If there is an error, send that back to the sender instead of sending the message. Wouldn't this defeat the purpose of web sockets though, if the server has to wait for a MySQL insert success confirmation?

答:
Assuming this is a big deal because you want to avoid a small amount of latency waiting for a database save (which I think is not actually a problem to do that)..Send the message.  On the screen, display 'sending message..'
On the server, initiate the asynchronous database save.
When the other user's client receives the message, send print an
acknowledgement on the sender's screen
When the database save on the server completes, you dont have to do anything, unless it gives an error in which case you can inform the user there was an error saving the message and then retry the save.

Some systems like Google Hangouts during voice/video don't even try to save chat history.

You are only really going to have a problem if your database server runs out of space or goes down, in which case you have bigger problems and your error messages will clue the users in.

Or you can wait to save in the database, it isn't a huge amount of time to wait.  Also, websockets and socket.io always go to the server anyway.  If you were using WebRTC Data Channels, that is a peer 2 peer protocol that would not involve the server.


问:
what is the use of "response.setContentType("text/html")" in servlet
```<code>public class HelloWorld extends HttpServlet{
      public void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException,IOException{
      **response.setContentType("text/html");**
      PrintWriter pw = response.getWriter();
      pw.println("<html>");
      pw.println("<head><title>Hello World</title></title>");
      pw.println("<body>");
      pw.println("<h1>Hello World</h1>");
      pw.println("</body></html>");
      }
    }
</code>```

答:
You have to tell the browser what you are sending back so that the
browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video
player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.

some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc

In your case since you are sending HTML response to client you will have to set the content type as text/html

Body:
public class HelloWorld extends HttpServlet{
      public void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException,IOException{
      **response.setContentType("text/html");**
      PrintWriter pw = response.getWriter();
      pw.println("");
      pw.println("<title>Hello World</title></title>");
      pw.println("");
      pw.println("
Hello World
");
      pw.println("");
      }
    }


问:
How to set up a remote database?
I'm a beginner in swift iOS development and I'm enrolled in a couple of Udemy courses (Swift) although there is one question that I have that I can't seem to find the answer to. Bare in mind that I'm a beginner.

I want to make an app and a website that both use the same online database. Basically I want my users to be able to have their own account and store data on a remote database then be able to access it from either the app or the website.

How can I do that ? Most of the courses I followed suggest Firebase but I don't know how scalable it is, if it's fast enough and if it's not too expansive (I plan on having at least 10 000 users)

What would be the best option ? Should I use a MySQL and PHP alongside my swift app ? Should I stick to Firebase ? Or do you have any other suggestion ?

In my mind the best option would be to use Core Data and then synchronizing it with my database, but how do I do it ?

Thanks in advance

答:
Let me answer your questions one by one.

Is firebase scalable?
Yes, you can scale it very easily. It supports up to 100,000+ simultaneous connections. Since you are hoping to have 10,000 users only few might be online simultaneously. So it will definitely work for you.
For more info read https://groups.google.com/forum/#!msg/firebase-talk/KwN4vN7DxfQ/dgduFFZ8DAAJ

Is firebase fast?
One of the reasons why firebase became popular is because it has a very good response time. Now that it is bought by Google, you don't need to worry about it at all.

How expensive is it?
At 10,000 users you might end up spending 0-25$ if you use firebase. Google also gives free credits for startups.

Should you go with MySQL + PHP backend?
I would recommend you not to because you will need the expertise to build and it is even more difficult to maintain the application. You will spend energy in places that will add very little value to your application. Instead, you can use firebase and focus on improving the UX in the front end of the application.

Note: Firebase had one shortcoming, which is that all business logic will be written in the frontend of the app. But with a recent update, they have fixed it as well. You can read this https://firebase.googleblog.com/2013/03/where-does-firebase-fit-in-your-app.html

Kindly let me know if it helps.

Title: How to set up a remote database?


问:
How do I create a Javascript that finds average at every clicks on a button
How do I create a Javascript program that find the average of numbers entered in text box every time the find button is click?

```<code>var all=[];
$(document).on('click', 'check', function()
{
    var second, minute, hours, aht;
    second = document.getElementById('sec').value;
    minute = document.getElementById('min').value;
    hours = document.getElementById('hour').value;

    nocAll.push = (eval(second + (minute * 60) + (hours * 60 *60)));

    for(var i =0; i< nocAll.length; i++);
    sum += parseInt(nocAll.elmt[i], 10);
    aht = sum/nocAll.length;

    document.getElementById("AHT").innerHTML = aht;
})
</code>```

This shows what I have tried.

答:
You edited your question so here is a way to do it.

You have a few problems in your code.

nocAll is undefined (I think you meant to use all

Array.prototype.push is a function, all.push(value)

var all = [];
// cache the elements you will be working with
var $second = $('#sec')
var $minute = $('#min')
var $hour = $('#hour')
var $aht = $("#AHT")
// add two numbers together
var add = function(a, b) {
  return a + b
}

$(document).on('click', '.check', function() {
  // get the current values of the inputs and convert to seconds
  var hours   = Number($hour.val()) * 60 * 60
  var minutes = Number($minute.val()) * 60
  var seconds = Number($second.val())
  // add total time in seconds to the all array
  all.push(hours + minutes + seconds)
  // just for dubugging
  console.log(all)
  // calculate the average by folding the array and adding the values
  // then divide by the length
  $aht.html('average seconds:' + all.reduce(add, 0) / all.length)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="hour" placeholder="hours" />
<input type="text" id="min" placeholder="minutes" />
<input type="text" id="sec" placeholder="seconds" />
<button class="check">check</button>
<div id="AHT"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I create a Javascript program that find the average of numbers entered in text box every time the find button is click?

var all=[];
$(document).on('click', 'check', function()
{
    var second, minute, hours, aht;
    second = document.getElementById('sec').value;
    minute = document.getElementById('min').value;
    hours = document.getElementById('hour').value;

    nocAll.push = (eval(second + (minute * 60) + (hours * 60 *60)));

    for(var i =0; i< nocAll.length; i++);
    sum += parseInt(nocAll.elmt[i], 10);
    aht = sum/nocAll.length;

    document.getElementById("AHT").innerHTML = aht;
})

This shows what I have tried.

Body:
You edited your question so here is a way to do it.

You have a few problems in your code.

nocAll is undefined (I think you meant to use all

Array.prototype.push is a function, all.push(value)

var all = [];
// cache the elements you will be working with
var $second = $('#sec')
var $minute = $('#min')
var $hour = $('#hour')
var $aht = $("#AHT")
// add two numbers together
var add = function(a, b) {
  return a + b
}

$(document).on('click', '.check', function() {
  // get the current values of the inputs and convert to seconds
  var hours   = Number($hour.val()) * 60 * 60
  var minutes = Number($minute.val()) * 60
  var seconds = Number($second.val())
  // add total time in seconds to the all array
  all.push(hours + minutes + seconds)
  // just for dubugging
  console.log(all)
  // calculate the average by folding the array and adding the values
  // then divide by the length
  $aht.html('average seconds:' + all.reduce(add, 0) / all.length)
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="hour" placeholder="hours" />
<input type="text" id="min" placeholder="minutes" />
<input type="text" id="sec" placeholder="seconds" />
<button class="check">check</button>
<div id="AHT"></div>


问:
Understanding a Cobweb code
I'm trying to run a cobweb code in Mathematica and I need the following script:

```<code>ClearAll[CobwebPlot]
Options[CobwebPlot]=Join[{CobStyle->Automatic},Options[Graphics]];
CobwebPlot[f_,start_?NumericQ,n_,xrange:{xmin_,xmax_},opts:OptionsPattern[]]:=Module[{cob,x,g1,coor},
cob=NestList[f,N[start],n];
coor = Partition[Riffle[cob,cob],2,1];
coor[[1,2]]=0;
cobstyle=OptionValue[CobwebPlot,CobStyle];
cobstyle=If[cobstyle===Automatic,Red,cobstyle];
g1=Graphics[{cobstyle,Line[coor]}];
Show[{Plot[{x,f[x]},{x,xmin,xmax},PlotStyle->{{Thick,Black},Black}],g1},FilterRules[{opts},Options[Graphics]]]
]

Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]
</code>```

I found the script online but I don't understand some features, such as what is the purpose of the following characters, # and &, in the Manipulate[] segment of the code:

```<code>Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]
</code>```

Can you help me?

答:
See this Mathematica documentation page on pure functions, or what other languages call anonymous functions, or lambda functions.

To give a cute example, suppose you have the function

```<code>doItTwice[x_,f_] := f[f[x]];
</code>```

Now say you want to use this function to square the number seven twice. One way to do this would be to define a square function like this:

```<code>square[x_] := x^2;
doItTwice[7, square]
</code>```

Well, there is a cleaner way to do this by simply writing the square function as a pure function, which would look like (#^2)&. The # is the parameter to the pure function, and the & is just there to indicate that it's a pure function. Really the parenthesis aren't even necessary, so you could write #^2&. Anyways, the following code is now a cleaner way to square seven twice:

```<code>doItTwice[7, (#^2)&]
</code>```

Title: Understanding a Cobweb code

Body:
I'm trying to run a cobweb code in Mathematica and I need the following script:

ClearAll[CobwebPlot]
Options[CobwebPlot]=Join[{CobStyle->Automatic},Options[Graphics]];
CobwebPlot[f_,start_?NumericQ,n_,xrange:{xmin_,xmax_},opts:OptionsPattern[]]:=Module[{cob,x,g1,coor},
cob=NestList[f,N[start],n];
coor = Partition[Riffle[cob,cob],2,1];
coor[[1,2]]=0;
cobstyle=OptionValue[CobwebPlot,CobStyle];
cobstyle=If[cobstyle===Automatic,Red,cobstyle];
g1=Graphics[{cobstyle,Line[coor]}];
Show[{Plot[{x,f[x]},{x,xmin,xmax},PlotStyle->{{Thick,Black},Black}],g1},FilterRules[{opts},Options[Graphics]]]
]

Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]

I found the script online but I don't understand some features, such as what is the purpose of the following characters, # and &, in the Manipulate[] segment of the code:

Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]

Can you help me?

Body:
See this Mathematica documentation page on pure functions, or what other languages call anonymous functions, or lambda functions.

To give a cute example, suppose you have the function

doItTwice[x_,f_] := f[f[x]];

Now say you want to use this function to square the number seven twice. One way to do this would be to define a square function like this:

square[x_] := x^2;
doItTwice[7, square]

Well, there is a cleaner way to do this by simply writing the square function as a pure function, which would look like (#^2)&. The # is the parameter to the pure function, and the & is just there to indicate that it's a pure function. Really the parenthesis aren't even necessary, so you could write #^2&. Anyways, the following code is now a cleaner way to square seven twice:

doItTwice[7, (#^2)&]


问:
Forward ControlEvent from UITableView
I want to create a list of planet in a separate controller (my PlanetPickerViewController). This controller uses a UITableView to display a given list of Planet. This works fine.

```<code>public class PlanetPickerViewController: RxViewController {

    // MARK: - PUBLIC -

    public var selection: ControlEvent<Planet>!

    public init(list: Driver<[Planet]>, active: Planet?) {
        self.list = list
        self.active = active
        super.init(nibName: "PlanetPickerViewController", bundle: nil)
    }

    @available(*, unavailable)
    required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    // MARK: - PRIVATE -

    private let list: Driver<[Planet]>
    private let active: Planet?

    // MARK: IBOutlets

    @IBOutlet private weak var tableView: UITableView!

    // MARK: View life cycle

    override public func viewDidLoad() {
        super.viewDidLoad()
        self.initializeTableView()
    }

    private func initializeTableView() {
        self.list.drive(self.tableView.rx.items(reusable: PlanetTableViewCell.self)) { row, planet, cell in
            cell.display(planet)
            cell.isSelected = planet == self.active
        }
        .disposed(by: self)

        self.selection = self.tableView.rx.modelSelected(Planet.self)
    }
}
</code>```

Now I want to forward the event of the user tapping a cell. Usually, I'd create a PlanetPickerViewControllerDelegate with a dedicated function to manually forward this event:

```<code>// PlanetPickerViewControllerDelegate
picker(_ picker: PlanetPickerViewController, didSelect planet: Planet)

// PlanetPickerViewController: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let planet = self.list[indexPath.row]
    self.delegate?.picker(self, didSelect: planet)
}
</code>```

But with RxSwift I want to replace this delegate by a ControlEvent<Planet>. This is what I intended with public var selection: ControlEvent<Planet>!. The bad thing is I can't subscribe to it before viewDidLoad occurs...

What should I change to be able to subscribe to my selection as soon as this controller is instantiated ?

```<code>let modal = PlanetPickerViewController(list: planets, active: nil)
modal.selection.subscribe { do something }
self.present(modal, animated: true, completion: nil)
</code>```

答:
You can create an Observable<Planet> and subscribe to it in your main view controller:

```<code>// PlanetPickerViewController

let didSelectPlanet: Observable<Planet>!

private func initializeTableView() {
    // ...

    self.didSelectPlanet = self.tableView.rx.modelSelected(Planet.self).asObservable()
}

// MainViewController
let modal = PlanetPickerViewController(list: planets, active: nil)
modal.self.didSelectPlanet
     .subscribe(onNext: { _ in /* do something */ })
     .disposed(by: disposeBag)
</code>```

Title: Forward ControlEvent from UITableView

Body:
I want to create a list of planet in a separate controller (my PlanetPickerViewController). This controller uses a UITableView to display a given list of Planet. This works fine.

public class PlanetPickerViewController: RxViewController {

    // MARK: - PUBLIC -

    public var selection: ControlEvent<Planet>!

    public init(list: Driver<[Planet]>, active: Planet?) {
        self.list = list
        self.active = active
        super.init(nibName: "PlanetPickerViewController", bundle: nil)
    }

    @available(*, unavailable)
    required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    // MARK: - PRIVATE -

    private let list: Driver<[Planet]>
    private let active: Planet?

    // MARK: IBOutlets

    @IBOutlet private weak var tableView: UITableView!

    // MARK: View life cycle

    override public func viewDidLoad() {
        super.viewDidLoad()
        self.initializeTableView()
    }

    private func initializeTableView() {
        self.list.drive(self.tableView.rx.items(reusable: PlanetTableViewCell.self)) { row, planet, cell in
            cell.display(planet)
            cell.isSelected = planet == self.active
        }
        .disposed(by: self)

        self.selection = self.tableView.rx.modelSelected(Planet.self)
    }
}

Now I want to forward the event of the user tapping a cell. Usually, I'd create a PlanetPickerViewControllerDelegate with a dedicated function to manually forward this event:

// PlanetPickerViewControllerDelegate
picker(_ picker: PlanetPickerViewController, didSelect planet: Planet)

// PlanetPickerViewController: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let planet = self.list[indexPath.row]
    self.delegate?.picker(self, didSelect: planet)
}

But with RxSwift I want to replace this delegate by a ControlEvent<Planet>. This is what I intended with public var selection: ControlEvent<Planet>!. The bad thing is I can't subscribe to it before viewDidLoad occurs...

What should I change to be able to subscribe to my selection as soon as this controller is instantiated ?

let modal = PlanetPickerViewController(list: planets, active: nil)
modal.selection.subscribe { do something }
self.present(modal, animated: true, completion: nil)

Body:
You can create an Observable<Planet> and subscribe to it in your main view controller:

// PlanetPickerViewController

let didSelectPlanet: Observable<Planet>!

private func initializeTableView() {
    // ...

    self.didSelectPlanet = self.tableView.rx.modelSelected(Planet.self).asObservable()
}

// MainViewController
let modal = PlanetPickerViewController(list: planets, active: nil)
modal.self.didSelectPlanet
     .subscribe(onNext: { _ in /* do something */ })
     .disposed(by: disposeBag)


问:
Unable to sort an Arraylist
Trying to print output as:

First max

First min

Second Max

Second min

Third Max ... and so on

This is my code:

```<code>import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class Arraylist1 {
public static void main(String args[]){
 List <Integer>list= new ArrayList <Integer> ( );
 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);
 for(int i=0;i<list.size();i++) {
  if(i%2==0){
    Object num=Collections.max(list);
    System.out.println(num);
    list.remove(num);
  }
 else if(i%2!=0)
    {
    Object num1=Collections.min(list);
    System.out.println(num1);
    list.remove(num1);
    }
}
}
}

 70
 20
 60
</code>```

Why it printing only first three numbers?

My expected output:

```<code> 70 20 60 30 50 40
</code>```

答:
With Every list.remove(), the size of list gets decremented. So the loop only runs 3 times. You can use a while loop instead.</p>

```<code>public static void main(String args[]){
    List<Integer>list= new ArrayList <Integer> ();
    list.add(20);
    list.add(30);
    list.add(70);
    list.add(50);
    list.add(60);
    list.add(40);
    int i =0;
    while(!list.isEmpty()) {
        if(i%2==0){
            Object num=Collections.max(list);
            System.out.println(num);
            list.remove(num);
        }
        else if(i%2!=0) {
            Object num1=Collections.min(list);
            System.out.println(num1);
            list.remove(num1);
        }
        i++;
    }
}
</code>```

Title: Unable to sort an Arraylist

Body:
Trying to print output as:

First max

First min

Second Max

Second min

Third Max ... and so on

This is my code:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class Arraylist1 {
public static void main(String args[]){
 List <Integer>list= new ArrayList <Integer> ( );
 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);
 for(int i=0;i<list.size();i++) {
  if(i%2==0){
    Object num=Collections.max(list);
    System.out.println(num);
    list.remove(num);
  }
 else if(i%2!=0)
    {
    Object num1=Collections.min(list);
    System.out.println(num1);
    list.remove(num1);
    }
}
}
}

 70
 20
 60

Why it printing only first three numbers?

My expected output:

 70 20 60 30 50 40

Body:
With Every list.remove(), the size of list gets decremented. So the loop only runs 3 times. You can use a while loop instead.

public static void main(String args[]){
    List<Integer>list= new ArrayList <Integer> ();
    list.add(20);
    list.add(30);
    list.add(70);
    list.add(50);
    list.add(60);
    list.add(40);
    int i =0;
    while(!list.isEmpty()) {
        if(i%2==0){
            Object num=Collections.max(list);
            System.out.println(num);
            list.remove(num);
        }
        else if(i%2!=0) {
            Object num1=Collections.min(list);
            System.out.println(num1);
            list.remove(num1);
        }
        i++;
    }
}


问:
Umbrella header 'CocoaAsyncSocket-umbrella.h' not found
With XCode 8.3 or lower, no values of variables are displayed:

When a variable T is output:

```<code>lldb> po t
</code>```

Then XCode issues the following error message:

```<code>warning: Swift error in module testProject.
Debug info from this module will be unavailable in the debugger.
error: in auto-import:
failed to get module 'testProject' from AST context:
error: /Users/xxx/Library/Developer/Xcode/DerivedData/testProject-ancfblnaxqmiivgqakzxqkocqfrg/Build/Products/Debug-iphonesimulator/CocoaAsyncSocket/CocoaAsyncSocket.framework/Modules/module.modulemap:2:19: error: umbrella header 'CocoaAsyncSocket-umbrella.h' not found
  umbrella header "CocoaAsyncSocket-umbrella.h"
</code>```

I found few pages for this problem:
Move header on top

However, it has not solved the problem.
The problem might be CocoaPod. In the previous versions of CocoaPod, there was a problem that Pod Libraries could not be compiled. Because CocoaPod generates the umbrella-headers automatically.

答: Seems this is already answered at Swift Framework: Umbrella header '[...].h' not found, If not please share your podfile and further observations.</p>

Body:
With XCode 8.3 or lower, no values of variables are displayed:

When a variable T is output:

lldb> po t

Then XCode issues the following error message:

warning: Swift error in module testProject.
Debug info from this module will be unavailable in the debugger.
error: in auto-import:
failed to get module 'testProject' from AST context:
error: /Users/xxx/Library/Developer/Xcode/DerivedData/testProject-ancfblnaxqmiivgqakzxqkocqfrg/Build/Products/Debug-iphonesimulator/CocoaAsyncSocket/CocoaAsyncSocket.framework/Modules/module.modulemap:2:19: error: umbrella header 'CocoaAsyncSocket-umbrella.h' not found
  umbrella header "CocoaAsyncSocket-umbrella.h"

I found few pages for this problem:
Move header on top

However, it has not solved the problem.
The problem might be CocoaPod. In the previous versions of CocoaPod, there was a problem that Pod Libraries could not be compiled. Because CocoaPod generates the umbrella-headers automatically.


问:
Can main() function be called a constructor function
I want to know whether int main() function be called a constructor function since it nearly works same as a constructor function of a class?

And if yes, then what is the class name it belongs to?

Edit: The reason why I think main() works nearly same as constructor function is that whenever we execute a programme the first thing which gets executed is the main function.. Similarly a constructor function executes first whenever we define a  variable with data type as user defined class

答:
From reference:

main() "is a global function named main, which is the designated start of the program".[1]

So it is not part of a class, not a member method, hence the method CANNOT be a constructor. Rememember that C++ is a multiparadigm language. It includes an object oriented approach, but it does not need it to function. Java or C# are also multiparadigm, but they are mainly class and OOP based. For instance, in Java and C# you need to have classes and objects to create a "Hello World" program.


问:
React Add/Remove and Toggle Class of Sidebar with background overlay
Here my code: http://codepen.io/rafaelfndev/pen/gmqmvo

I need to add class:

.overflow to body

.overlay-active to .overlay

.sidebar-active to #sidebar

I need add when I click on .show-sidebar independent of the location of the component that has this classes. If I click on .hide-sidebar, I need remove this classes, and if I click on .toggle-class I need to toggle this classes...

I know how to do this with jQuery, but I read somewhere that is wrong manipulate React elements with jQuery...

I need to do exactly what this code does, but without jQuery, just using the React pattern:

```<code>$('.toggle-sidebar').click(function(){
    $('#sidebar').toggleClass('sidebar-active');
    $('body').toggleClass('overflow');
    $('overlay').toggleClass('overlay-active');
});

$('.show-sidebar').click(function(){
    $('#sidebar').addClass('sidebar-active');
    $('body').addClass('overflow');
    $('overlay').addClass('overlay-active');
});

$('.hide-sidebar, overlay').click(function(){
    $('#sidebar').removeClass('sidebar-active');
    $('body').removeClass('overflow');
    $('overlay').removeClass('overlay-active');
});
</code>```

答:
I don't know exactly which elements you are using for sidebar, but I will consider it as a div and the others as buttons.

You can keep a state on the main component(The component controlling the sidebar and the buttons) and change the state with the onClick of each button. With this state you can set some styles on you sidebar or activate classes with something like classenames lib

I made this codepen showing how you can follow this approach, hope it help you. It is basically a SideBar component receiving a props called "show" and using it do change a div style. The App component has a "show" state that changes with the click on the buttons and passes it to SideBar component.

The code is as follow:

```<code>class SideBar extends React.Component{
  render() {
    return <div style={{display: this.props.show?'block':'none'}}>
      I am a side bar!
    </div>
  };
}

class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {show: true};
  }

  render(){
    return <div>
      <SideBar show={this.state.show}/>
      <button onClick={()=>this.setState({show: !this.state.show})} >toggle</button>
      <button onClick={()=>this.setState({show:true})} >add</button>
      <button onClick={()=>this.setState({show:false})}>remove</button>
    </div>
  }
}

ReactDOM.render(<App/>, document.getElementById('container'));
</code>```

Body:
Here my code: http://codepen.io/rafaelfndev/pen/gmqmvo

I need to add class:

.overflow to body

.overlay-active to .overlay

.sidebar-active to #sidebar

I need add when I click on .show-sidebar independent of the location of the component that has this classes. If I click on .hide-sidebar, I need remove this classes, and if I click on .toggle-class I need to toggle this classes...

I know how to do this with jQuery, but I read somewhere that is wrong manipulate React elements with jQuery...

I need to do exactly what this code does, but without jQuery, just using the React pattern:

$('.toggle-sidebar').click(function(){
    $('#sidebar').toggleClass('sidebar-active');
    $('body').toggleClass('overflow');
    $('overlay').toggleClass('overlay-active');
});

$('.show-sidebar').click(function(){
    $('#sidebar').addClass('sidebar-active');
    $('body').addClass('overflow');
    $('overlay').addClass('overlay-active');
});

$('.hide-sidebar, overlay').click(function(){
    $('#sidebar').removeClass('sidebar-active');
    $('body').removeClass('overflow');
    $('overlay').removeClass('overlay-active');
});

Body:
I don't know exactly which elements you are using for sidebar, but I will consider it as a div and the others as buttons.

You can keep a state on the main component(The component controlling the sidebar and the buttons) and change the state with the onClick of each button. With this state you can set some styles on you sidebar or activate classes with something like classenames lib

I made this codepen showing how you can follow this approach, hope it help you. It is basically a SideBar component receiving a props called "show" and using it do change a div style. The App component has a "show" state that changes with the click on the buttons and passes it to SideBar component.

The code is as follow:

class SideBar extends React.Component{
  render() {
    return <div style={{display: this.props.show?'block':'none'}}>
      I am a side bar!
    </div>
  };
}

class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {show: true};
  }

  render(){
    return <div>
      <SideBar show={this.state.show}/>
      <button onClick={()=>this.setState({show: !this.state.show})} >toggle</button>
      <button onClick={()=>this.setState({show:true})} >add</button>
      <button onClick={()=>this.setState({show:false})}>remove</button>
    </div>
  }
}

ReactDOM.render(<App/>, document.getElementById('container'));


问:
Pull new updates from original GitHub repository into forked GitHub repository
I forked someone's repository on GitHub and would like to update my version with commits and updates made in the original repository. These were made after I forked my copy.

How can I pull in the changes that were made in the origin and incorporate them into my repository?

答:
If you're using the GitHub desktop application, there is a synchronise button on the top right corner. Click on it then Update from <original repo> near top left.

If there are no changes to be synchronised, this will be inactive.

Here are some screenshots to make this easy.


问:
Changing data between 2 view controllers objective C
I have 2 view controller: AccountViewController and ChangeEmailViewController. The account controller contains the email of the user. The user can change his email by pressing the button titled "change" and will take him to a ChangeEmailViewController. In ChangeEmailViewController, he can write the new email and  click on the button titled "submit" to change the email and will show the new email in AccountViewController.(check image to see what I've done in storyboard)

image

My Questions are:
1- How I can connect both view controllers together?
2- How can I show the email of the user in the old email section in ChangeViewController?
3- How can I change the email of user in AccountViewController with the new email that the user will submit when he/she writes it in the textfield of ChangeEmailController and will be the new email in AccountViewController

答:
Here are my answers

How I can connect both view controllers together?

You can use delegate. You can connect two viewcontrollers through delegate.

You can use NSNotificationCenter.

You can set one of them to a property of the other.

How can I show the email of the user in the old email section in ChangeViewController?

In general, you can pass the old email value when you call/create ChangeViewController. Perhaps, you will call/create instance of ChangeViewController via segue identification or Xib identification.
If you use segue identification, you can pass the value by overriding prepareForSeque.
please note: How to pass prepareForSegue: an object

If you use Xib identification, you can note below
Passing parameter from one xib to another xib

You could have another one way. If the value was stored in DB or BackEnd Server, you can get it again in ChangeViewController.
Of course, Once you think that it's better way for you.

How can I change the email of....

You can use Delegate or NSNotificationCenter.

When the value is changed, you can use call function through Delegate or send a message via NSNotificationCenter.

Well, if you have another questions, please feel free to contact me.

Thanks.


问:
ABC size too high, even when there are no branches, assignments, or conditionals
I am confused here about what RuboCop is complaining about.

"Assignment Branch Condition size for draw is too high. [29/15]"

for the method below:

```<code>class Ball
  attr_reader :color
  attr_reader :center
  attr_reader :radius
  attr_reader :dir
  attr_reader :x, :y
  attr_reader :w, :h
  attr_accessor :worldWidth
  attr_accessor :worldHeight
  ...
  # Draw the ball into this device context
  def draw(dc)
    dc.setForeground(color)
    dc.fillArc(x, y, w, h, 0, 64 * 90)
    dc.fillArc(x, y, w, h, 64 * 90, 64 * 180)
    dc.fillArc(x, y, w, h, 64 * 180, 64 * 270)
    dc.fillArc(x, y, w, h, 64 * 270, 64 * 360)
  end
  ...
</code>```

Because there are no assignments, branches, nor conditionals here!

What am I missing? And what is so bad about this function anyway? It would seem silly to have to change it, and I am not clear on what "benefit" it would bring. Please clarify!

答:
The formula RuboCop uses to calculate the ABC size is:

```<code>sqrt(assignments^2 + branches^2 + condition^2)
</code>```

A message send (a.k.a. method call) is considered one "branch" in RuboCop. Since, as you pointed out, there are no assignments or conditions in this case, the ABC size for this method is given by sqrt(branches^2) or, simply, branches.

We can check that this is correct by counting the message sends in the method:

1 x #setForeground

1 x #color

4 x #fillArc

4 x #x

4 x #y

4 x #w

4 x #h

7 x #*

for a grand total of 29, which is the ABC size we expected.

And what is so bad about this function anyway? It would seem silly to have to change it, and I am not clear on what "benefit" it would bring.

Don't make the mistake of thinking RuboCop is omnipotent. It neither reads nor understands code. It doesn't have a notion of "better" code. It applies some (rather primitive) heuristics that gives us a proxy measure of "quality." It is up to us to interpret that and decide what action to take.

A common case where RuboCop struggles is declarative DSLs. In those cases, it's usually best to disable the cops that break down. RuboCop offers different levels of granularity to do this. You can do it inline, using rubocop:disable CopName (remember to enable it again), on a file or directory basis in .rubocop.yml, or for the entire project in the same file.

Body:
I am confused here about what RuboCop is complaining about.

"Assignment Branch Condition size for draw is too high. [29/15]"

for the method below:

class Ball
  attr_reader :color
  attr_reader :center
  attr_reader :radius
  attr_reader :dir
  attr_reader :x, :y
  attr_reader :w, :h
  attr_accessor :worldWidth
  attr_accessor :worldHeight
  ...
  # Draw the ball into this device context
  def draw(dc)
    dc.setForeground(color)
    dc.fillArc(x, y, w, h, 0, 64 * 90)
    dc.fillArc(x, y, w, h, 64 * 90, 64 * 180)
    dc.fillArc(x, y, w, h, 64 * 180, 64 * 270)
    dc.fillArc(x, y, w, h, 64 * 270, 64 * 360)
  end
  ...

Because there are no assignments, branches, nor conditionals here!

What am I missing? And what is so bad about this function anyway? It would seem silly to have to change it, and I am not clear on what "benefit" it would bring. Please clarify!

Body:
The formula RuboCop uses to calculate the ABC size is:

sqrt(assignments^2 + branches^2 + condition^2)

A message send (a.k.a. method call) is considered one "branch" in RuboCop. Since, as you pointed out, there are no assignments or conditions in this case, the ABC size for this method is given by sqrt(branches^2) or, simply, branches.

We can check that this is correct by counting the message sends in the method:

1 x #setForeground

1 x #color

4 x #fillArc

4 x #x

4 x #y

4 x #w

4 x #h

7 x #*

for a grand total of 29, which is the ABC size we expected.

And what is so bad about this function anyway? It would seem silly to have to change it, and I am not clear on what "benefit" it would bring.

Don't make the mistake of thinking RuboCop is omnipotent. It neither reads nor understands code. It doesn't have a notion of "better" code. It applies some (rather primitive) heuristics that gives us a proxy measure of "quality." It is up to us to interpret that and decide what action to take.

A common case where RuboCop struggles is declarative DSLs. In those cases, it's usually best to disable the cops that break down. RuboCop offers different levels of granularity to do this. You can do it inline, using rubocop:disable CopName (remember to enable it again), on a file or directory basis in .rubocop.yml, or for the entire project in the same file.


问:
php add html element inside while loop
Hello here is my code :

```<code><table class="table table-hover table-bordered">
<tr>
<th class="well" style="text-align:center">ID</th>
<th class="well" style="text-align:center">Email</th>
<th class="well" style="text-align:center">User level</th>
</tr>';

<?
$code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_id ASC ";
$code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
$sql_rows = mysql_num_rows($code_query);
if($sql_rows > 0){
while($rows = mysql_fetch_object($code_query)){
$user_id = intval($rows->user_id);
$user_level= intval($rows->user_level);
$user_email = htmlspecialchars($rows->user_email);
echo '      <tr>
<td>'.$user_id.'</td>
<td>'.$user_email.'</td>
<td>'.$user_level.'</td>
</tr>';
}
mysql_free_result($code_query);
}else{
echo '<tr>
<td>
<font color="red">no data found</font>
</td>
</tr>';
}
echo '</table>';
?>
</code>```

the output of the code will be like .

```<code><table class="table table-hover table-bordered">
<tr>
<th class="well" style="text-align:center">ID</th>
<th class="well" style="text-align:center">Email</th>
<th class="well" style="text-align:center">User level</th>
</tr>
<tr>
<td>1</td>
<td>test1@gmail.com</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>test2@gmail.com</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>test3@gmail.com</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>test4@gmail.com</td>
<td>1</td>
</tr>
</table>
</code>```

(1 = normal user , and 2 = admin for user level) but what I want is something .like that

```<code><table class="table table-hover table-bordered">
<tr>
<th class="well" style="text-align:center">ID</th>
<th class="well" style="text-align:center">Email</th>
<th class="well" style="text-align:center">User level</th>
</tr>
<div id="users">
<tr>
<td>1</td>
<td>test1@gmail.com</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>test4@gmail.com</td>
<td>1</td>
</tr>
</div>
<div id="admins">
<tr>
<td>2</td>
<td>test2@gmail.com</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>test3@gmail.com</td>
<td>2</td>
</tr>
</div>
</table>
</code>```

I want to add a div id="users" that will contain all users from database that have user_level = 1 and another div id="admins" for user_level = 2.

答:
Try the below code with tbody to group table rows,

```<code><?php
$code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_level ASC, user_id ASC ";
$code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
$sql_rows =        mysql_num_rows($code_query);
if($sql_rows > 0){
  $newgroup = false;
  $groupid = array(1=>'users', 2=>'admins');
  while($rows = mysql_fetch_object($code_query)){
    $user_id = intval($rows->user_id);
    $user_level= intval($rows->user_level);
    $user_email = htmlspecialchars($rows->user_email);
    if($newgroup != $user_level) {
      if($newgroup != false) echo '</tbody>';
      echo '<tbody id="'.$groupid[$user_level].'">';
      $newgroup = $user_level;
    }
  echo '      <tr>
  <td>'.$user_id.'</td>
  <td>'.$user_email.'</td>
  <td>'.$user_level.'</td>
  </tr>';
}
echo '</tbody>';
mysql_free_result($code_query);
}else{
 echo '<tr>
  <td>
    <font color="red">no data found</font>
  </td>
</tr>';
}
echo '</table>';
?>
</code>```

Note:
It would work if you just want to group table rows. But if you want to add additional features like animation then you might need to add more css/jQuery.

Additional suggestions:
1. You should start using mysqli or PDO
2. You should start using css to replace font tags.

Title: php add html element inside while loop

Body:
Hello here is my code :

ID
Email
User level

';

<?
$code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_id ASC ";
$code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
$sql_rows = mysql_num_rows($code_query);
if($sql_rows > 0){
while($rows = mysql_fetch_object($code_query)){
$user_id = intval($rows->user_id);
$user_level= intval($rows->user_level);
$user_email = htmlspecialchars($rows->user_email);
echo '

'.$user_id.'
'.$user_email.'
'.$user_level.'

';
}
mysql_free_result($code_query);
}else{
echo '

no data found

';
}
echo '
';
?>

the output of the code will be like .

ID
Email
User level

1
test1@gmail.com
1

2
test2@gmail.com
2

3
test3@gmail.com
2

4
test4@gmail.com
1

(1 = normal user , and 2 = admin for user level) but what I want is something .like that

ID
Email
User level

1
test1@gmail.com
1

4
test4@gmail.com
1

2
test2@gmail.com
2

3
test3@gmail.com
2

I want to add a div id="users" that will contain all users from database that have user_level = 1 and another div id="admins" for user_level = 2.

Body:
Try the below code with tbody to group table rows,

<?php
$code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_level ASC, user_id ASC ";
$code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
$sql_rows =        mysql_num_rows($code_query);
if($sql_rows > 0){
  $newgroup = false;
  $groupid = array(1=>'users', 2=>'admins');
  while($rows = mysql_fetch_object($code_query)){
    $user_id = intval($rows->user_id);
    $user_level= intval($rows->user_level);
    $user_email = htmlspecialchars($rows->user_email);
    if($newgroup != $user_level) {
      if($newgroup != false) echo '</tbody>';
      echo '<tbody id="'.$groupid[$user_level].'">';
      $newgroup = $user_level;
    }
  echo '      <tr>
  <td>'.$user_id.'</td>
  <td>'.$user_email.'</td>
  <td>'.$user_level.'</td>
  </tr>';
}
echo '</tbody>';
mysql_free_result($code_query);
}else{
 echo '<tr>
  <td>
    <font color="red">no data found</font>
  </td>
</tr>';
}
echo '</table>';
?>

Note:
It would work if you just want to group table rows. But if you want to add additional features like animation then you might need to add more css/jQuery.

Additional suggestions:
1. You should start using mysqli or PDO
2. You should start using css to replace font tags.


问:
Pygame can't run over 60 FPS
I'm running a Pygame simulation with Python 3 on OSX. For some reason I cannot exceed 60 fps, but ideally I would be able to run it very high to run multiple trials in a short amount of time.

Im using clock = pygame.time.Clock() at the top of my main, and then:

```<code>while True:
    clock.tick(1000)
    print(clock.get_fps())
</code>```

Any suggestions for how I could get my clock to run faster? Thanks.

答:
From http://pygame.org/docs/ref/time.html#pygame.time.Clock.tick

Note that this function uses SDL_Delay function which is not accurate
  on every platform, but does not use much CPU. Use tick_busy_loop if
  you want an accurate timer, and don’t mind chewing CPU.

tick_busy_loop reference: http://pygame.org/docs/ref/time.html#pygame.time.Clock.tick_busy_loop

Title: Pygame can't run over 60 FPS

Body:
I'm running a Pygame simulation with Python 3 on OSX. For some reason I cannot exceed 60 fps, but ideally I would be able to run it very high to run multiple trials in a short amount of time.

Im using clock = pygame.time.Clock() at the top of my main, and then:

while True:
    clock.tick(1000)
    print(clock.get_fps())

Any suggestions for how I could get my clock to run faster? Thanks.


问:
Spark & Scala: Generate DataSet (or Dataframe) with given size
For evaluation purposes, I need a function that creates a dummy-Dataset (or, alternatively aDataFrame), initialized with random numbers. The dimensions in terms of columns and rows should be parametrized

I came up with a solution, but that is absurdly slow (5.3s for 10 rows with 100 columns):

```<code>def createDummyDataset(rows : Int, columns: Int, spark: SparkSession) = {
   import spark.implicits._

   var ds = Seq.fill(rows)(Random.nextDouble).toDF()
   if (columns > 1) {
      for (i <- 2 to columns) {
         ds = ds.withColumn(i.toString, rand)
      }
   }
   ds // return ds
}
</code>```

Is that due to the architecture of Spark or am I doing something completely wrong and there is a much better way?

I guess a better way would be to define some kind of matrix and convert that to a Dataset at a blow. But I was not able to figure that out.

System: Spark 2.1.0, Scala 2.11.8, Ubuntu 16.04, i5-6300U, 32GB RAM

答:
Based on ImDarrenG answer, however the output is a data frame with n rows and m columns.

```<code>import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{DoubleType, StructField, StructType}

def start(rows: Int, cols: Int, col: String, spark: SparkSession): Unit = {

         val data = (1 to rows).map(_ => Seq.fill(cols)(Random.nextDouble))

         val colNames = (1 to cols).mkString(",")
         val sch = StructType(colNames.split(",").map(fieldName => StructField(fieldName, DoubleType, true)))

         val rdd = spark.sparkContext.parallelize(data.map(x => Row(x:_*)))
         val df = spark.sqlContext.createDataFrame(rdd, sch)

         df.printSchema()

         spark.stop()
    }
</code>```

Running on Spark 2.1.0, Scala 2.11.8, Fedora Scientific,  i5-5200U 4 cores, 16Gb RAM

For 10 Rows x 100 Columns on average elapsed time was 0.9 sec

Body:
For evaluation purposes, I need a function that creates a dummy-Dataset (or, alternatively aDataFrame), initialized with random numbers. The dimensions in terms of columns and rows should be parametrized

I came up with a solution, but that is absurdly slow (5.3s for 10 rows with 100 columns):

def createDummyDataset(rows : Int, columns: Int, spark: SparkSession) = {
   import spark.implicits._

   var ds = Seq.fill(rows)(Random.nextDouble).toDF()
   if (columns > 1) {
      for (i <- 2 to columns) {
         ds = ds.withColumn(i.toString, rand)
      }
   }
   ds // return ds
}

Is that due to the architecture of Spark or am I doing something completely wrong and there is a much better way?

I guess a better way would be to define some kind of matrix and convert that to a Dataset at a blow. But I was not able to figure that out.

System: Spark 2.1.0, Scala 2.11.8, Ubuntu 16.04, i5-6300U, 32GB RAM

Body:
Based on ImDarrenG answer, however the output is a data frame with n rows and m columns.

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{DoubleType, StructField, StructType}

def start(rows: Int, cols: Int, col: String, spark: SparkSession): Unit = {

         val data = (1 to rows).map(_ => Seq.fill(cols)(Random.nextDouble))

         val colNames = (1 to cols).mkString(",")
         val sch = StructType(colNames.split(",").map(fieldName => StructField(fieldName, DoubleType, true)))

         val rdd = spark.sparkContext.parallelize(data.map(x => Row(x:_*)))
         val df = spark.sqlContext.createDataFrame(rdd, sch)

         df.printSchema()

         spark.stop()
    }

Running on Spark 2.1.0, Scala 2.11.8, Fedora Scientific,  i5-5200U 4 cores, 16Gb RAM

For 10 Rows x 100 Columns on average elapsed time was 0.9 sec


问:
vb.net datatype in manually added column
```<code>Dim pctofpax As New DataColumn
        pctofpax = New DataColumn("PCTPAX1", GetType(Decimal))
        pctofpax.Expression = "[ASOFPAX] / [YEPAX]"
        ds.Tables("workplease").Columns.Add(pctofpax)

        Dim avgppax As New DataColumn
        avgppax = New DataColumn("AVG PAX", GetType(Double))
        avgppax.Expression = "[Current Sales] / [Current PAX]"
        ds.Tables("workplease").Columns.Add(avgppax)
</code>```

These are two columns that i added into my asp.net/vb.net datagrid. the problem is i keep trying to change the datatypes so they show up as numbers with only two decimals but it is not working

```<code>            <span lang="en-us">Sales As Of Analysis</span><br />
        <asp:GridView ID="GridView1" runat="server" BackColor="White"
            BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
            GridLines="Vertical">
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
        </asp:GridView>
    <asp:BoundColumn DataField="PCTPAX1"
                 HeaderText="PCTPAX1"
                 DataFormatString="{0:c}">

    </div>
    </form>
</body>
</html>
</code>```

and nothing happend to my data

答:
If it's just a matter of displaying only two decimals, this can be accomplished in the display code for the DataGrid:

```<code><asp:BoundField DataField="PCTPAX1"
                 HeaderText="PCTPAX1"
                 DataFormatString="{0:c}">
</code>```

Note the DataFormatString value of {0:c} which specifies that the formatting of the value in that field should be "currency."  (You can also try with a capital C, I don't have a test handy for it right now.)  There's a lot more you can do with format strings, more information here.

Or do you want the actual values to be rounded to currency values?  You'll likely use Math.Round for that, though I don't have an example handy.  There's information about that here.

Edit: Based on your comment(s), it sounds like you were attempting to change data types at the database level.  This won't really impact the code.  The value coming back from the database in the form of a double or decimal or some other numeric likely won't carry that precision back to the code.  As far as the DataGrid is concerned, it's calling .ToString() on a double and showing the result.  No database data type is involved.  Using the DataFormatString property to pass a format string to the .ToString() method is how to change the display.

Edit again based on your question edit: Your HTML is broken.  You have the BoundColumn outside of the grid, and the column tag itself isn't closed.  Columns go inside the grid.  See the grid layout here.  Basically, you'd want something more like:

```<code><asp:GridView ID="GridView1" runat="server" BackColor="White"
              BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
              GridLines="Vertical">
    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="#DCDCDC" />
    <Columns>
        <asp:BoundField DataField="PCTPAX1"
                         HeaderText="PCTPAX1"
                         DataFormatString="{0:c}">
        </asp:BoundField>
    </Columns>
</asp:GridView>
</code>```

Body:
Dim pctofpax As New DataColumn
        pctofpax = New DataColumn("PCTPAX1", GetType(Decimal))
        pctofpax.Expression = "[ASOFPAX] / [YEPAX]"
        ds.Tables("workplease").Columns.Add(pctofpax)

        Dim avgppax As New DataColumn
        avgppax = New DataColumn("AVG PAX", GetType(Double))
        avgppax.Expression = "[Current Sales] / [Current PAX]"
        ds.Tables("workplease").Columns.Add(avgppax)

These are two columns that i added into my asp.net/vb.net datagrid. the problem is i keep trying to change the datatypes so they show up as numbers with only two decimals but it is not working

            Sales As Of Analysis

        <asp:GridView ID="GridView1" runat="server" BackColor="White"
            BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
            GridLines="Vertical">
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
        </asp:GridView>
    <asp:BoundColumn DataField="PCTPAX1"
                 HeaderText="PCTPAX1"
                 DataFormatString="{0:c}">

    </form>

and nothing happend to my data

Body:
If it's just a matter of displaying only two decimals, this can be accomplished in the display code for the DataGrid:

<asp:BoundField DataField="PCTPAX1"
                 HeaderText="PCTPAX1"
                 DataFormatString="{0:c}">

Note the DataFormatString value of {0:c} which specifies that the formatting of the value in that field should be "currency."  (You can also try with a capital C, I don't have a test handy for it right now.)  There's a lot more you can do with format strings, more information here.

Or do you want the actual values to be rounded to currency values?  You'll likely use Math.Round for that, though I don't have an example handy.  There's information about that here.

Edit: Based on your comment(s), it sounds like you were attempting to change data types at the database level.  This won't really impact the code.  The value coming back from the database in the form of a double or decimal or some other numeric likely won't carry that precision back to the code.  As far as the DataGrid is concerned, it's calling .ToString() on a double and showing the result.  No database data type is involved.  Using the DataFormatString property to pass a format string to the .ToString() method is how to change the display.

Edit again based on your question edit: Your HTML is broken.  You have the BoundColumn outside of the grid, and the column tag itself isn't closed.  Columns go inside the grid.  See the grid layout here.  Basically, you'd want something more like:

<asp:GridView ID="GridView1" runat="server" BackColor="White"
              BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
              GridLines="Vertical">
    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="#DCDCDC" />
    <Columns>
        <asp:BoundField DataField="PCTPAX1"
                         HeaderText="PCTPAX1"
                         DataFormatString="{0:c}">
        </asp:BoundField>
    </Columns>
</asp:GridView>


问:
how to debug when react native app doesnt start on ios device
when I start the react-native app, it always starts, as long as I have it connected to the mac.

As soon as I disconnect the iphone, the app mostly hangs on startup and crashes, without any further error messages.
But, other errors will show up on the screen (red and yellow flagged errors).

When I doubleclick the homebutton, strangely, the app seems to be in a started state, but I am not able to switch to it.

How can you debug best such a behavior and find the the things causing the strange startup behavior?

Update:

I found those errors

```<code>2016-08-08 16:25:23.604 [warn][tid:main][RCTEventEmitter.m:54] Sending `websocketFailed` with no listeners registered.
2016-08-08 16:25:23.612113 PhoenixApp[525:64778] Sending `websocketFailed` with no listeners registered.
2016-08-08 16:25:23.742 [warn][tid:com.facebook.react.JavaScript] The regenerator/runtime module is deprecated; please import regenerator-runtime/runtime instead.
2016-08-08 16:25:23.741927 PhoenixApp[525:65027] The regenerator/runtime module is deprecated; please import regenerator-runtime/runtime instead.
2016-08-08 16:25:23.860 [info][tid:com.facebook.react.JavaScript] Running application "PhoenixApp" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
2016-08-08 16:25:23.860251 PhoenixApp[525:65027] Running application "PhoenixApp" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
2016-08-08 16:25:24.139 [info][tid:com.facebook.react.JavaScript] null
2016-08-08 16:25:24.138808 PhoenixApp[525:65027] null
</code>```

followed by (each second)

```<code>2016-08-08 16:31:43.159749 PhoenixApp[525:64956] [] __nw_connection_get_connected_socket_block_invoke 176 Connection has no connected handler
2016-08-08 16:31:45.372329 PhoenixApp[525:65445] [] __nw_connection_get_connected_socket_block_invoke 177 Connection has no connected handler
2016-08-08 16:31:47.575208 PhoenixApp[525:64955] [] __nw_connection_get_connected_socket_block_invoke 178 Connection has no connected handler
2016-08-08 16:31:49.788935 PhoenixApp[525:65445] [] __nw_connection_get_connected_socket_block_invoke 179 Connection has no connected handler
2016-08-08 16:31:51.970877 PhoenixApp[525:64955] [] __nw_connection_get_connected_socket_block_invoke 180 Connection has no connected handler
2016-08-08 16:31:54.173791 PhoenixApp[525:65445] [] __nw_connection_get_connected_socket_block_invoke 181 Connection has no connected handler
</code>```

AppDelegate.m

```<code>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#import "AppDelegate.h"

#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  [[RCTBundleURLProvider sharedSettings] setDefaults];
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"PhoenixTrello"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end
</code>```

setup:

react-native-cli: 1.0.0
react-native: 0.32.0-rc.0
react: 15.3.0

Xcode 8 beta 4, iOS 10

答: I was seeing this error because the app was calling an API to get data from remote server and the device didn't have internet connection. The error went away when the device was connected to internet.</p>

Body:
when I start the react-native app, it always starts, as long as I have it connected to the mac.

As soon as I disconnect the iphone, the app mostly hangs on startup and crashes, without any further error messages.
But, other errors will show up on the screen (red and yellow flagged errors).

When I doubleclick the homebutton, strangely, the app seems to be in a started state, but I am not able to switch to it.

How can you debug best such a behavior and find the the things causing the strange startup behavior?

Update:

I found those errors

2016-08-08 16:25:23.604 [warn][tid:main][RCTEventEmitter.m:54] Sending `websocketFailed` with no listeners registered.
2016-08-08 16:25:23.612113 PhoenixApp[525:64778] Sending `websocketFailed` with no listeners registered.
2016-08-08 16:25:23.742 [warn][tid:com.facebook.react.JavaScript] The regenerator/runtime module is deprecated; please import regenerator-runtime/runtime instead.
2016-08-08 16:25:23.741927 PhoenixApp[525:65027] The regenerator/runtime module is deprecated; please import regenerator-runtime/runtime instead.
2016-08-08 16:25:23.860 [info][tid:com.facebook.react.JavaScript] Running application "PhoenixApp" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
2016-08-08 16:25:23.860251 PhoenixApp[525:65027] Running application "PhoenixApp" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
2016-08-08 16:25:24.139 [info][tid:com.facebook.react.JavaScript] null
2016-08-08 16:25:24.138808 PhoenixApp[525:65027] null

followed by (each second)

2016-08-08 16:31:43.159749 PhoenixApp[525:64956] [] __nw_connection_get_connected_socket_block_invoke 176 Connection has no connected handler
2016-08-08 16:31:45.372329 PhoenixApp[525:65445] [] __nw_connection_get_connected_socket_block_invoke 177 Connection has no connected handler
2016-08-08 16:31:47.575208 PhoenixApp[525:64955] [] __nw_connection_get_connected_socket_block_invoke 178 Connection has no connected handler
2016-08-08 16:31:49.788935 PhoenixApp[525:65445] [] __nw_connection_get_connected_socket_block_invoke 179 Connection has no connected handler
2016-08-08 16:31:51.970877 PhoenixApp[525:64955] [] __nw_connection_get_connected_socket_block_invoke 180 Connection has no connected handler
2016-08-08 16:31:54.173791 PhoenixApp[525:65445] [] __nw_connection_get_connected_socket_block_invoke 181 Connection has no connected handler

AppDelegate.m

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#import "AppDelegate.h"

#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  [[RCTBundleURLProvider sharedSettings] setDefaults];
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"PhoenixTrello"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end

setup:

react-native-cli: 1.0.0
react-native: 0.32.0-rc.0
react: 15.3.0

Xcode 8 beta 4, iOS 10


答:
Can main() function be called a constructor function

No

A class constructor is a member-funtion. A member function is different from a non-member function which int main() is.

Actually a Constructor is a special kind of member-function that has no name and no address. This is responsible for creating objects. Objects can be created an "infinite" number of times in your program.

While main() is the function that starts up your program and you are not permitted to call main() else you invoke Undefined Behavior

Body:
I want to know whether int main() function be called a constructor function since it nearly works same as a constructor function of a class?

And if yes, then what is the class name it belongs to?

Edit: The reason why I think main() works nearly same as constructor function is that whenever we execute a programme the first thing which gets executed is the main function.. Similarly a constructor function executes first whenever we define a  variable with data type as user defined class


问:
Pass individual elements of an array to a case statement in Ruby - LCD display numbers
I am trying to pass an array of numbers to a case statement.
For example: I ask the user to input a value, for example 12. Then I split it into an array [1,2]. I then pass it to my method case statement. My case statement is to output the digital format of 1 and 2.

My Issue:
I cannot get it to print more than an input of 1 element.
How can I output both the 1 and 2 as a digital number with 1 array? Or with a users input? Is my code far off?

My Code:

```<code>puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
x = x.split('')

def digital_number(n)

digits = n

#Start case for digit input
  case digits
  when ["1"]
  puts " | "
  puts "   "
  puts " | "
  puts "   "
  puts n

  when ["2"]
  puts " - "
  puts "  |"
  puts " - "
  puts "|  "
  puts " - "

  else
  puts "That is not an available number."

  end
end

digital_number(x)
</code>```

答:
This is very similar to Vasily Yudin's answer just with scan and the same as what he had also said in his comment. </p>

```<code>puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
@arr = []

def digital_number(n)

  #Start case for digit input
  case n
  when "1"
    @arr << " | "
    @arr << " | "
    puts n

  when "2"
    @arr << "-"
    @arr << " |"
    @arr << "-"
    @arr << "| "
    @arr << "-"
  else
    puts "That is not an available number."
  end
end

x.scan(/\w/).each{|d| digital_number(d)}
puts @arr.join(' ')
</code>```

Body:
I am trying to pass an array of numbers to a case statement.
For example: I ask the user to input a value, for example 12. Then I split it into an array [1,2]. I then pass it to my method case statement. My case statement is to output the digital format of 1 and 2.

My Issue:
I cannot get it to print more than an input of 1 element.
How can I output both the 1 and 2 as a digital number with 1 array? Or with a users input? Is my code far off?

My Code:

puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
x = x.split('')

def digital_number(n)

digits = n

#Start case for digit input
  case digits
  when ["1"]
  puts " | "
  puts "   "
  puts " | "
  puts "   "
  puts n

  when ["2"]
  puts " - "
  puts "  |"
  puts " - "
  puts "|  "
  puts " - "

  else
  puts "That is not an available number."

  end
end

digital_number(x)

Body:
This is very similar to Vasily Yudin's answer just with scan and the same as what he had also said in his comment.

puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
@arr = []

def digital_number(n)

  #Start case for digit input
  case n
  when "1"
    @arr << " | "
    @arr << " | "
    puts n

  when "2"
    @arr << "-"
    @arr << " |"
    @arr << "-"
    @arr << "| "
    @arr << "-"
  else
    puts "That is not an available number."
  end
end

x.scan(/\w/).each{|d| digital_number(d)}
puts @arr.join(' ')