问:
AppendMenu doesn't work when ModalPopupMode=pmAuto
In Delphi, i use the following line (and others, almost identical) to add items to the system menu of forms:

```<code>AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, cSetScreenResolution1024x768,  PChar('1024x768'));
</code>```

This is part of a class that all other forms inherit from, and it works fine most of the time, but I've noticed that when forms are opened in modal mode the custom menuitems aren't there. When the same form is opened in modeless mode it works just fine. I've spent some time figuring out why, and I have found that if ModalPopupMode=pmAuto I get this error. When it's pmNone, things work just fine.

Can anyone explain why this happens? And maybe give advise on how to solve it? I use ModalPopupMode=pmAuto to fix other issues, so it's not a good alternative to revert it to pmNone.

To reproduce, just make a small project with two forms. Drop two buttons on the first form, one to open the second form modally, one to open it modeless. Put this line into the second form's create:

```<code>AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, 10000,  PChar('1024x768'));
</code>```

It will now work as expected. Now set the applications ModalPopupMode to pmAuto, and observe that the extra menuitem on the systemmenu has disappeared when opening the form modally.

Alternatively (and maybe more conveniently?) copy these 5 "files":

PROJECT1.DPR

```<code>program Project1;

uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  Application.ModalPopupMode := pmAuto;
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.
</code>```

UNIT1.PAS

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TForm2.Create(nil) do
  try
    ShowModal;
  finally
    Free;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  with TForm2.Create(Application.Mainform) do
  begin
    show;
  end;
end;

end.
</code>```

UNIT1.DFM

```<code>object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 337
  ClientWidth = 635
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 8
    Top = 8
    Width = 75
    Height = 25
    Caption = 'Modal'
    TabOrder = 0
    OnClick = Button1Click
  end
  object Button2: TButton
    Left = 8
    Top = 39
    Width = 75
    Height = 25
    Caption = 'Modeless'
    TabOrder = 1
    OnClick = Button2Click
  end
end
</code>```

UNIT2.PAS

```<code>unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm2 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
  AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, 10000,  PChar('Test'));
end;

end.
</code>```

UNIT2.DFM

```<code>object Form2: TForm2
  Left = 0
  Top = 0
  Caption = 'Form2'
  ClientHeight = 337
  ClientWidth = 635
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
end
</code>```

答:
The constructor is not the place to manipulate a form's window handle. A control's handle may get re-created during the lifetime of the form.

You should only use the window handle after you know the form has a window handle. Override your form's CreateWnd method and put your AppendMenu code there. That method is called after the form's handle has been created, each time the form's handle is created, so you may see it called multiple times for the same form. Some property of your form is probably changing while it's being created modally, and that's causing the window to be re-created. In fact, your AppendMenu command might be exacerbating the problem by forcing the form to create its window before it's ready. (Reading the Handle property forces the handle into existence if it's not already there.)

Body:
In Delphi, i use the following line (and others, almost identical) to add items to the system menu of forms:

AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, cSetScreenResolution1024x768,  PChar('1024x768'));

This is part of a class that all other forms inherit from, and it works fine most of the time, but I've noticed that when forms are opened in modal mode the custom menuitems aren't there. When the same form is opened in modeless mode it works just fine. I've spent some time figuring out why, and I have found that if ModalPopupMode=pmAuto I get this error. When it's pmNone, things work just fine.

Can anyone explain why this happens? And maybe give advise on how to solve it? I use ModalPopupMode=pmAuto to fix other issues, so it's not a good alternative to revert it to pmNone.

To reproduce, just make a small project with two forms. Drop two buttons on the first form, one to open the second form modally, one to open it modeless. Put this line into the second form's create:

AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, 10000,  PChar('1024x768'));

It will now work as expected. Now set the applications ModalPopupMode to pmAuto, and observe that the extra menuitem on the systemmenu has disappeared when opening the form modally.

Alternatively (and maybe more conveniently?) copy these 5 "files":

PROJECT1.DPR

program Project1;

uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  Application.ModalPopupMode := pmAuto;
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

UNIT1.PAS

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TForm2.Create(nil) do
  try
    ShowModal;
  finally
    Free;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  with TForm2.Create(Application.Mainform) do
  begin
    show;
  end;
end;

end.

UNIT1.DFM

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 337
  ClientWidth = 635
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 8
    Top = 8
    Width = 75
    Height = 25
    Caption = 'Modal'
    TabOrder = 0
    OnClick = Button1Click
  end
  object Button2: TButton
    Left = 8
    Top = 39
    Width = 75
    Height = 25
    Caption = 'Modeless'
    TabOrder = 1
    OnClick = Button2Click
  end
end

UNIT2.PAS

unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm2 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
  AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, 10000,  PChar('Test'));
end;

end.

UNIT2.DFM

object Form2: TForm2
  Left = 0
  Top = 0
  Caption = 'Form2'
  ClientHeight = 337
  ClientWidth = 635
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
end


来源: stackexchange

问:
Vb.net webclient error : too many automatic redirections was attempted
This code was running just fine before , but since yesterday the error started to show up.
After reading many similar disscutions i though that my problem was about cookies so i add a CookieContainer but i still get the same error.
My code allows me to get pictures and their titles from a website and display them , here is my code:

Form 1 :

```<code>Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Dim websiteURL1 As String = "http://www.gamestop.com/collection/upcoming-video-games"
    Class1.getPics(websiteURL1, "<img src=""(?<Data>[^>]*)""><p>(?<Dataa>[^>]*)<br>")
    Me.AutoScroll = True
End Sub
</code>```

Class1 fucntion :

```<code>Public Shared Function getPics(website As String, pattern As String)
    Dim tempTitles As New List(Of String)()
    Dim tempTitles2 As New List(Of String)()
    Dim lestitres As New List(Of titlesclass)
    Dim webClient As New CookieAwareWebClient()
    webClient.Headers.Add("user-agent", "null")
    'If the website happens to go offline, at least your application wont crash.
    'Handle default proxy
    Dim proxy As IWebProxy = WebRequest.GetSystemWebProxy()
    proxy.Credentials = CredentialCache.DefaultCredentials
    webClient.Proxy = proxy

    Dim content As String = webClient.DownloadString(website)
    Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
                Select New With {Key .Link = String.Concat("http://www.gamestop.com", title.Groups("Data").Value),
                     Key .Title = title.Groups("Dataa").Value}

    Dim titles = tempTitles.Distinct().ToArray() 'remove duplicate titles
    Dim titles2 = lestitres.Distinct().ToArray()
    lestitres.Clear()
    'Count Items
    Dim item As Integer = 0
    'Count Row
    Dim row As Integer = 0
    'image: 222*122
    For Each letitre In query.Distinct
        Dim ImageInBytes() As Byte = webClient.DownloadData(letitre.Link)
        Dim ImageStream As New IO.MemoryStream(ImageInBytes)
        Dim MyPic As New PictureBox
        Dim MyLab As New Label
        'x = numéro item fois largeur image
        'y = numéro de ligne fois hauteur image
        MyPic.Location = New Point(item * 222, row * 122)
        MyLab.Location = New Point(item * 222, row * 122)
        MyPic.SizeMode = PictureBoxSizeMode.AutoSize
        MyLab.Text = letitre.Title
        MyPic.Image = New System.Drawing.Bitmap(ImageStream)
        Form2.Controls.Add(MyPic)
        Form2.Controls.Add(MyLab)
        'Bring Labels to front
        For Each ctrl As Control In Form2.Controls
            'If the control is of type button
            If TypeOf ctrl Is Label Then
                'Then disable it
                ctrl.BringToFront()
            End If
        Next
        'Increment the item count
        item = item + 1
        'If item is multiple of 4 or could check 4 then
        If item Mod 4 = 0 Then
            'Reset counter
            item = 0
            'Increment Row
            row = row + 1
        End If
    Next
End Function
</code>```

CookieContainer WebClient class :

```<code>    Imports System.Net
Imports System.Text.RegularExpressions
Public Class CookieAwareWebClient
    Inherits WebClient

    Private cc As New CookieContainer()
    Private lastPage As String

    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim R = MyBase.GetWebRequest(address)
        If TypeOf R Is HttpWebRequest Then
            With DirectCast(R, HttpWebRequest)
                .CookieContainer = cc
                If Not lastPage Is Nothing Then
                    .Referer = lastPage
                End If
            End With
        End If
        lastPage = address.ToString()
        Return R
    End Function
End Class
</code>```

答:
The website did add a new function which detect automatically the webclient location (country) and redirect them to another website , so in my case i set my webclient proxy to the USA so it can visit the link i want to without redirections.
To add the proxy settings you can use :

```<code>webclient1.Proxy = New WebProxy("YourProxyServerName", port)
</code>```

For exemple

```<code>webClient.Proxy = New WebProxy("100.12.34.36", 8080)
</code>```

Here is a list of free usa proxys :
https://www.us-proxy.org/

ContentLicense: CC BY-SA 3.0

Body:
This code was running just fine before , but since yesterday the error started to show up.
After reading many similar disscutions i though that my problem was about cookies so i add a CookieContainer but i still get the same error.
My code allows me to get pictures and their titles from a website and display them , here is my code:

Form 1 :

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Dim websiteURL1 As String = "http://www.gamestop.com/collection/upcoming-video-games"
    Class1.getPics(websiteURL1, "<img src=""(?<Data>[^>]*)"">
(?<Dataa>[^>]*)
")
    Me.AutoScroll = True
End Sub

Class1 fucntion :

Public Shared Function getPics(website As String, pattern As String)
    Dim tempTitles As New List(Of String)()
    Dim tempTitles2 As New List(Of String)()
    Dim lestitres As New List(Of titlesclass)
    Dim webClient As New CookieAwareWebClient()
    webClient.Headers.Add("user-agent", "null")
    'If the website happens to go offline, at least your application wont crash.
    'Handle default proxy
    Dim proxy As IWebProxy = WebRequest.GetSystemWebProxy()
    proxy.Credentials = CredentialCache.DefaultCredentials
    webClient.Proxy = proxy

    Dim content As String = webClient.DownloadString(website)
    Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
                Select New With {Key .Link = String.Concat("http://www.gamestop.com", title.Groups("Data").Value),
                     Key .Title = title.Groups("Dataa").Value}

    Dim titles = tempTitles.Distinct().ToArray() 'remove duplicate titles
    Dim titles2 = lestitres.Distinct().ToArray()
    lestitres.Clear()
    'Count Items
    Dim item As Integer = 0
    'Count Row
    Dim row As Integer = 0
    'image: 222*122
    For Each letitre In query.Distinct
        Dim ImageInBytes() As Byte = webClient.DownloadData(letitre.Link)
        Dim ImageStream As New IO.MemoryStream(ImageInBytes)
        Dim MyPic As New PictureBox
        Dim MyLab As New Label
        'x = numéro item fois largeur image
        'y = numéro de ligne fois hauteur image
        MyPic.Location = New Point(item * 222, row * 122)
        MyLab.Location = New Point(item * 222, row * 122)
        MyPic.SizeMode = PictureBoxSizeMode.AutoSize
        MyLab.Text = letitre.Title
        MyPic.Image = New System.Drawing.Bitmap(ImageStream)
        Form2.Controls.Add(MyPic)
        Form2.Controls.Add(MyLab)
        'Bring Labels to front
        For Each ctrl As Control In Form2.Controls
            'If the control is of type button
            If TypeOf ctrl Is Label Then
                'Then disable it
                ctrl.BringToFront()
            End If
        Next
        'Increment the item count
        item = item + 1
        'If item is multiple of 4 or could check 4 then
        If item Mod 4 = 0 Then
            'Reset counter
            item = 0
            'Increment Row
            row = row + 1
        End If
    Next
End Function

CookieContainer WebClient class :

    Imports System.Net
Imports System.Text.RegularExpressions
Public Class CookieAwareWebClient
    Inherits WebClient

    Private cc As New CookieContainer()
    Private lastPage As String

    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim R = MyBase.GetWebRequest(address)
        If TypeOf R Is HttpWebRequest Then
            With DirectCast(R, HttpWebRequest)
                .CookieContainer = cc
                If Not lastPage Is Nothing Then
                    .Referer = lastPage
                End If
            End With
        End If
        lastPage = address.ToString()
        Return R
    End Function
End Class

Body:
The website did add a new function which detect automatically the webclient location (country) and redirect them to another website , so in my case i set my webclient proxy to the USA so it can visit the link i want to without redirections.
To add the proxy settings you can use :

webclient1.Proxy = New WebProxy("YourProxyServerName", port)

For exemple

webClient.Proxy = New WebProxy("100.12.34.36", 8080)

Here is a list of free usa proxys :
https://www.us-proxy.org/


问:
ARKit - Issue with ARSession
I'm trying to create ARSession, using ARKit with Xcode 9 beta (for iOS 11). But it seems not working properly.

Code I've tried is:

```<code>override func viewDidLoad() {

    super.viewDidLoad()

    // configure session
    let configuration = ARWorldTrackingSessionConfiguration()
    configuration.planeDetection = .horizontal

    // run session
    sceneView.session.run(configuration)
}
</code>```

Can anyone help? Code is almost correct according to Apple Documentation.

答:
You have problem with View controller's life cycle. According to apple guideline for ARSession, it Session can after you view is loaded completely. I mean, user view will appear to run your session.

Here is apple document for the same: Building a Basic AR Experience

Also, look at following sample.

ContentLicense: CC BY-SA 4.0

Title: ARKit - Issue with ARSession

Body:
I'm trying to create ARSession, using ARKit with Xcode 9 beta (for iOS 11). But it seems not working properly.

Code I've tried is:

override func viewDidLoad() {

    super.viewDidLoad()

    // configure session
    let configuration = ARWorldTrackingSessionConfiguration()
    configuration.planeDetection = .horizontal

    // run session
    sceneView.session.run(configuration)
}

Can anyone help? Code is almost correct according to Apple Documentation.


问:
Bottom Navigation View not responsive
I need that BottomNavigationView to be responsive. When I use a Nexus 4 it has the exact measurement, but with Nexus 6 it does not. Any idea?</p>

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>
</code>```

答:
Set layout_height attribute to wrap_content instead of match_parent:

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" //modify this line
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>
</code>```

Title: Bottom Navigation View not responsive

Body:
I need that BottomNavigationView to be responsive. When I use a Nexus 4 it has the exact measurement, but with Nexus 6 it does not. Any idea?

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>

Body:
Set layout_height attribute to wrap_content instead of match_parent:

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" //modify this line
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>


问:
Installing R on Linux: configure: WARNING: you cannot build PDF versions of the R manuals
While configuring R on Debian GNU/Linux 8.8 (jessie) I am getting the warning above. Any ideas which package should be installed to solve the issue and have the manuals build as PDF?</p>

答:
A possible solution is to install LaTeX:

```<code>sudo apt-get install texlive
</code>```

This enables production of PDF but leaves a warning on missing sty files open:

```<code>configure: WARNING: neither inconsolata.sty nor zi4.sty found: PDF vignettes and package manuals will not be rendered optimally
</code>```

To solve the issue, install the extra fonts package to texlive

```<code>sudo apt-get install texlive-fonts-extra
</code>```

Body:
A possible solution is to install LaTeX:

sudo apt-get install texlive

This enables production of PDF but leaves a warning on missing sty files open:

configure: WARNING: neither inconsolata.sty nor zi4.sty found: PDF vignettes and package manuals will not be rendered optimally

To solve the issue, install the extra fonts package to texlive

sudo apt-get install texlive-fonts-extra


问:
Set accept and contentType to json by default for restassured
How could I set the accept and contentType to json projectwide in my rest tests?

```<code>    given()
        .accept(ContentType.JSON)
        .contentType(ContentType.JSON)
</code>```

This will reduce quite some repetitive code

答:
```<code>RestAssured.requestSpecification = new RequestSpecBuilder()
        .setContentType(ContentType.JSON)
        .setAccept(ContentType.JSON)
        .build();
</code>```

Body:
How could I set the accept and contentType to json projectwide in my rest tests?

    given()
        .accept(ContentType.JSON)
        .contentType(ContentType.JSON)

This will reduce quite some repetitive code


问:
OLEDB date(time) issue asp.net c#
I have written a little excel helper which works fine. It uses this connection string:

```<code>"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<FILENAME>;Extended Properties=\"Excel 12.0;HDR=Yes;\";";
</code>```

Unfortunately when I deploy the code, cells, which contains a date string like this: 28/12/2008 are returned as: 12/25/2008 12:00:00 AM rather than 25/12/2008 00:00:00 after using ToString. I adjusted the time zone etc. of the machine (all machines are now UK time zones) but this hasn't changed anything. I am just curious what determines how OLEDB 'behaves'. The aim would be to get 25/12/2008 00:00:00 on both machines.

Thanks!

Christian

答: The machines may need to have their locale settings changed, and not just the timezone settings. I believe they are separate.</p>

ContentLicense: CC BY-SA 2.5

Title: OLEDB date(time) issue asp.net c#

Body:
I have written a little excel helper which works fine. It uses this connection string:

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<FILENAME>;Extended Properties=\"Excel 12.0;HDR=Yes;\";";

Unfortunately when I deploy the code, cells, which contains a date string like this: 28/12/2008 are returned as: 12/25/2008 12:00:00 AM rather than 25/12/2008 00:00:00 after using ToString. I adjusted the time zone etc. of the machine (all machines are now UK time zones) but this hasn't changed anything. I am just curious what determines how OLEDB 'behaves'. The aim would be to get 25/12/2008 00:00:00 on both machines.

Thanks!

Christian


问:
backpack for laravel column width
Is it possible to reduce columns width for certain columns in backpack crud for laravel, is there any attribute in add columns that allows that?

On the image displayed , i want to swap the 1s for glyphicon-ok, but i can't find a way to do it

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

    $this->crud->setModel("App\ReporteParamEstacion");
    $this->crud->setRoute("admin/reporte_paramestacion");
    // $this->crud->setRouteName("crud.reportes.listado_importacion");
    $this->crud->setEntityNameStrings('parametro estacion', 'parametro estaciones');
    $this->crud->enableExportButtons();
    $this->crud->removeAllButtons();

     $this->crud->addColumn([
     'name' => 'nombre',
     'label' =>'Estacion',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'nombre_comuna',
     'label' =>'Comuna',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'MP10',
     'label' =>'MP10',
     'type' => 'text'

    ]);

    $this->crud->addColumn([
     'name' => 'MP25',
     'label' =>'MP25',
     'type' => 'text'

    ]);

    $this->crud->addColumn([
     'name' => 'SO2',
     'label' =>'SO2',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'NO2',
     'label' =>'NO2',
     'type' => 'text'
    ]);

     $this->crud->addColumn([
     'name' => 'CO',
     'label' =>'CO',
     'type' => 'text'

    ]);

    $this->crud->addColumn([
     'name' => 'O3',
     'label' =>'O3',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'BC',
     'label' =>'BC',
     'type' => 'text'
    ]);

     $this->crud->addColumn([
     'name' => 'NOX',
     'label' =>'NOX',
     'type' => 'text'
    ]);
 }
</code>```

thanks in advance

答:
Set type to "check" like this:

[
   'name' => 'mp10', // The db column name
   'label' => "MP10", // Table column heading
   'type' => 'check'
]

Title: backpack for laravel column width

Body:
Is it possible to reduce columns width for certain columns in backpack crud for laravel, is there any attribute in add columns that allows that?

On the image displayed , i want to swap the 1s for glyphicon-ok, but i can't find a way to do it

public function setup(){

    $this->crud->setModel("App\ReporteParamEstacion");
    $this->crud->setRoute("admin/reporte_paramestacion");
    // $this->crud->setRouteName("crud.reportes.listado_importacion");
    $this->crud->setEntityNameStrings('parametro estacion', 'parametro estaciones');
    $this->crud->enableExportButtons();
    $this->crud->removeAllButtons();

     $this->crud->addColumn([
     'name' => 'nombre',
     'label' =>'Estacion',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'nombre_comuna',
     'label' =>'Comuna',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'MP10',
     'label' =>'MP10',
     'type' => 'text'

    ]);

    $this->crud->addColumn([
     'name' => 'MP25',
     'label' =>'MP25',
     'type' => 'text'

    ]);

    $this->crud->addColumn([
     'name' => 'SO2',
     'label' =>'SO2',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'NO2',
     'label' =>'NO2',
     'type' => 'text'
    ]);

     $this->crud->addColumn([
     'name' => 'CO',
     'label' =>'CO',
     'type' => 'text'

    ]);

    $this->crud->addColumn([
     'name' => 'O3',
     'label' =>'O3',
     'type' => 'text'
    ]);

    $this->crud->addColumn([
     'name' => 'BC',
     'label' =>'BC',
     'type' => 'text'
    ]);

     $this->crud->addColumn([
     'name' => 'NOX',
     'label' =>'NOX',
     'type' => 'text'
    ]);
 }

thanks in advance


问:
Not updating value in database instead Inserting new entry
I am using below code to update database and putting where clause for date

```<code> ContentValues values = new ContentValues();
    values.put(DBTransactions.USER_ID_KEY, userId);
    values.put(DBTransactions.DATE_KEY, date);
    values.put(DBTransactions.DAY_KEY, day);
    values.put(DBTransactions.GOAL_KEY, dailyGoal);
    values.put(DBTransactions.VOLUME_KEY, dailyVolume);
    values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
    db.getWritableDatabase().update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ?", new String[]{date});
    closeDB();
</code>```

am I wrong somewhere in putting where clause? Its not updating database, Its creating new entry in database.

Its not updating database.
Thanks in Advance

答:
Use below code to update your table:

```<code>SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(DBTransactions.USER_ID_KEY, userId);
values.put(DBTransactions.DATE_KEY, date);
values.put(DBTransactions.DAY_KEY, day);
values.put(DBTransactions.GOAL_KEY, dailyGoal);
values.put(DBTransactions.VOLUME_KEY, dailyVolume);
values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);

db.update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ? ", new String[]{String.valueOf(date)});

closeDB();
</code>```

Body:
I am using below code to update database and putting where clause for date

 ContentValues values = new ContentValues();
    values.put(DBTransactions.USER_ID_KEY, userId);
    values.put(DBTransactions.DATE_KEY, date);
    values.put(DBTransactions.DAY_KEY, day);
    values.put(DBTransactions.GOAL_KEY, dailyGoal);
    values.put(DBTransactions.VOLUME_KEY, dailyVolume);
    values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
    db.getWritableDatabase().update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ?", new String[]{date});
    closeDB();

am I wrong somewhere in putting where clause? Its not updating database, Its creating new entry in database.

Its not updating database.
Thanks in Advance

Body:
Use below code to update your table:

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(DBTransactions.USER_ID_KEY, userId);
values.put(DBTransactions.DATE_KEY, date);
values.put(DBTransactions.DAY_KEY, day);
values.put(DBTransactions.GOAL_KEY, dailyGoal);
values.put(DBTransactions.VOLUME_KEY, dailyVolume);
values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);

db.update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ? ", new String[]{String.valueOf(date)});

closeDB();


问:
Webdriver wait for driver.current.url
I have the following code which is working fine. But when I tried to remove the sleep from the below code I am getting the assert failure error. Can someone please suggest me how I can use WebDriverWait for self.driver.current.url i.e for validating assert.

```<code>ele = WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//button[""@aria-label='Add Device Model']")))
ele.click()
sleep(5)
self.assertEqual(True, ("adddevicemodel" in self.driver.current_url))
</code>```

答:
Java and C# has already implemented ExpectedConditions for url. My guess is its only a meter of time until Python catches up. In the meantime you can use your on implementation

```<code>class wait_url_to_contain(object):
    def __init__(self, _text):
        self.text = _text

    def __call__(self, driver):
        return self.text in driver.current_url

wait = WebDriverWait(self.driver, 30)
ele = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[""@aria-label='Add Device Model']")))
ele.click()
wait.until(wait_url_to_contain("adddevicemodel"))
self.assertEqual(True, ("adddevicemodel" in self.driver.current_url))
</code>```

Title: Webdriver wait for driver.current.url

Body:
I have the following code which is working fine. But when I tried to remove the sleep from the below code I am getting the assert failure error. Can someone please suggest me how I can use WebDriverWait for self.driver.current.url i.e for validating assert.

ele = WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//button[""@aria-label='Add Device Model']")))
ele.click()
sleep(5)
self.assertEqual(True, ("adddevicemodel" in self.driver.current_url))

Body:
Java and C# has already implemented ExpectedConditions for url. My guess is its only a meter of time until Python catches up. In the meantime you can use your on implementation

class wait_url_to_contain(object):
    def __init__(self, _text):
        self.text = _text

    def __call__(self, driver):
        return self.text in driver.current_url

wait = WebDriverWait(self.driver, 30)
ele = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[""@aria-label='Add Device Model']")))
ele.click()
wait.until(wait_url_to_contain("adddevicemodel"))
self.assertEqual(True, ("adddevicemodel" in self.driver.current_url))


问:
Comparing data and dates in plsql
I have a table as:

```<code>date_stmp     ticker_name    a_clos_prc   b_clos_prc
05/20/17      APPL           $300.60      $300.60
05/21/17      APPL                        $300.61
</code>```

Is there a way to check to see IF b_clos_prc is the same as the day before if a_clos_prc is missing data AND b_clos_prc has data?

So for the example, the result would look like this:

```<code> date_stmp   ticker_name     a_clos_prc   b_clos_prc   Diff
 05/20/17    APPL            $300.60      $300.60
 05/21/17    APPL                         $300.61     +0.01
</code>```

I am stuck on how to come up with the logic for this.

答:
```<code>select *
  from table a2, table a1
 where trunc(a1.date_stmp) - 1 = trunc(a2.date_stmp)
   and (a1.a_clos_prc = a2.b_clos_prc  or (a1.a_clos_prc is null and  a2.b_clos_prc is null ))
</code>```

Title: Comparing data and dates in plsql

Body:
I have a table as:

date_stmp     ticker_name    a_clos_prc   b_clos_prc
05/20/17      APPL           $300.60      $300.60
05/21/17      APPL                        $300.61

Is there a way to check to see IF b_clos_prc is the same as the day before if a_clos_prc is missing data AND b_clos_prc has data?

So for the example, the result would look like this:

 date_stmp   ticker_name     a_clos_prc   b_clos_prc   Diff
 05/20/17    APPL            $300.60      $300.60
 05/21/17    APPL                         $300.61     +0.01

I am stuck on how to come up with the logic for this.


问:
unsupported operand type(s) for ** or pow(): 'str' and 'int' with Python3
My Python3 code

```<code>def ask():

    while True:
        try:
            n = input('Input an integer: ')
        except:
            print ('An error occurred! Please try again!')
            continue
        else:
            break

    print ('Thank you, you number squared is: ', n**2)
</code>```

Why do I got error if I want to take a square of number?

```<code>unsupported operand type(s) for ** or pow(): 'str' and 'int'
</code>```

From command line no problems

```<code>>>> 3**2
9
</code>```

答: input returns a string; ** requires 2 numbers.

Body:
My Python3 code

def ask():

    while True:
        try:
            n = input('Input an integer: ')
        except:
            print ('An error occurred! Please try again!')
            continue
        else:
            break

    print ('Thank you, you number squared is: ', n**2)

Why do I got error if I want to take a square of number?

unsupported operand type(s) for ** or pow(): 'str' and 'int'

From command line no problems

>>> 3**2
9


问:
I want to use substring and get values according to my pattern
```<code>select substr(e.orgmessage, 40, 50) as one,
       orgmessage as original_message
  from table
</code>```

The result in the column one is:

```<code>00 02182 00363 00008 O    PKR      500 01983 00319
</code>```

but the original string is:

```<code>09:22:12 CASH COUNTERS(C)    PKR     1000 02182 00363 00008 O    PKR      500 01983 00319 00315 O    ***        0 00000 00000 00000 N    ***        0 00000 00000 00000 N
</code>```

I am unable to get substring to return what I want.  I want values like 500 and 1000.  The data type of the field is VARCHAR2(1000 Byte).

答: Use INSTR to find the position of the substring in the source string, then use substr to parse it out from that position.</p>

Body:
select substr(e.orgmessage, 40, 50) as one,
       orgmessage as original_message
  from table

The result in the column one is:

00 02182 00363 00008 O    PKR      500 01983 00319

but the original string is:

09:22:12 CASH COUNTERS(C)    PKR     1000 02182 00363 00008 O    PKR      500 01983 00319 00315 O    ***        0 00000 00000 00000 N    ***        0 00000 00000 00000 N

I am unable to get substring to return what I want.  I want values like 500 and 1000.  The data type of the field is VARCHAR2(1000 Byte).


问:
Page didn't redirect in Angularjs
I've created an authentication process with firebase and angularjs.

After the authentication process, the page must redirect to the htmlnew.html Using $routeprovider. But it doesn't redirect after authentication.

index.html

```<code><html ng-app="appName">
 <body>
 <div ng-controller="loginCtrl" id="message">
    <a ng-click="googleSignin()">SignIn into App</a>
 </div>
   <p id="load">Firebase SDK Loading…</p>
 </body>
</html>
</code>```

htmlnew.html

```<code><body>
<div id="message" ng-controller="loginpage">
    <h1>Welcome</h1>
    <a ng-click="googleSignout()">Signout</a>
</div>
</body>
</code>```

app.js

```<code> var app = angular.module("appName", ["ngRoute", "firebase"]);
 app.config(function ($routeProvider) {
 $routeProvider
    .when("/", {
        templateUrl: 'public/index.html',
        controller: 'loginCtrl'
    })
    .when('/login', {
        templateUrl: 'public/htmlnew.html',
        controller: 'loginpage'
    })
  });

  app.controller('loginCtrl', function ($scope) {
  var provider = new firebase.auth.GoogleAuthProvider();
  $scope.googleSignin = function () {
  firebase.auth()
        .signInWithPopup(provider).then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    console.log(token);
    console.log(user);

  }).catch(function (error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorCode);
    console.log(errorMessage);
    });
   }
 });

 app.controller('loginpage', function ($scope) {
 $scope.googleSignout = function () {
  firebase.auth().signOut()
        .then(function () {
            console.log('Signout Succesfull');
        }, function (error) {
            console.log('Signout Failed');
        });
   }
 });
</code>```

Project documentation

For demo check on this Project link

Thanks in advance

答:
```<code>firebase.auth()
        .signInWithPopup(provider).then(function (result) {

    var token = result.credential.accessToken;
    var user = result.user;

     // You missed this $location.path('/pathYouNeed ');
</code>```

Title: Page didn't redirect in Angularjs

Body:
I've created an authentication process with firebase and angularjs.

After the authentication process, the page must redirect to the htmlnew.html Using $routeprovider. But it doesn't redirect after authentication.

index.html

    SignIn into App

Firebase SDK Loading…

htmlnew.html

Welcome

    Signout

app.js

 var app = angular.module("appName", ["ngRoute", "firebase"]);
 app.config(function ($routeProvider) {
 $routeProvider
    .when("/", {
        templateUrl: 'public/index.html',
        controller: 'loginCtrl'
    })
    .when('/login', {
        templateUrl: 'public/htmlnew.html',
        controller: 'loginpage'
    })
  });

  app.controller('loginCtrl', function ($scope) {
  var provider = new firebase.auth.GoogleAuthProvider();
  $scope.googleSignin = function () {
  firebase.auth()
        .signInWithPopup(provider).then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    console.log(token);
    console.log(user);

  }).catch(function (error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorCode);
    console.log(errorMessage);
    });
   }
 });

 app.controller('loginpage', function ($scope) {
 $scope.googleSignout = function () {
  firebase.auth().signOut()
        .then(function () {
            console.log('Signout Succesfull');
        }, function (error) {
            console.log('Signout Failed');
        });
   }
 });

Project documentation

For demo check on this Project link

Thanks in advance


问:
how to make vertical animation like feedly android app
i am using vertical viewpager but it is not smooth like feedly android app.I dont know what component is used by feedly.

Any help will be appreciated.

public class VerticalViewPager extends ViewPager {

```<code>public VerticalViewPager(Context context) {
    super(context);
    init();
}

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

private void init() {
    // The majority of the magic happens here
    setPageTransformer(true, new VerticalPageTransformer());
    // The easiest way to get rid of the overscroll drawing that happens on the left and right
    setOverScrollMode(OVER_SCROLL_NEVER);
}

private class VerticalPageTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = .75f;
    @Override
    public void transformPage(View view, float position) {

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        }  else if (position <= 0) { // [-1,0]
            // Use the default slide transition when moving to the left page
            view.setAlpha(1);
            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            //set Y position to swipe in from top
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);
            view.setScaleX(1);
            view.setScaleY(1);

        } else if (position <= 1) { // [0,1]
            view.setAlpha(1);

            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            // Scale the page down (between MIN_SCALE and 1)
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}

/*private class VerticalPageTransformer implements ViewPager.PageTransformer {

    @Override
    public void transformPage(View view, float position) {

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        } else if (position <= 1) { // [-1,1]
            view.setAlpha(1);

            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            //set Y position to swipe in from top
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}*/

/**
 * Swaps the X and Y coordinates of your touch event.
 */
private MotionEvent swapXY(MotionEvent ev) {
    float width = getWidth();
    float height = getHeight();

    float newX = (ev.getY() / height) * width;
    float newY = (ev.getX() / width) * height;

    ev.setLocation(newX, newY);

    return ev;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
    boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
    swapXY(ev); // return touch coordinates to original reference frame for any child views
    return intercepted;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    //return super.onTouchEvent(swapXY(ev));
    final boolean toHandle = super.onTouchEvent(swapXY(ev));
    // Return MotionEvent to normal
    swapXY(ev);
    return toHandle;
}

@Override
public boolean canScrollVertically(int direction) {
    return true;
}

@Override
public boolean canScrollHorizontally(int direction) {
    return false;
}
</code>```

}

答:
I think you have to go with this link , i think in your xml two scroll function is calling and that's why it gives issue .</p>

```<code>https://stackoverflow.com/questions/14326317/view-pager-not-smooth-when-embedded-within-scrollview
</code>```

Body:
i am using vertical viewpager but it is not smooth like feedly android app.I dont know what component is used by feedly.

Any help will be appreciated.

public class VerticalViewPager extends ViewPager {

public VerticalViewPager(Context context) {
    super(context);
    init();
}

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

private void init() {
    // The majority of the magic happens here
    setPageTransformer(true, new VerticalPageTransformer());
    // The easiest way to get rid of the overscroll drawing that happens on the left and right
    setOverScrollMode(OVER_SCROLL_NEVER);
}

private class VerticalPageTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = .75f;
    @Override
    public void transformPage(View view, float position) {

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        }  else if (position <= 0) { // [-1,0]
            // Use the default slide transition when moving to the left page
            view.setAlpha(1);
            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            //set Y position to swipe in from top
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);
            view.setScaleX(1);
            view.setScaleY(1);

        } else if (position <= 1) { // [0,1]
            view.setAlpha(1);

            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            // Scale the page down (between MIN_SCALE and 1)
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}

/*private class VerticalPageTransformer implements ViewPager.PageTransformer {

    @Override
    public void transformPage(View view, float position) {

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        } else if (position <= 1) { // [-1,1]
            view.setAlpha(1);

            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            //set Y position to swipe in from top
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}*/

/**
 * Swaps the X and Y coordinates of your touch event.
 */
private MotionEvent swapXY(MotionEvent ev) {
    float width = getWidth();
    float height = getHeight();

    float newX = (ev.getY() / height) * width;
    float newY = (ev.getX() / width) * height;

    ev.setLocation(newX, newY);

    return ev;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
    boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
    swapXY(ev); // return touch coordinates to original reference frame for any child views
    return intercepted;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    //return super.onTouchEvent(swapXY(ev));
    final boolean toHandle = super.onTouchEvent(swapXY(ev));
    // Return MotionEvent to normal
    swapXY(ev);
    return toHandle;
}

@Override
public boolean canScrollVertically(int direction) {
    return true;
}

@Override
public boolean canScrollHorizontally(int direction) {
    return false;
}

}

Body:
I think you have to go with this link , i think in your xml two scroll function is calling and that's why it gives issue .

https://stackoverflow.com/questions/14326317/view-pager-not-smooth-when-embedded-within-scrollview


问:
codeigniter session destroy two different application
For example i am using two admin panel.Once I destroy all session value through one admin panel, another one admin session value also will destroyed . I am using unset and session_destroy for both admin panel. Is this any way to prevent one another

答: if you are using both panel in the same broswer. Then it will be destroyed. Using different browser might help. That's how session are made to work.</p>


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答:
Java doesn't have the concept of a "count" of the used elements in an array.

To get this, Java uses an ArrayList.  The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20).  To get rid of the extra capacity, you use mylist.trimToSize().

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?


问:
Xcode 9 Simulator side buttons
What is the purpose of side buttons on Xcode 9 Simulator?

答:
From the Help Viewer of the Simulator

Does nobody use the Help at all ? ...

Title: Xcode 9 Simulator side buttons


问:
How to Retrieve a Listing of Employee's Superiors in SQL
Essentially, I have a table that lists an employee's number and the employeeNumber of who they report to.

```<code> EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532
</code>```

Etc. Etc. So Dong Wong's hierarchy would be: He reports to -> 1532 which reports to -> 3245 which reports to -> 1234.

(I'm new to SQL, so clean and understandable solutions would be appreciated)

答:
By doing a join...

```<code>select e1.EmpNum, e1.name, e2.EmpNum as BossNum, e2.name as BossName from empTable e1 join empTable e2 on e1.ReportsTo=e2.EmpNum
</code>```

The join can then be as long as you want, e3, e4... But doing it programatically is probably easier in the front end.

Body:
Essentially, I have a table that lists an employee's number and the employeeNumber of who they report to.

 EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532

Etc. Etc. So Dong Wong's hierarchy would be: He reports to -> 1532 which reports to -> 3245 which reports to -> 1234.

(I'm new to SQL, so clean and understandable solutions would be appreciated)

Body:
By doing a join...

select e1.EmpNum, e1.name, e2.EmpNum as BossNum, e2.name as BossName from empTable e1 join empTable e2 on e1.ReportsTo=e2.EmpNum

The join can then be as long as you want, e3, e4... But doing it programatically is probably easier in the front end.


答: because the height is matching_parent!! so it depends of how the parent is composed and adapting the views, for this case is better to have a fix value width or setup to wrap_content but then you have to take care of size of icons! </p>

Title: Bottom Navigation View not responsive

Body:
I need that BottomNavigationView to be responsive. When I use a Nexus 4 it has the exact measurement, but with Nexus 6 it does not. Any idea?

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>


问:
preventDefault() seems to disable entire form?
I have a very simple form:

```<code><form id="formRegister">
    ....
    <input autocomplete="off" class="form-control input-sm required " id="Code" maxlength="10" name="Code" placeholder="VIP Code" style="width:150px;" type="text" value="">
    ....
    <button id="btnVIPCodeLookup" type="submit" class="button-primary">Submit<i class="icon"></i></button>
</form>
</code>```

And here's the script behind it:

```<code>// Landing page form submit
$("#formRegister").submit(function (e) {
    e.preventDefault();
    var code = $('#Code').val();
    vipLookup(code);
});

function vipLookup(code) {
    showBusy();
    $.getJSON("/EventRegistration/EventRegistrationCodeLookUp", { code: code }, function (data) {
        hideBusy();
        if (data.Result == "true") {
            $('#CodeResultSpan').text('');
            $('#EncryptedCode').val(data.EncryptedVIPCode);
            ShowLegal();
        }
        else
        {
            if (data.Result == "false") {
                $('#CodeResultSpan').text('VIP Code not found. Please check the VIP Code you received and try again.');
            }
            if (data.Result == "used") {
                $('#CodeResultSpan').text('VIP Code has been used.');
            }
            if (data.Result == "error") {
                $('#CodeResultSpan').text('There was an error while looking up your VIP Code.  Please try again.');
            }
            if (data.Result == "canceled") {
                $('#CodeResultSpan').text('This VIP Code has been canceled.');
            }
            $('#Code').css('border-bottom', '1px solid #e03e3e');
        }
    });
}
</code>```

The weird thing that I am seeing in some browsers (especially any iOS device, or when emulating an iOS device in Chrome), is that after the button is clicked, the form becomes disabled.  I can't refocus into the textbox, and I can't click the button again.

If I remove e.preventDefault(); then the problem goes away, but this of course creates a new problem in that the page is refreshed, and the error messages vanishes.

You can see this in action here:

http://dev.walkup.audidriveusa.com/EventRegistration

Using Chrome, just type anything into the text box and click 'Submit'. You'll see the message.  Then (if you can) change the text, and try to click 'Submit' again.  It doesn't let you.

答:
Your problem is; your error div that after getting the ajax request overlaps the form in mobile browsers as you see in image below.

You can use;

```<code>margin-top:20px;
</code>```

for your error div. After solved that, just use the

```<code>return false;
</code>```

instead of

```<code>e.preventDefault();
</code>```

beacuse Mobile browsers don't have a click event. You need to use touchstart or touchend.

Full Code

```<code>$("#formRegister").submit(function (e) {
    var code = $('#Code').val();
    vipLookup(code);
    return false;
});
</code>```

Also there are a lot of question about the e.preventDefault on mobile browsers in SO.

Mobile Safari preventDefault() not working? Android works fine

e.PreventDefault() & e.stopPropogation() not working on tablet & mobile

Body:
I have a very simple form:

<form id="formRegister">
    ....
    <input autocomplete="off" class="form-control input-sm required " id="Code" maxlength="10" name="Code" placeholder="VIP Code" style="width:150px;" type="text" value="">
    ....
    <button id="btnVIPCodeLookup" type="submit" class="button-primary">Submit</button>
</form>

And here's the script behind it:

// Landing page form submit
$("#formRegister").submit(function (e) {
    e.preventDefault();
    var code = $('#Code').val();
    vipLookup(code);
});

function vipLookup(code) {
    showBusy();
    $.getJSON("/EventRegistration/EventRegistrationCodeLookUp", { code: code }, function (data) {
        hideBusy();
        if (data.Result == "true") {
            $('#CodeResultSpan').text('');
            $('#EncryptedCode').val(data.EncryptedVIPCode);
            ShowLegal();
        }
        else
        {
            if (data.Result == "false") {
                $('#CodeResultSpan').text('VIP Code not found. Please check the VIP Code you received and try again.');
            }
            if (data.Result == "used") {
                $('#CodeResultSpan').text('VIP Code has been used.');
            }
            if (data.Result == "error") {
                $('#CodeResultSpan').text('There was an error while looking up your VIP Code.  Please try again.');
            }
            if (data.Result == "canceled") {
                $('#CodeResultSpan').text('This VIP Code has been canceled.');
            }
            $('#Code').css('border-bottom', '1px solid #e03e3e');
        }
    });
}

The weird thing that I am seeing in some browsers (especially any iOS device, or when emulating an iOS device in Chrome), is that after the button is clicked, the form becomes disabled.  I can't refocus into the textbox, and I can't click the button again.

If I remove e.preventDefault(); then the problem goes away, but this of course creates a new problem in that the page is refreshed, and the error messages vanishes.

You can see this in action here:

http://dev.walkup.audidriveusa.com/EventRegistration

Using Chrome, just type anything into the text box and click 'Submit'. You'll see the message.  Then (if you can) change the text, and try to click 'Submit' again.  It doesn't let you.

Body:
Your problem is; your error div that after getting the ajax request overlaps the form in mobile browsers as you see in image below.

You can use;

margin-top:20px;

for your error div. After solved that, just use the

return false;

instead of

e.preventDefault();

beacuse Mobile browsers don't have a click event. You need to use touchstart or touchend.

Full Code

$("#formRegister").submit(function (e) {
    var code = $('#Code').val();
    vipLookup(code);
    return false;
});

Also there are a lot of question about the e.preventDefault on mobile browsers in SO.

Mobile Safari preventDefault() not working? Android works fine

e.PreventDefault() & e.stopPropogation() not working on tablet & mobile


问:
How to send HTTP error from http-proxy?
Is it possible in http-proxy to do not forward requests to the server, but at once return a response with some error code, for example with 401 Unauthorized?

I need analyze request body and in some cases do not forward requests to the server.

is it possible to do at all?

Or http-proxy can only modify request and response, but request always should be forwarded to the server?

答:
you can try doing it this way:</p>

```<code>const server = http.createServer((req, res) => {
    if(/*your auth check*/){
        //return the 401 error
    }
    //auth check is passed, pass the request to the proxy
    proxy.web(req, res, { target: 'http://your.target' });
});
</code>```

Title: How to send HTTP error from http-proxy?

Body:
you can try doing it this way:

const server = http.createServer((req, res) => {
    if(/*your auth check*/){
        //return the 401 error
    }
    //auth check is passed, pass the request to the proxy
    proxy.web(req, res, { target: 'http://your.target' });
});


问:
Access Not Configured. +1 API
I'm trying to get shares counts from Google+ using the Google+ API and catch only error:

Access Not Configured. +1 API has not been used in project 383866521277 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/pos.googleapis.com/overview?project=383866521277 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

After that I visit recommended link and catch pos.googleapis.com not found. How to enable this API?

答:
In order to access Google APIs you need to register your application on Google developer console.   You have probably already created your credentials.  The API key or Oauth2 credentials you created identifies the application to Google.  The project that was used to create the API key or Oauth2 credentials you are using must have the Google+ API enabled.

Enable API:

What you have forgotten to do is to tell Google which APis you will be accessing.  On the Left hand side look for "Library"  find the Google+ api and enable it.

Error pos.googleapis.com

Means that you do not have access to the project 383866521277 or it was deleted.  The person who created the project must enable the Google+ api for you.  Remember this is denoted by the The API key or Oauth2 credentials you created and are using in your code.

Title: Access Not Configured. +1 API


问:
R Shiny App - window opens with no content
this is a quite weird issue which I was unable to solve with the support of prof.google.
When I start a Shiny App, the window (or alternatively the browser) open up but
- in case of the RStudio window: no content is shown
- in case of the IE: loading for 30 sec, then "page cannot be displayed" error

When I try to log, using

```<code>options(shiny.reactlog=TRUE)
<starting app here>
showReactLog()
</code>```

the HTML page for the log opens with no content.
I assume, it could be a Java issue (I am using Java 32bit, version 8, update 111)

Any support would be highly appreciated.

All the best; G

ps:
R version used: 3.3.1
shiny package 0.14.1
app used:

```<code>runExample("01_hello")
</code>```

答:
First find out where the 01_hello app is kept on your computer by using the following command in a R console:

```<code>system.file("examples", package="shiny")
</code>```

The output might like this:

```<code>"/Library/Frameworks/R.framework/Versions/3.3/Resources/library/shiny/examples"
</code>```

That is how it looked on my computer. Next, navigate to the examples directory and cd into the 01_hello app subdirectory. Then open either the ui.R or server.R file in the 01_hello subdirectory and place the following code at the top of the opened file:

```<code>options(shiny.reactlog=TRUE)
</code>```

Save the file and go back to R. The reactive log visualizer should now work when you use the following commands:

```<code>library(shiny)
runExample("01_hello")
showReactLog()
</code>```

After the second command you should stop the app to get your console back. Everything gets saved in the reactive log but only for the session. The more times you stop and start the example app or any other app, the more information the reactive log will contain.

A browser window will open with the reactive log visualizer that you can navigate using the left and right keys on your keyboard:

Body:
this is a quite weird issue which I was unable to solve with the support of prof.google.
When I start a Shiny App, the window (or alternatively the browser) open up but
- in case of the RStudio window: no content is shown
- in case of the IE: loading for 30 sec, then "page cannot be displayed" error

When I try to log, using

options(shiny.reactlog=TRUE)
<starting app here>
showReactLog()

the HTML page for the log opens with no content.
I assume, it could be a Java issue (I am using Java 32bit, version 8, update 111)

Any support would be highly appreciated.

All the best; G

ps:
R version used: 3.3.1
shiny package 0.14.1
app used:

runExample("01_hello")

Body:
First find out where the 01_hello app is kept on your computer by using the following command in a R console:

system.file("examples", package="shiny")

The output might like this:

"/Library/Frameworks/R.framework/Versions/3.3/Resources/library/shiny/examples"

That is how it looked on my computer. Next, navigate to the examples directory and cd into the 01_hello app subdirectory. Then open either the ui.R or server.R file in the 01_hello subdirectory and place the following code at the top of the opened file:

options(shiny.reactlog=TRUE)

Save the file and go back to R. The reactive log visualizer should now work when you use the following commands:

library(shiny)
runExample("01_hello")
showReactLog()

After the second command you should stop the app to get your console back. Everything gets saved in the reactive log but only for the session. The more times you stop and start the example app or any other app, the more information the reactive log will contain.

A browser window will open with the reactive log visualizer that you can navigate using the left and right keys on your keyboard:


问:
ASP.NET Cannot Find MySQL Host Even Though I'm Not Using MySQL
I am trying to get a simple web page up and running, which uses TreeView as well as an SiteMapDataSource. The TreeView is to list links on the web application. My data source for the site navigation is an XML file (Web.sitemap).

When I run this application in my web browser, I get the error: "Unable to connect to any of the specified MySQL hosts."

It says my error is on line 285:

```<code>Line 283:    <siteMap>
Line 284:      <providers>
Line 285:        <add name="MySqlSiteMapProvider" type="MySql.Web.SiteMap.MySqlSiteMapProvider, MySql.Web, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
Line 286:      </providers>
Line 287:    </siteMap>
</code>```

Source File:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config    Line:  285

I am not using MySQL or any RDBMS for my sitemap, so I am not sure why I am getting this error. I did Install MySQL onto my system, as well as the plugins for Visual Studio 2015, so could this be the problem?

Thanks.

答:
Inside <system.web> add this;
Like this as below;

```<code><system.web>
   ...
    <siteMap>
    <providers>
        <remove name="MySqlSiteMapProvider" />
    </providers>
  </siteMap>
<system.web>
</code>```

Body:
I am trying to get a simple web page up and running, which uses TreeView as well as an SiteMapDataSource. The TreeView is to list links on the web application. My data source for the site navigation is an XML file (Web.sitemap).

When I run this application in my web browser, I get the error: "Unable to connect to any of the specified MySQL hosts."

It says my error is on line 285:

Line 283:    <siteMap>
Line 284:      <providers>
Line 285:        <add name="MySqlSiteMapProvider" type="MySql.Web.SiteMap.MySqlSiteMapProvider, MySql.Web, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
Line 286:      </providers>
Line 287:    </siteMap>

Source File:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config    Line:  285

I am not using MySQL or any RDBMS for my sitemap, so I am not sure why I am getting this error. I did Install MySQL onto my system, as well as the plugins for Visual Studio 2015, so could this be the problem?

Thanks.

Body:
Inside <system.web> add this;
Like this as below;

<system.web>
   ...
    <siteMap>
    <providers>
        <remove name="MySqlSiteMapProvider" />
    </providers>
  </siteMap>
<system.web>


问:
show 100% width child within non 100% width parent
I have a div that has max-width of let's say 1024px and I have it's child that needs to take 100% width starting at the left of the screen.

Is it possible without introducing additional markup? I understand that can make child 100% with width: 100vw; but can't seem to push it to the left.

CODE

.parent {
  max-width: 800px;
  margin: 0 auto;
}

.child {
  margin-top: 20px;
  padding: 20px;
  width: 100vw;
  background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  Toggle content
  <div class="child">Content</div>
</div></code>```

https://codepen.io/anon/pen/QgbPJj

答:
You can do it with absolute positioned pseudo elements. I had to add a wrapper with overflow hidden, otherwise a horizontal scroll was added. Someone might be able to figure out how to do it with the wrapper.

https://codepen.io/anon/pen/EXjzjE

.wrapper {
  overflow:hidden;
  margin-top:40px;
}

.parent {
  max-width: 800px;
  margin: 0 auto;
}

.child {
  margin-top: 20px;
  padding: 20px;
  width: 100%;
  background: grey;
  position:relative;
}

.child:before, .child:after {
  content:"";
  position:absolute;
  top:0;
  height:100%;
  width:100%;
  background:grey;
}
.child:before {
  left:-100%;
}
.child:after {
  right:-100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="parent">

   Toggle content

   <div class="child">Content</div>

  </div>
</div></code>```

Body:
I have a div that has max-width of let's say 1024px and I have it's child that needs to take 100% width starting at the left of the screen.

Is it possible without introducing additional markup? I understand that can make child 100% with width: 100vw; but can't seem to push it to the left.

CODE

.parent {
  max-width: 800px;
  margin: 0 auto;
}

.child {
  margin-top: 20px;
  padding: 20px;
  width: 100vw;
  background: grey;
}

  Toggle content

Content

https://codepen.io/anon/pen/QgbPJj

Body:
You can do it with absolute positioned pseudo elements. I had to add a wrapper with overflow hidden, otherwise a horizontal scroll was added. Someone might be able to figure out how to do it with the wrapper.

https://codepen.io/anon/pen/EXjzjE

.wrapper {
  overflow:hidden;
  margin-top:40px;
}

.parent {
  max-width: 800px;
  margin: 0 auto;
}

.child {
  margin-top: 20px;
  padding: 20px;
  width: 100%;
  background: grey;
  position:relative;
}

.child:before, .child:after {
  content:"";
  position:absolute;
  top:0;
  height:100%;
  width:100%;
  background:grey;
}
.child:before {
  left:-100%;
}
.child:after {
  right:-100%;
}

<div class="wrapper">
  <div class="parent">

   <a href="#" class="toggle">Toggle content</a>

   <div class="child">Content</div>

  </div>
</div>


问:
Is this right Script?
```<code>Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection "\\my_server_name\my_printer_name"
</code>```

hello all,

i used the script written above in a windows server 2003 (group policy management) running in a virtual machine then i used the command "gpupdate /force", but when i go to the client machine nothing happend

答: I found it, what was wrong is I should put the script in Default logon folder in the server  </p>

Title: Is this right Script?

Body:
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection "\\my_server_name\my_printer_name"

hello all,

i used the script written above in a windows server 2003 (group policy management) running in a virtual machine then i used the command "gpupdate /force", but when i go to the client machine nothing happend


问:
Test if a function runs in the past minute or second javascript
I'm using socket.io with a node.js server in communication between clients, and in receiving message from one client I do some treatment in the callback and i have some code that run every time and some that must run once a minute to store data in a mysql database:

```<code>io.on('connection', function(socket) {
       socket.on('createroom', function(room) {
                socket.on('values', function(values) {
                        treatment done each time with values;
                        treatment must be done once a minute with values;
                }
       }
}
</code>```

How I can test if a function or some code has run in the past minute.

答:
You can record as a socket property, when you last processed this event and just check that time:

```<code>io.on('connection', function(socket) {
    // initialize lastProcessed time to a long time ago (haven't done it yet)
    socket.lastProcessed = 0;
    socket.on('createroom', function(room) {
        // there's a problem here because you will create duplicate event handlers
        // for the values message
        socket.on('values', function(values) {
            treatment done each time with values;
            if (Date.now() - socket.lastProcessed > (1000 * 60)) {
                treatment must be done once a minute with values;
                // update time we last processed it
                socket.lastProcessed = Date.now();
            }
        });
    });
});
</code>```

FYI, you have another problem here that every time you get the createroom event you are adding another listener for the values message.  You will end up with duplicate handlers for that message which is a problem.  Since you don't explain the overall logic here, I'm not quite sure what solution to that would be best.

Possible solutions.  Assign the values event handler at the same scope as you assign the createroom event handler or remove the values event handler after it occurs.

Body:
I'm using socket.io with a node.js server in communication between clients, and in receiving message from one client I do some treatment in the callback and i have some code that run every time and some that must run once a minute to store data in a mysql database:

io.on('connection', function(socket) {
       socket.on('createroom', function(room) {
                socket.on('values', function(values) {
                        treatment done each time with values;
                        treatment must be done once a minute with values;
                }
       }
}

How I can test if a function or some code has run in the past minute.

Body:
You can record as a socket property, when you last processed this event and just check that time:

io.on('connection', function(socket) {
    // initialize lastProcessed time to a long time ago (haven't done it yet)
    socket.lastProcessed = 0;
    socket.on('createroom', function(room) {
        // there's a problem here because you will create duplicate event handlers
        // for the values message
        socket.on('values', function(values) {
            treatment done each time with values;
            if (Date.now() - socket.lastProcessed > (1000 * 60)) {
                treatment must be done once a minute with values;
                // update time we last processed it
                socket.lastProcessed = Date.now();
            }
        });
    });
});

FYI, you have another problem here that every time you get the createroom event you are adding another listener for the values message.  You will end up with duplicate handlers for that message which is a problem.  Since you don't explain the overall logic here, I'm not quite sure what solution to that would be best.

Possible solutions.  Assign the values event handler at the same scope as you assign the createroom event handler or remove the values event handler after it occurs.


问:
No module named 'django_auth_ldap'
I'm trying to configure a website with django and LDAP authentification. Upon my login page, I just type in any username and password, and expect to get to a different html page (without connecting to a database, for now. My method in my view.py file:

```<code>def login_view(request):
    if request.POST:
        print ('*'*50)
        print (request.POST)
        print ('*'*50)
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        print ('*'*50)
        print (user)
        print ('*'*50)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('index')
            else:
                messages.error(request, "User is not active in Database")
        else:
            messages.error(request, "Please check your username and password!")
    return render(request, 'login.html')
</code>```

I'm new to django so not even too sure whether I should be seeing any page of if this error message is correct. I'm using Python3.5 and I installed successfully pyasn1-0.2.3. Then going into my console I can successfully import ldap3. However I can't get any further than this.

settings.py

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'UserAuth',
]
</code>```

Any my directory looks like this:

```<code>UserAuth
  -> user_auth
  -> UserAuth
  manage.py
</code>```

From what I can deduce, it appears that django_ldap_auth cannot be easily installed for 1. Windows 8.1 Enterprise and 2. for Python 3 (https://github.com/susundberg/django-auth-ldap-ad)

That is annoying, perhaps if I switch to Python2 maybe this would work....

答:
I reached a dead with this and unless I hear on the contrary, then for Python3 users on Windows, this will also become a dead end. A thread on the matter can be found here.

Instead I'll now try with Radius.

Title: No module named 'django_auth_ldap'

Body:
I'm trying to configure a website with django and LDAP authentification. Upon my login page, I just type in any username and password, and expect to get to a different html page (without connecting to a database, for now. My method in my view.py file:

def login_view(request):
    if request.POST:
        print ('*'*50)
        print (request.POST)
        print ('*'*50)
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        print ('*'*50)
        print (user)
        print ('*'*50)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('index')
            else:
                messages.error(request, "User is not active in Database")
        else:
            messages.error(request, "Please check your username and password!")
    return render(request, 'login.html')

I'm new to django so not even too sure whether I should be seeing any page of if this error message is correct. I'm using Python3.5 and I installed successfully pyasn1-0.2.3. Then going into my console I can successfully import ldap3. However I can't get any further than this.

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'UserAuth',
]

Any my directory looks like this:

UserAuth
  -> user_auth
  -> UserAuth
  manage.py

From what I can deduce, it appears that django_ldap_auth cannot be easily installed for 1. Windows 8.1 Enterprise and 2. for Python 3 (https://github.com/susundberg/django-auth-ldap-ad)

That is annoying, perhaps if I switch to Python2 maybe this would work....


问:
plt.show() not executing properly
Currently, I am attempting to follow along with a Sentdex YouTube tutorial video (https://www.youtube.com/watchv=cExOVprMlQg&list=PLQVvvaa0QuDe6ZBtkCNWNUbdaBo2vA4RO), however I am running into some difficulties with plt.show(). I have written this script nearly verbatim as detailed in this video and I have turned to StackOverflow to update any syntax, yet I have not been able to actually view this graph. Nothing comes up when I run the script, the shell just spits out '>>'.  I have changed backends, unistalled, upgraded and reinstalled matplotlib. I've also tried this script on the exact version of Python seen in this video as well as 3.6.1 and a few others on OS X and Windows 10 via Parallels - still running into the same issue.

Here is my code thus far:

```<code>import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
import pylab

def graphRawFX():
    date, bid, ask = np.loadtext('GBPUSD1d.txt', unpack=True,
                                 delimiter='-',
                                 converters={0: mdates.strpdate2numb('%Y%m%d%H%M%S')})

    fig = plt.figure(figsize=(10,7))

    ax1 = plt.subplot2grid((40,40), (0), rowspan=40, colspan=40)
    ax1.plot(date, bid)
    ax1.plot(date, ask)

    ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d %H:#M:#S'))
    for label in ax1.axis,get_xticklabels():
        label.set_rotation(45)

    ply.gca().get_yaxis().get_major_formatter().set_useOffset(False)

    plt.grid(True)
    plt.show()
    pylab.show()
</code>```

Any thoughts on a solution?

答:
I have it working (mac OS). Just try to copy paste to see if there's some typing problem. (it was working without "import pylab" and the "pylab.show()" I have just put it to have the same code you have.</p>

```<code>import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticher
import matplotlib.dates as mdates
import numpy as np
import pylab

def graphRawFX():
        date,bid,ask = np.loadtxt('GBPUSD1d.txt', unpack=True, delimiter=',',converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})

        fig = plt.figure(figsize=(10,7))
        ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

        ax1.plot(date,bid)
        ax1.plot(date,ask)
        plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)

        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
        for label in ax1.xaxis.get_ticklabels() :
                label.set_rotation(45)

        ax1_2=ax1.twinx()
        ax1_2.fill_between(date,0, (ask-bid),facecolor='g',alpha=.3)

        plt.subplots_adjust(bottom=.23)

        plt.grid(True)
        plt.show()
        pylab.show()

graphRawFX()
</code>```

Title: plt.show() not executing properly

Body:
Currently, I am attempting to follow along with a Sentdex YouTube tutorial video (https://www.youtube.com/watchv=cExOVprMlQg&list=PLQVvvaa0QuDe6ZBtkCNWNUbdaBo2vA4RO), however I am running into some difficulties with plt.show(). I have written this script nearly verbatim as detailed in this video and I have turned to StackOverflow to update any syntax, yet I have not been able to actually view this graph. Nothing comes up when I run the script, the shell just spits out '>>'.  I have changed backends, unistalled, upgraded and reinstalled matplotlib. I've also tried this script on the exact version of Python seen in this video as well as 3.6.1 and a few others on OS X and Windows 10 via Parallels - still running into the same issue.

Here is my code thus far:

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
import pylab

def graphRawFX():
    date, bid, ask = np.loadtext('GBPUSD1d.txt', unpack=True,
                                 delimiter='-',
                                 converters={0: mdates.strpdate2numb('%Y%m%d%H%M%S')})

    fig = plt.figure(figsize=(10,7))

    ax1 = plt.subplot2grid((40,40), (0), rowspan=40, colspan=40)
    ax1.plot(date, bid)
    ax1.plot(date, ask)

    ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d %H:#M:#S'))
    for label in ax1.axis,get_xticklabels():
        label.set_rotation(45)

    ply.gca().get_yaxis().get_major_formatter().set_useOffset(False)

    plt.grid(True)
    plt.show()
    pylab.show()

Any thoughts on a solution?

Body:
I have it working (mac OS). Just try to copy paste to see if there's some typing problem. (it was working without "import pylab" and the "pylab.show()" I have just put it to have the same code you have.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticher
import matplotlib.dates as mdates
import numpy as np
import pylab

def graphRawFX():
        date,bid,ask = np.loadtxt('GBPUSD1d.txt', unpack=True, delimiter=',',converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})

        fig = plt.figure(figsize=(10,7))
        ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

        ax1.plot(date,bid)
        ax1.plot(date,ask)
        plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)

        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
        for label in ax1.xaxis.get_ticklabels() :
                label.set_rotation(45)

        ax1_2=ax1.twinx()
        ax1_2.fill_between(date,0, (ask-bid),facecolor='g',alpha=.3)

        plt.subplots_adjust(bottom=.23)

        plt.grid(True)
        plt.show()
        pylab.show()

graphRawFX()


问:
php placement of the dot in a long number
I want to display a large number with a leading zero and a dot after.

The balance i want to display starts with 0.000000000000000000 ( 18 zeros after the dot ). This should be able to go up to 99.00000000000000000.( 17 zeros after the dot ).

I did a lot of trial and error but i just can't seem to get the dot in there. As far as for the zeros i got it working. What i have now is:

```<code>$leadingBalance = sprintf("%019d", $balance);
echo $leadingBalance;
</code>```

This will display the correct balance but i need to place the dot in there. It means that if my balance has 17 or 18 numbers it should place the dot as 0.0000... If the balance has 19 numbers it should place the dot as 00.0000...

Whatever i try, how much i look up i can't figure it out.

答:
You are using %019d when you actually wants a float number, try this:

```<code><?php
    $format = '%0.19f';
    $args = 9;
    $result = sprintf ($format, $args);
    //$result will be equal to 9.0000000000000000000
?>
</code>```

```<code><?php
    $format = '%0.19f';
    $args = 99;
    $result = sprintf ($format, $args);
    //$result will be equal to 99.0000000000000000000
?>
</code>```

Edit:

Since it looks like you want your whole number to be equal to 20 digits only, you may try to do some math if number_format doesn't do your job. You can try something like:

```<code><?php
    $number = 999;
    $number_length = strlen($number);
    $format_len = 20 - $number_length;
    $format = '%0.'. $format_len .'f';
    $result = sprintf($format, $number);
?>
</code>```

Body:
I want to display a large number with a leading zero and a dot after.

The balance i want to display starts with 0.000000000000000000 ( 18 zeros after the dot ). This should be able to go up to 99.00000000000000000.( 17 zeros after the dot ).

I did a lot of trial and error but i just can't seem to get the dot in there. As far as for the zeros i got it working. What i have now is:

$leadingBalance = sprintf("%019d", $balance);
echo $leadingBalance;

This will display the correct balance but i need to place the dot in there. It means that if my balance has 17 or 18 numbers it should place the dot as 0.0000... If the balance has 19 numbers it should place the dot as 00.0000...

Whatever i try, how much i look up i can't figure it out.

Body:
You are using %019d when you actually wants a float number, try this:

<?php
    $format = '%0.19f';
    $args = 9;
    $result = sprintf ($format, $args);
    //$result will be equal to 9.0000000000000000000
?>

<?php
    $format = '%0.19f';
    $args = 99;
    $result = sprintf ($format, $args);
    //$result will be equal to 99.0000000000000000000
?>

Edit:

Since it looks like you want your whole number to be equal to 20 digits only, you may try to do some math if number_format doesn't do your job. You can try something like:

<?php
    $number = 999;
    $number_length = strlen($number);
    $format_len = 20 - $number_length;
    $format = '%0.'. $format_len .'f';
    $result = sprintf($format, $number);
?>


问:
Setting Color through Javascript based on condition
I am generating a html table through C# code in an MVC Application .

I want to color the value in table cell as red and condition for this is (if column-x value is greater than value of column-y than set color of column-x as red).

column-x and column-y have their on id,s

Below is generated HTML and javascript code which I am using

$('#body table').each(function () {
    $('#' + this.id + ' ' + 'tr').each(function () {
        var v1 = $('#TodayPDue').html();
        var v2 = $('#TodayIntDue').html();

        if (v1 > v2){
            $('#TodayPDue').css('color','red');
        }
     })
});```
<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>
<table id='CollectionRPT' class='table table-bordered table-hover'>
     <tbody>
         <tr>
            <td>1</td>
            <td>BIHAR</td>
            <td id='TodayPDue'>2220515</td>
            <td id='TodayIntDue'>457565</td>
            <td id='TodayPCollected'>0</td>
            <td id='TodayIntCollected'>0</td>
            <td id='MonthPDue'>10232468</td>
            <td id='MonthIntDue'>2058526</td>
            <td id='MonthPCollected'>5912869</td>
            <td id='MonthIntCollected'>1167760</td>
            <td id='YearPDue'>6432342</td>
            <td id='YearIntDue'>1303773</td>
            <td id='YearPCollected'>2111473</td>
            <td id='YearIntCollected'>413023</td>
         </tr>
     </tbody>
</table></code>```

Any idea why it is showing no effect ?

答:
You need to convert the text "2220515" to a number 2220515, for instance with parseInt() or with the + operator, as I did.

$('#CollectionRPT td').each(function () {
    var v1 = +$('#TodayPDue').html();
    var v2 = +$('#TodayIntDue').html();

    if (v1 > v2){
       $('#TodayPDue').css('color','red');
    }
})```
<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>
<table id='CollectionRPT' class='table table-bordered table-hover'>
     <tbody>
         <tr>
            <td>1</td>
            <td>BIHAR</td>
            <td id='TodayPDue'>2220515</td>
            <td id='TodayIntDue'>457565</td>
            <td id='TodayPCollected'>0</td>
            <td id='TodayIntCollected'>0</td>
            <td id='MonthPDue'>10232468</td>
            <td id='MonthIntDue'>2058526</td>
            <td id='MonthPCollected'>5912869</td>
            <td id='MonthIntCollected'>1167760</td>
            <td id='YearPDue'>6432342</td>
            <td id='YearIntDue'>1303773</td>
            <td id='YearPCollected'>2111473</td>
            <td id='YearIntCollected'>413023</td>
         </tr>
     </tbody>
</table></code>```

Body:
I am generating a html table through C# code in an MVC Application .

I want to color the value in table cell as red and condition for this is (if column-x value is greater than value of column-y than set color of column-x as red).

column-x and column-y have their on id,s

Below is generated HTML and javascript code which I am using

$('#body table').each(function () {
    $('#' + this.id + ' ' + 'tr').each(function () {
        var v1 = $('#TodayPDue').html();
        var v2 = $('#TodayIntDue').html();

        if (v1 > v2){
            $('#TodayPDue').css('color','red');
        }
     })
});

            1
            BIHAR
            2220515
            457565
            0
            0
            10232468
            2058526
            5912869
            1167760
            6432342
            1303773
            2111473
            413023

Any idea why it is showing no effect ?

Body:
You need to convert the text "2220515" to a number 2220515, for instance with parseInt() or with the + operator, as I did.

$('#CollectionRPT td').each(function () {
    var v1 = +$('#TodayPDue').html();
    var v2 = +$('#TodayIntDue').html();

    if (v1 > v2){
       $('#TodayPDue').css('color','red');
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='CollectionRPT' class='table table-bordered table-hover'>
     <tbody>
         <tr>
            <td>1</td>
            <td>BIHAR</td>
            <td id='TodayPDue'>2220515</td>
            <td id='TodayIntDue'>457565</td>
            <td id='TodayPCollected'>0</td>
            <td id='TodayIntCollected'>0</td>
            <td id='MonthPDue'>10232468</td>
            <td id='MonthIntDue'>2058526</td>
            <td id='MonthPCollected'>5912869</td>
            <td id='MonthIntCollected'>1167760</td>
            <td id='YearPDue'>6432342</td>
            <td id='YearIntDue'>1303773</td>
            <td id='YearPCollected'>2111473</td>
            <td id='YearIntCollected'>413023</td>
         </tr>
     </tbody>
</table>


问:
How do I desing my application on Java(eclipse)
I'm new with learning Java. I was learning C# and C# has own designer inside it. Like " Add: Button, Label, Timer, TextBox" But in Eclipse there is no such a thing. Should I use and external program for design or I'm blind and can't see it?

答: You can use NetBeans it has all of the features you are looking for (Add: Button, Label, Timer, TextBox), And it supports java. It is very easy to use and it is very similar to eclipse. good luck!</p>


问:
self.tabBarController sometimes nil
I have UIViewController (first) which has tab bar at the bottom. I have next code in this controller:

```<code>let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
</code>```

It's working fine, but when I'm going from this first to next one (second) controller and then pressing Back button and returning to first, self.tabBarController is nil. Why does it happen? I have only one version, that stack of controllers is overcrowded.

How can I fix this? I need this height to calculate some value for constraint change in keyboardWillShow function.

UPDATE:

How do I call it:

```<code>// MARK: - Scroll view on keyboard show/hide
extension CommentariesController: UITextFieldDelegate {
    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
           let keyboardHeight = keyboardSize.height
           let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
           UIView.animate(withDuration: 1.0, animations: {
               self.newCommentViewBotConstraint.constant = -keyboardHeight + tabBarHeight!
               self.view.layoutIfNeeded()
           })
        }
    }

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

Update 2:

I can see tab bar. But it is nil.

Structure (with Show segues): tabbar -> navbar -> viewcontroller -> viewcontroller -> viewcontroller (first) -> viewcontroller (second).

Thanks

答:
On iOS >= 8.0, the tabbar height is always 49 pt (see What's the height of a UITabBar on iOS 8, iOS 9 and iOS 10?).

If you need some complex UI use case to solve when the tabbar is not accessible, just put that number into a constant and use that, e.g.:

```<code>let tabbarHeight: CGFloat = 49.0
</code>```

or, save the value to a variable, e.g.

```<code>var tabbarHeight:

viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated: animated)

    self.tabbarHeight = self.tabBarController!.tabBar.frame.size.height
}
</code>```

Title: self.tabBarController sometimes nil

Body:
I have UIViewController (first) which has tab bar at the bottom. I have next code in this controller:

let tabBarHeight = self.tabBarController?.tabBar.frame.size.height

It's working fine, but when I'm going from this first to next one (second) controller and then pressing Back button and returning to first, self.tabBarController is nil. Why does it happen? I have only one version, that stack of controllers is overcrowded.

How can I fix this? I need this height to calculate some value for constraint change in keyboardWillShow function.

UPDATE:

How do I call it:

// MARK: - Scroll view on keyboard show/hide
extension CommentariesController: UITextFieldDelegate {
    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
           let keyboardHeight = keyboardSize.height
           let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
           UIView.animate(withDuration: 1.0, animations: {
               self.newCommentViewBotConstraint.constant = -keyboardHeight + tabBarHeight!
               self.view.layoutIfNeeded()
           })
        }
    }

    // other code
}

Update 2:

I can see tab bar. But it is nil.

Structure (with Show segues): tabbar -> navbar -> viewcontroller -> viewcontroller -> viewcontroller (first) -> viewcontroller (second).

Thanks

Body:
On iOS >= 8.0, the tabbar height is always 49 pt (see What's the height of a UITabBar on iOS 8, iOS 9 and iOS 10?).

If you need some complex UI use case to solve when the tabbar is not accessible, just put that number into a constant and use that, e.g.:

let tabbarHeight: CGFloat = 49.0

or, save the value to a variable, e.g.

var tabbarHeight:

viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated: animated)

    self.tabbarHeight = self.tabBarController!.tabBar.frame.size.height
}