问:
How do I figure out what is causing Data IO spikes on my Azure SQL database?
I have a Azure SQL production database that runs at around 10-20% DTU usage on average, however, I get DTU spikes that take it upwards of 100% at times. Here is a sample from the past 1 hour:

I realize this could be a rouge query, so I switched over to the Query Performance Insight tab, and I find the following from the past 24 hours:

This chart makes sense with regards to the CPU usage line. Query 3780 takes the majority of at CPU, as expected with my application. The Overall DTU (red) line seems to follow this correctly (minus the spikes).

However, in the DTU Components charts I can see large Data IO spikes occurring that coincide with the Overall DTU spikes. Switching over to the TOP 5 queries by Data IO, I see the following:

This seems to indicate that there are no queries that are using high amounts of Data IO.

How do I find out where this Data IO usage is coming from?

Finally, I see that there is this one, "odd ball" query (7966) listed under the TOP 5 queries by Data IO with only 5 executions. Selecting it shows the following:

```<code>SELECT StatMan([SC0], [SC1], [SC2], [SB0000])
    FROM (SELECT TOP 100 PERCENT [SC0], [SC1], [SC2], step_direction([SC0]) over (order by NULL) AS [SB0000]
    FROM (SELECT [UserId] AS [SC0], [Type] AS [SC1], [Id] AS [SC2] FROM [dbo].[Cipher] TABLESAMPLE SYSTEM (1.828756e+000 PERCENT)
    WITH (READUNCOMMITTED) ) AS _MS_UPDSTATS_TBL_HELPER
ORDER BY [SC0], [SC1], [SC2], [SB0000] ) AS _MS_UPDSTATS_TBL
OPTION (MAXDOP 16)
</code>```

What is this query?

This does not look like any query that my application has created/uses. The timestamps on the details chart seem to line up with the approximate times of the overall Data IO spikes (just prior to 6am) which leads me to think this query has something to do with all of this.

Are there any other tools can I use to help isolate this issue?

答:
The query is updating statistics..this occurs when this setting AUTO UPDATE STATISTICS  is on..This should be kept on  and you can't turn it off..this is a best practice..

You should update stats manually only when when you see a query not performing well and stats are off for that query..

Also below are some rules when SQL will update stats automatically for you

When a table with no rows gets a row

When 500 rows are changed to a table that is less than 500 rows

When 20% + 500 are changed in a table greater than 500 rows

By ‘change’ we mean if a row is inserted, updated or deleted. So, yes, even the automatically-created statistics get updated and maintained as the data changes.There were some changes to these rules in recent versions and sql can update stats more often

References:

https://www.sqlskills.com/blogs/erin/understanding-when-statistics-will-automatically-update/

Body:
I have a Azure SQL production database that runs at around 10-20% DTU usage on average, however, I get DTU spikes that take it upwards of 100% at times. Here is a sample from the past 1 hour:

I realize this could be a rouge query, so I switched over to the Query Performance Insight tab, and I find the following from the past 24 hours:

This chart makes sense with regards to the CPU usage line. Query 3780 takes the majority of at CPU, as expected with my application. The Overall DTU (red) line seems to follow this correctly (minus the spikes).

However, in the DTU Components charts I can see large Data IO spikes occurring that coincide with the Overall DTU spikes. Switching over to the TOP 5 queries by Data IO, I see the following:

This seems to indicate that there are no queries that are using high amounts of Data IO.

How do I find out where this Data IO usage is coming from?

Finally, I see that there is this one, "odd ball" query (7966) listed under the TOP 5 queries by Data IO with only 5 executions. Selecting it shows the following:

SELECT StatMan([SC0], [SC1], [SC2], [SB0000])
    FROM (SELECT TOP 100 PERCENT [SC0], [SC1], [SC2], step_direction([SC0]) over (order by NULL) AS [SB0000]
    FROM (SELECT [UserId] AS [SC0], [Type] AS [SC1], [Id] AS [SC2] FROM [dbo].[Cipher] TABLESAMPLE SYSTEM (1.828756e+000 PERCENT)
    WITH (READUNCOMMITTED) ) AS _MS_UPDSTATS_TBL_HELPER
ORDER BY [SC0], [SC1], [SC2], [SB0000] ) AS _MS_UPDSTATS_TBL
OPTION (MAXDOP 16)

What is this query?

This does not look like any query that my application has created/uses. The timestamps on the details chart seem to line up with the approximate times of the overall Data IO spikes (just prior to 6am) which leads me to think this query has something to do with all of this.

Are there any other tools can I use to help isolate this issue?


来源: stackexchange

问:
Tkinter rectangle itemconfig fill update does not work every time
I'm having a strange behavior with tkinter, canvas and itemconfig.

I have a small window, with a canvas that is filled with rectangles, each rectangle shows a color of a palette. I've setup an event for left & right mouse buttons, LMB selects a color, RMB swaps the clicked color with the selected one. The bind event is working fine, since other operations being done during this process happen (actual palette colors being swapped).

The thing is that upon first LMB & RMB click, the rectangles "fill" does not get updated (or at least there is no refresh on screen), but upon 2nd RMB click, the color change is reflected (but the color is swapped twice).

The code that updates the rectangles is:

```<code>app.paletteCanvas.itemconfig(app.paletteColorBoxes[newColor], fill=transformColor(app,app.drawColor))
app.paletteCanvas.itemconfig(app.paletteColorBoxes[app.drawColor], fill=transformColor(app,newColor))
</code>```

app is the main application, paletteCanvas is the canvas which is packed in a "palette window", in app.paletteColorBoxes I keep the index of the rectangle to change, newColor and app.drawColor are the original color and color to swap, and finally transformColor just transgorms a (R,G,B) thing into a  #RRGGBB string for itemconfig to understand.

So, everything seems to work fine, except that upon first call to the routine the refresh is not done, but upon 2nd call the refresh is done.

I tried all sorts of .update() and .update_idletasks() but no luck.

To fully test this behavior you can check the full application at:

https://github.com/zayamatias/retrotool

The misbehaving function is in retrofunctions.py / swapColor

You need to open an image, click on some color and select "Tile Viewer/ Editor", after the tool is done (maybe it can fail, still WIP) you will see the palette window.

Thanks!

BTW I'm on Python 3.6.3 if that helps.

答: Ok, so finally the issue was not with tkinter but with a mix up in teh values passed to the itemconfig method...my bad!</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm having a strange behavior with tkinter, canvas and itemconfig.

I have a small window, with a canvas that is filled with rectangles, each rectangle shows a color of a palette. I've setup an event for left & right mouse buttons, LMB selects a color, RMB swaps the clicked color with the selected one. The bind event is working fine, since other operations being done during this process happen (actual palette colors being swapped).

The thing is that upon first LMB & RMB click, the rectangles "fill" does not get updated (or at least there is no refresh on screen), but upon 2nd RMB click, the color change is reflected (but the color is swapped twice).

The code that updates the rectangles is:

app.paletteCanvas.itemconfig(app.paletteColorBoxes[newColor], fill=transformColor(app,app.drawColor))
app.paletteCanvas.itemconfig(app.paletteColorBoxes[app.drawColor], fill=transformColor(app,newColor))

app is the main application, paletteCanvas is the canvas which is packed in a "palette window", in app.paletteColorBoxes I keep the index of the rectangle to change, newColor and app.drawColor are the original color and color to swap, and finally transformColor just transgorms a (R,G,B) thing into a  #RRGGBB string for itemconfig to understand.

So, everything seems to work fine, except that upon first call to the routine the refresh is not done, but upon 2nd call the refresh is done.

I tried all sorts of .update() and .update_idletasks() but no luck.

To fully test this behavior you can check the full application at:

https://github.com/zayamatias/retrotool

The misbehaving function is in retrofunctions.py / swapColor

You need to open an image, click on some color and select "Tile Viewer/ Editor", after the tool is done (maybe it can fail, still WIP) you will see the palette window.

Thanks!

BTW I'm on Python 3.6.3 if that helps.


问:
Messy data shown in blade but not in mobile view
For some reason when I try to add in a navbar into my edit page, my view became messed up. I don't know why this is happening, I thought it might be the work of the css and all but I tried moving them but nothing happen. But when I try to use the developer tool which shows it in a mobile view, it became neat again. Can anyone explain to me what is going on?

This is the blade view:

This is the mobile view:

Here is the edit.blade.php:

```<code>@extends('layouts.app')
@section('title', 'Summary')
@section('content')
    <div class="container" style="background-color:#ADD8E6">
        <link href="{{ asset('css/homeStyle.css') }}" rel="stylesheet">
        <!DOCTYPE html>
        <html>
            <head></head>
            <body>
                <div class="form-group">
                    <form class="form-horizontal" method="post" action="{{ url('/user/show/'.$object->id) }}">
                        {{ method_field('PUT')  }}
                        {{ csrf_field() }}
                        <label class="col-md-2"><b>Name AS PER NRIC/PASSPORT:</b></label>
                        <div class="col-md-6">
                            <input type="text" name="Name" value="{{ $object->Name }}" class="form-control">
                        </div>
                        <label class="col-md-2"><b>Alias:</b></label>
                        <div class="col-md-6">
                            <input type="text" name="Alias" value="{{ $object->Alias }}" class="form-control">
                        </div>
                        <label class="col-md-2"><b>Email:</b></label>
                        <div class="col-md-6">
                            <input type="email" name="Email" value="{{ $object->Email }}" class="form-control">
                        </div>
                        <label class="col-md-2"><b>Mobile Number:</b></label>
                        <div class="col-md-6">
                            <input type="number" name="Mobile_No" value="{{ $object->Mobile_No }}" class="form-control">
                        </div>
                        <label class="col-md-2"><b>Telephone Number:</b></label>
                        <div class="col-md-6">
                            <input type="number" name="Tele_no" value="{{ $object->Tele_no }}" class="form-control">
                        </div>
                        <label class="col-md-2"><b>NRIC:</b></label>
                        <div class="col-md-6">
                            <input type="text" name="NRIC" value="{{ $object->NRIC }}" class="form-control">
                        </div>
                        <div class="form-group">
                            <div class="col-md-6-offset-2">
                            <input type="submit" class="btn btn-primary" value="Save">
                            </div>
                        </div>
                    </form>
                </div>
            </body>
        </html>
        @if(count($errors))
            @foreach($errors->all() as $error)
                <div class="alert alert-danger">
                    {{$error}}
                </div>
            @endforeach
        @endif
    </div>
@endsection
</code>```

答:
first of all remove html head and body tags from it as there is already in layout then try to add div with row and make it like size of row is 12 so what you have to do is make your class like it's equal 12 give you what you desire further check bootstrap

```<code>@extends('layouts.app')
    @section('title', 'Summary')
    @section('content')
    <div class="container" style="background-color:#ADD8E6">
    <link href="{{ asset('css/homeStyle.css') }}" rel="stylesheet">

    <div class="form-group">
            <form class="form-horizontal" method="post" action="{{ url('/user/show/'.$object->id) }}">

              {{ method_field('PUT')  }}
              {{ csrf_field() }}

                <div class='row' >
                  <label class="col-md-4"><b>Name AS PER NRIC/PASSPORT:</b></label>
                  <div class="col-md-8">
                  <input type="text" name="Name" value="{{ $object->Name }}" class="form-control">
                  </div>
                </div>

                <div class='row' >
                  <label class="col-md-4"><b>Alias:</b></label>
                  <div class="col-md-8">
                  <input type="text" name="Alias" value="{{ $object->Alias }}" class="form-control">
                  </div>
                </div>

              <div class='row' >
                <label class="col-md-4"><b>Email:</b></label>
                <div class="col-md-8">
                  <input type="email" name="Email" value="{{ $object->Email }}" class="form-control">
                </div>
              </div>

              <div class='row' >
                <label class="col-md-4"><b>Mobile Number:</b></label>
                <div class="col-md-8">
                  <input type="number" name="Mobile_No" value="{{ $object->Mobile_No }}" class="form-control">
                </div>
              </div>

              <div class='row' >
                <label class="col-md-4"><b>Telephone Number:</b></label>
                <div class="col-md-8">
                  <input type="number" name="Tele_no" value="{{ $object->Tele_no }}" class="form-control">
                </div>
              </div>

              <div class='row' >
                <label class="col-md-4"><b>NRIC:</b></label>
                <div class="col-md-8">
                  <input type="text" name="NRIC" value="{{ $object->NRIC }}" class="form-control">
                </div>
              </div>

              <div class="form-group">
                <div class="col-md-8-offset-4">
                  <input type="submit" class="btn btn-primary" value="Save">
                </div>
              </div>

          </form>
    </div>
      @if(count($errors))
        @foreach($errors->all() as $error)
        <div class="alert alert-danger">
              {{$error}}
        </div>
         @endforeach
      @endif
    </div>
    @endsection
</code>```

hope it will help you!

Body:
For some reason when I try to add in a navbar into my edit page, my view became messed up. I don't know why this is happening, I thought it might be the work of the css and all but I tried moving them but nothing happen. But when I try to use the developer tool which shows it in a mobile view, it became neat again. Can anyone explain to me what is going on?

This is the blade view:

This is the mobile view:

Here is the edit.blade.php:

@extends('layouts.app')
@section('title', 'Summary')
@section('content')

        <link href="{{ asset('css/homeStyle.css') }}" rel="stylesheet">
        <!DOCTYPE html>

                    <form class="form-horizontal" method="post" action="{{ url('/user/show/'.$object->id) }}">
                        {{ method_field('PUT')  }}
                        {{ csrf_field() }}
                        Name AS PER NRIC/PASSPORT:

                            <input type="text" name="Name" value="{{ $object->Name }}" class="form-control">

                        Alias:

                            <input type="text" name="Alias" value="{{ $object->Alias }}" class="form-control">

                        Email:

                            <input type="email" name="Email" value="{{ $object->Email }}" class="form-control">

                        Mobile Number:

                            <input type="number" name="Mobile_No" value="{{ $object->Mobile_No }}" class="form-control">

                        Telephone Number:

                            <input type="number" name="Tele_no" value="{{ $object->Tele_no }}" class="form-control">

                        NRIC:

                            <input type="text" name="NRIC" value="{{ $object->NRIC }}" class="form-control">

                            <input type="submit" class="btn btn-primary" value="Save">

                    </form>

        @if(count($errors))
            @foreach($errors->all() as $error)

                    {{$error}}

            @endforeach
        @endif

@endsection

Body:
first of all remove html head and body tags from it as there is already in layout then try to add div with row and make it like size of row is 12 so what you have to do is make your class like it's equal 12 give you what you desire further check bootstrap

@extends('layouts.app')
    @section('title', 'Summary')
    @section('content')
    <div class="container" style="background-color:#ADD8E6">
    <link href="{{ asset('css/homeStyle.css') }}" rel="stylesheet">

    <div class="form-group">
            <form class="form-horizontal" method="post" action="{{ url('/user/show/'.$object->id) }}">

              {{ method_field('PUT')  }}
              {{ csrf_field() }}

                <div class='row' >
                  <label class="col-md-4"><b>Name AS PER NRIC/PASSPORT:</b></label>
                  <div class="col-md-8">
                  <input type="text" name="Name" value="{{ $object->Name }}" class="form-control">
                  </div>
                </div>

                <div class='row' >
                  <label class="col-md-4"><b>Alias:</b></label>
                  <div class="col-md-8">
                  <input type="text" name="Alias" value="{{ $object->Alias }}" class="form-control">
                  </div>
                </div>

              <div class='row' >
                <label class="col-md-4"><b>Email:</b></label>
                <div class="col-md-8">
                  <input type="email" name="Email" value="{{ $object->Email }}" class="form-control">
                </div>
              </div>

              <div class='row' >
                <label class="col-md-4"><b>Mobile Number:</b></label>
                <div class="col-md-8">
                  <input type="number" name="Mobile_No" value="{{ $object->Mobile_No }}" class="form-control">
                </div>
              </div>

              <div class='row' >
                <label class="col-md-4"><b>Telephone Number:</b></label>
                <div class="col-md-8">
                  <input type="number" name="Tele_no" value="{{ $object->Tele_no }}" class="form-control">
                </div>
              </div>

              <div class='row' >
                <label class="col-md-4"><b>NRIC:</b></label>
                <div class="col-md-8">
                  <input type="text" name="NRIC" value="{{ $object->NRIC }}" class="form-control">
                </div>
              </div>

              <div class="form-group">
                <div class="col-md-8-offset-4">
                  <input type="submit" class="btn btn-primary" value="Save">
                </div>
              </div>

          </form>
    </div>
      @if(count($errors))
        @foreach($errors->all() as $error)
        <div class="alert alert-danger">
              {{$error}}
        </div>
         @endforeach
      @endif
    </div>
    @endsection

hope it will help you!


问:
wxReactor Problem
I am developing a program that uses Twisted and wxReactor. Everytime I try to exit the application, it hangs, and I have to force quit it. My wxPython OnClose() event does call reactor.stop(), which to my knowledge should fix this issue. In my quest for an answer, I've come across this ticket: www.twistedmatrix.com/trac/ticket/3948.

I've tried a patch listed on the page, with no luck. I've been at this problem for 2 weeks now, and am pretty desperate :).

To give you all some background on this project: It is a freeware client that uses sockets to connect to a multiplayer game server (currently plays Monopoly and Uno). If you run it, you will immediately notice there are no graphics. That is because this client only provides audio feedback through speech synthesis and sound effects. The target audience of this project is visually impaired gamers.

To test the issue, run python rsg.py (which can be found in the src folder. In case you need to know, I use Python 2.6.5). In a terminal, you will see the output the program produces (which is mostly what the server sends to our client). Once you see the line "Connection Made" (which should print very shortly after running), try closing the program (by clicking the X). The client will hang for a few seconds, and then you will need to force quit the application (on Ubuntu, it comes up asking if I want to force quit the application).

I do have an idea of why it doesn't exit properly. When I ran it through gdb, two threads weren't exiting. Strange enough, if the server closed the connection, then I exited the program, it would work fine.

I really appreciate all help. Thank you in advance.

Edit Since I was asked to provide a basic demo of my problem, here it is:

```<code>import wx
import sys
from twisted.internet import wxreactor
wxreactor.install()

# import t.i.reactor only after installing wxreactor:
from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import ClientFactory
class ZGPClient(LineReceiver):
    """Our client object."""
    def lineReceived(self, datavar):
         "As soon as any data is received"
         print datavar

class EchoFactory(ClientFactory):
    protocol =  ZGPClient
    def startedConnecting(self, connector):
        global conn
        conn = connector
        print 'Started to connect.'

    def sendData(self, data=""):
      conn.transport.write(data.encode("ascii", "ignore") + "\n")

class main_window(wx.Frame):
 def __init__(self, parent, id, title):
  super(main_window, self).__init__(parent, id, title, style=wx.DEFAULT_FRAME_STYLE)
  self.Bind(wx.EVT_CLOSE, self.OnClose)
  self.Show(True)

 def OnClose(self, event):
   reactor.stop()
   sys.exit()

if __name__ == "__main__":
  app = wx.App()
  frame = main_window(None, wx.ID_ANY, "RS Games Client - No Game")
  reactor.registerWxApp(app)
  sockObj = EchoFactory()
  reactor.connectTCP("rsgamesmonserver.webhop.org", 3555, sockObj)
  reactor.run()
  app.MainLoop()
</code>```

答:
This will work for you:</p>

```<code>def OnClose(self, evt):
    # ugly hack until wxreactor is patched:
    reactor._stopping = True
    reactor.callFromThread(_threadedselect.ThreadedSelectReactor.stop, reactor)
</code>```

Title: wxReactor Problem

Body:
I am developing a program that uses Twisted and wxReactor. Everytime I try to exit the application, it hangs, and I have to force quit it. My wxPython OnClose() event does call reactor.stop(), which to my knowledge should fix this issue. In my quest for an answer, I've come across this ticket: www.twistedmatrix.com/trac/ticket/3948.

I've tried a patch listed on the page, with no luck. I've been at this problem for 2 weeks now, and am pretty desperate :).

To give you all some background on this project: It is a freeware client that uses sockets to connect to a multiplayer game server (currently plays Monopoly and Uno). If you run it, you will immediately notice there are no graphics. That is because this client only provides audio feedback through speech synthesis and sound effects. The target audience of this project is visually impaired gamers.

To test the issue, run python rsg.py (which can be found in the src folder. In case you need to know, I use Python 2.6.5). In a terminal, you will see the output the program produces (which is mostly what the server sends to our client). Once you see the line "Connection Made" (which should print very shortly after running), try closing the program (by clicking the X). The client will hang for a few seconds, and then you will need to force quit the application (on Ubuntu, it comes up asking if I want to force quit the application).

I do have an idea of why it doesn't exit properly. When I ran it through gdb, two threads weren't exiting. Strange enough, if the server closed the connection, then I exited the program, it would work fine.

I really appreciate all help. Thank you in advance.

Edit Since I was asked to provide a basic demo of my problem, here it is:

import wx
import sys
from twisted.internet import wxreactor
wxreactor.install()

# import t.i.reactor only after installing wxreactor:
from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import ClientFactory
class ZGPClient(LineReceiver):
    """Our client object."""
    def lineReceived(self, datavar):
         "As soon as any data is received"
         print datavar

class EchoFactory(ClientFactory):
    protocol =  ZGPClient
    def startedConnecting(self, connector):
        global conn
        conn = connector
        print 'Started to connect.'

    def sendData(self, data=""):
      conn.transport.write(data.encode("ascii", "ignore") + "\n")

class main_window(wx.Frame):
 def __init__(self, parent, id, title):
  super(main_window, self).__init__(parent, id, title, style=wx.DEFAULT_FRAME_STYLE)
  self.Bind(wx.EVT_CLOSE, self.OnClose)
  self.Show(True)

 def OnClose(self, event):
   reactor.stop()
   sys.exit()

if __name__ == "__main__":
  app = wx.App()
  frame = main_window(None, wx.ID_ANY, "RS Games Client - No Game")
  reactor.registerWxApp(app)
  sockObj = EchoFactory()
  reactor.connectTCP("rsgamesmonserver.webhop.org", 3555, sockObj)
  reactor.run()
  app.MainLoop()

Body:
This will work for you:

def OnClose(self, evt):
    # ugly hack until wxreactor is patched:
    reactor._stopping = True
    reactor.callFromThread(_threadedselect.ThreadedSelectReactor.stop, reactor)

ContentLicense: CC BY-SA 2.5


问:
Firebase not showing data to a listview
I'm trying to make a android app for a class in college, I need to show the information from the firebase database and show it in a listview. I had searched a lot but I couldn't find anything that will help me. I need help please.The app sent me some type of error but I couldn't found out what is wrong. I need to get each name of the products and show it in a listview for now.
by the way I'm a newbie to Android Studio.

This my database of firebase

This my activity:

```<code>public class buscador extends AppCompatActivity {

ListView lv;
private DatabaseReference myRef,ref,ref2;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private String id;
private FirebaseDatabase mFirebaseDatabase;
private static final String TAG = "buscador";
int num=1;
private ArrayList<String> array2;

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

    lv=(ListView)findViewById(R.id.cat1);
    EditText search = (EditText)findViewById(R.id.searchfind);
    mAuth=FirebaseAuth.getInstance();
    FirebaseUser user=mAuth.getCurrentUser();
    id=ref.getKey();

    setupFirebaseAuth();

    ref=FirebaseDatabase.getInstance().getReference("Products");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
public void showData(DataSnapshot dataSnapshot){
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        Producto info = new Producto();
        info.setName(ds.child(id).getValue(Producto.class).getName());

        Log.d(TAG, "showData:name:" + info.getName());
        ArrayList<String> array=new ArrayList<>();
        array.add(info.getName());
        ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
        lv.setAdapter(adapter);}
}
</code>```

Producto class object:

```<code>public class Producto {
private String image;
private String name;
private float price;
private String descripcion;
private String catalogo;
private String id;

public Producto(String image, String name, float price, String descripcion, String catalogo, String id) {
    this.image = image;
    this.name = name;
    this.price = price;
    this.descripcion = descripcion;
    this.catalogo = catalogo;
    this.id = id;
}

public Producto() {
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public String getDescripcion() {
    return descripcion;
}

public void setDescripcion(String descripcion) {
    this.descripcion = descripcion;
}

public String getCatalogo() {
    return catalogo;
}

public void setCatalogo(String catalogo) {
    this.catalogo = catalogo;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}
    }
</code>```

Error:

```<code>  Process: com.example.roge.navapp, PID: 32020

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.roge.navapp/com.example.roge.navapp.buscador}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5590)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at Com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.roge.navapp.buscador.onCreate(buscador.java:51)
at android.app.Activity.performCreate(Activity.java:5447)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
</code>```

答:
To get the name out of your Firebase database, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            list.add(name);
            Log.d("TAG", name);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
productsRef.addListenerForSingleValueEvent(eventListener);
</code>```

Yout output will be:

```<code>ps4
Xbox
//and so on
</code>```

Title: Firebase not showing data to a listview

Body:
I'm trying to make a android app for a class in college, I need to show the information from the firebase database and show it in a listview. I had searched a lot but I couldn't find anything that will help me. I need help please.The app sent me some type of error but I couldn't found out what is wrong. I need to get each name of the products and show it in a listview for now.
by the way I'm a newbie to Android Studio.

This my database of firebase

This my activity:

public class buscador extends AppCompatActivity {

ListView lv;
private DatabaseReference myRef,ref,ref2;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private String id;
private FirebaseDatabase mFirebaseDatabase;
private static final String TAG = "buscador";
int num=1;
private ArrayList<String> array2;

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

    lv=(ListView)findViewById(R.id.cat1);
    EditText search = (EditText)findViewById(R.id.searchfind);
    mAuth=FirebaseAuth.getInstance();
    FirebaseUser user=mAuth.getCurrentUser();
    id=ref.getKey();

    setupFirebaseAuth();

    ref=FirebaseDatabase.getInstance().getReference("Products");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
public void showData(DataSnapshot dataSnapshot){
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        Producto info = new Producto();
        info.setName(ds.child(id).getValue(Producto.class).getName());

        Log.d(TAG, "showData:name:" + info.getName());
        ArrayList<String> array=new ArrayList<>();
        array.add(info.getName());
        ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
        lv.setAdapter(adapter);}
}

Producto class object:

public class Producto {
private String image;
private String name;
private float price;
private String descripcion;
private String catalogo;
private String id;

public Producto(String image, String name, float price, String descripcion, String catalogo, String id) {
    this.image = image;
    this.name = name;
    this.price = price;
    this.descripcion = descripcion;
    this.catalogo = catalogo;
    this.id = id;
}

public Producto() {
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public String getDescripcion() {
    return descripcion;
}

public void setDescripcion(String descripcion) {
    this.descripcion = descripcion;
}

public String getCatalogo() {
    return catalogo;
}

public void setCatalogo(String catalogo) {
    this.catalogo = catalogo;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}
    }

Error:

  Process: com.example.roge.navapp, PID: 32020

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.roge.navapp/com.example.roge.navapp.buscador}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5590)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at Com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.roge.navapp.buscador.onCreate(buscador.java:51)
at android.app.Activity.performCreate(Activity.java:5447)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)

Body:
To get the name out of your Firebase database, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            list.add(name);
            Log.d("TAG", name);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
productsRef.addListenerForSingleValueEvent(eventListener);

Yout output will be:

ps4
Xbox
//and so on


问:
RxJS - How Subscriber is different from Observable and Subscription?
I have been trying to find an example of wrapping Observable into a Subscriber to monitor async call's status e.g. loading, completed or errored. Can you provide a short example?</p>

答:
Not sure if this is what you mean, but you can wrap an async http call like so

```<code>const httpStream = Observable.create(observer => {

    fetch('http://server.com')
      .then(response => response.json())
      .then(data => {
        observer.next(data); // if http call provides progress as well as completion
                             // these can all be pushed with observer.next()
        observer.complete();
      })
      .catch(err => observer.error(err));

  });

  httpStream.subscribe(data => console.log(data));
</code>```

Of course if it was actually fetch you wanted to wrap you could instead just do

```<code>var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
</code>```

EDIT: If you are using the angular HttpClient then there is no need to wrap it as it is already an observable. To get progress updates as well as the final response something like the following should work

```<code>const req = new HttpRequest('POST', 'http://api.server.com', body, {
    reportProgress: true
});

this._http.request(req)
.filter((event) => event.type === HttpEventType.UploadProgress || event instanceof HttpResponse)
.map((event) => {
    if (event.type === HttpEventType.UploadProgress) {
        const percentDone = Math.round(100 * event.loaded / event.total);
        return { type: 'uploadProgress', percentDone };
    } else if (event instanceof HttpResponse) {
        return { type: 'httpResponse', status: event.status };
    }
})
.subscribe((response) => {
    if (response.type === 'uploadProgress') {
        console.log(`upload still in progress - percent done = ${response.percentDone}%`);
    } else {
        console.log(`upload completed  - status = ${response.status}`);
    }
});
</code>```

If in fact all you want to know is when all the request have completed, and don't need the progress updates from each then rather than pushing the requests into an array a better option might be to use a forkJoin - which is similar to a promise.all in that you only get an output from the observable once all of the sub observables have completed - https://www.learnrxjs.io/operators/combination/forkjoin.html

Body:
Not sure if this is what you mean, but you can wrap an async http call like so

const httpStream = Observable.create(observer => {

    fetch('http://server.com')
      .then(response => response.json())
      .then(data => {
        observer.next(data); // if http call provides progress as well as completion
                             // these can all be pushed with observer.next()
        observer.complete();
      })
      .catch(err => observer.error(err));

  });

  httpStream.subscribe(data => console.log(data));

Of course if it was actually fetch you wanted to wrap you could instead just do

var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));

EDIT: If you are using the angular HttpClient then there is no need to wrap it as it is already an observable. To get progress updates as well as the final response something like the following should work

const req = new HttpRequest('POST', 'http://api.server.com', body, {
    reportProgress: true
});

this._http.request(req)
.filter((event) => event.type === HttpEventType.UploadProgress || event instanceof HttpResponse)
.map((event) => {
    if (event.type === HttpEventType.UploadProgress) {
        const percentDone = Math.round(100 * event.loaded / event.total);
        return { type: 'uploadProgress', percentDone };
    } else if (event instanceof HttpResponse) {
        return { type: 'httpResponse', status: event.status };
    }
})
.subscribe((response) => {
    if (response.type === 'uploadProgress') {
        console.log(`upload still in progress - percent done = ${response.percentDone}%`);
    } else {
        console.log(`upload completed  - status = ${response.status}`);
    }
});

If in fact all you want to know is when all the request have completed, and don't need the progress updates from each then rather than pushing the requests into an array a better option might be to use a forkJoin - which is similar to a promise.all in that you only get an output from the observable once all of the sub observables have completed - https://www.learnrxjs.io/operators/combination/forkjoin.html


问:
win 32 console app crashes when running strcmp code
```<code>void emt_card_discount()
{
    char emt_card[8];
    char*none[5];
    int new_total_amt;

    printf("\tkey in EMT card number (7 figure) if present or type 'none': \n\t >> ");
    scanf_s("%s", &emt_card);

    if (strcmp(emt_card,"none") == 0)
    {
        printf("\tyour seat price is: %.2f\n",total_amt);
    }

    else
    {
        new_total_amt = total_amt*0.15;
        printf("\tyour seat price is(RM):%.2f\n", new_total_amt);
    }
}
</code>```

This is my code for strcmp.this particular basically functions to provide the user booking the ticket to enter card info to get a special discount..but whenever i get to this part of the code the whole console app crashes..

.

答:
scanf_s() is not a drop-in replacement for scanf(). With scanf_s(), a %s, %c or %[ conversion needs two arguments, the second one is the size of the target buffer.

Originally, scanf_s() (and "friends") is a Microsoft idea, and the Microsoft definition is slightly different from the now standardized scanf_s(). The Microsoft version defines the size in bytes of type unsigned, while the C standard defines it in elements of type rsize_t (which is the same number here, but still incompatible ...).

Correct usage of scanf_s() would look like this in your code:

```<code>char emt_card[8];
[...]
int rc = scanf_s("%s", emt_card, 8U); // microsoft
int rc = scanf_s("%s", emt_card, (rsize_t)8); // standard C
if (rc < 1)
{
    // handle error, either EOF or 0 (buffer was too small for input)
}
</code>```

Note also there's no address-of operator in the call. emt_card already evaluates to a pointer to the first element (char *), while &emt_card would be a pointer to the array (char (*)[8]). The values are the same, still &emt_card would have the wrong type, so it's undefined behavior.

The "funny" thing is that you forgot exactly the size which was the reason to introduce scanf_s() in the first place. scanf("%s", ...) is alyways a bug because it will overflow any buffer. But there's a way to write this code correctly with just scanf() as well by using a field width:

```<code>int rc = scanf("%7s", emt_card); // read up to 7 bytes, leaving room for the `0` byte
if (rc < 1)
{
    // handle error
}
</code>```

The difference here is that if the input is too long, the scanf() with a field-width will just stop consuming input, while scanf_s() with a size given and without field-width would fail the conversion.

I'd personally suggest to never use scanf_s() and friends because of the incompatible definitions. scanf() is sufficient if you use field widths. On a side note, scanf() for interactive input is almost always very problematic, I'd suggest to not use it at all. See my beginners' guide away from scanf() for more information and alternatives.

Body:
void emt_card_discount()
{
    char emt_card[8];
    char*none[5];
    int new_total_amt;

    printf("\tkey in EMT card number (7 figure) if present or type 'none': \n\t >> ");
    scanf_s("%s", &emt_card);

    if (strcmp(emt_card,"none") == 0)
    {
        printf("\tyour seat price is: %.2f\n",total_amt);
    }

    else
    {
        new_total_amt = total_amt*0.15;
        printf("\tyour seat price is(RM):%.2f\n", new_total_amt);
    }
}

This is my code for strcmp.this particular basically functions to provide the user booking the ticket to enter card info to get a special discount..but whenever i get to this part of the code the whole console app crashes..

.

Body:
scanf_s() is not a drop-in replacement for scanf(). With scanf_s(), a %s, %c or %[ conversion needs two arguments, the second one is the size of the target buffer.

Originally, scanf_s() (and "friends") is a Microsoft idea, and the Microsoft definition is slightly different from the now standardized scanf_s(). The Microsoft version defines the size in bytes of type unsigned, while the C standard defines it in elements of type rsize_t (which is the same number here, but still incompatible ...).

Correct usage of scanf_s() would look like this in your code:

char emt_card[8];
[...]
int rc = scanf_s("%s", emt_card, 8U); // microsoft
int rc = scanf_s("%s", emt_card, (rsize_t)8); // standard C
if (rc < 1)
{
    // handle error, either EOF or 0 (buffer was too small for input)
}

Note also there's no address-of operator in the call. emt_card already evaluates to a pointer to the first element (char *), while &emt_card would be a pointer to the array (char (*)[8]). The values are the same, still &emt_card would have the wrong type, so it's undefined behavior.

The "funny" thing is that you forgot exactly the size which was the reason to introduce scanf_s() in the first place. scanf("%s", ...) is alyways a bug because it will overflow any buffer. But there's a way to write this code correctly with just scanf() as well by using a field width:

int rc = scanf("%7s", emt_card); // read up to 7 bytes, leaving room for the `0` byte
if (rc < 1)
{
    // handle error
}

The difference here is that if the input is too long, the scanf() with a field-width will just stop consuming input, while scanf_s() with a size given and without field-width would fail the conversion.

I'd personally suggest to never use scanf_s() and friends because of the incompatible definitions. scanf() is sufficient if you use field widths. On a side note, scanf() for interactive input is almost always very problematic, I'd suggest to not use it at all. See my beginners' guide away from scanf() for more information and alternatives.


问:
Angular: Reading json from web-api
I would like to create an Angular service to load JSON data from my Web API but I have no idea how to do this. The data looks like this:</p>
```<code>{"employees":[{"id":1,"name":"Peter"},{"id":2,"name":"Paul"}]}
</code>```

答:
Use http.get method to get data from the web services.</p>

```<code>this.http.get('pass your url')
.subscribe(
   data => {
   console.log(JSON.parse(data));
},
error => {
   console.log(error);
});
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular: Reading json from web-api

Body:
I would like to create an Angular service to load JSON data from my Web API but I have no idea how to do this. The data looks like this:

{"employees":[{"id":1,"name":"Peter"},{"id":2,"name":"Paul"}]}

Body:
Use http.get method to get data from the web services.

this.http.get('pass your url')
.subscribe(
   data => {
   console.log(JSON.parse(data));
},
error => {
   console.log(error);
});


问:
running .NET in sles 11
i'm trying to figure out if it is possible to run .NET on the server at work. we mainly run COBOL but i want to know if it is possible to run .NET also.
this is what i can find that is installed on the server:

```<code>cobol v5.1.00
PRN=RXCVF/AAP:9t.r3.51.13
PTI=WrapPack 12
PTI=SUSE Linux Enterprise Server 11 (x86_64)
PTI=ES

LSB Version:    n/a
Distributor ID: SUSE LINUX
Description:    SUSE Linux Enterprise Server 11 (x86_64)
Release:        11
Codename:       n/a
</code>```

i don't think i'm allowed to give much more info than this. i hope this can give me something that i know what i can do to make .net run.

regards,

bjorn

答:
You can use Mono. It isn't a perfect clone of .Net, and Windows apps might not work perfectly on it. For example, it does not support WPF. However, it does have basic functionality.

https://en.wikipedia.org/wiki/Mono_(software)#Current_status_and_roadmap

Title: running .NET in sles 11

Body:
i'm trying to figure out if it is possible to run .NET on the server at work. we mainly run COBOL but i want to know if it is possible to run .NET also.
this is what i can find that is installed on the server:

cobol v5.1.00
PRN=RXCVF/AAP:9t.r3.51.13
PTI=WrapPack 12
PTI=SUSE Linux Enterprise Server 11 (x86_64)
PTI=ES

LSB Version:    n/a
Distributor ID: SUSE LINUX
Description:    SUSE Linux Enterprise Server 11 (x86_64)
Release:        11
Codename:       n/a

i don't think i'm allowed to give much more info than this. i hope this can give me something that i know what i can do to make .net run.

regards,

bjorn


问:
iPhone - core data NSSet relationship
I have two entities Books and Bundles. A book can belong to none, to one or more bundles. So I have a bi-directional to-many relationship between these entities.

I am about to setup the value of this relationship on the Book part.

If the attribute was a regular one, I would simply do something like

```<code>aBook.title = @"this is my title";
</code>```

If I wanted to set the title for a book. But as this is a bi-directional to-many relationship, core data says it is a NSSet attribute.

My question is: how do I set and read values from this attribute?

I first thought it was a regular NSSet. So, after reading the product I simple did

```<code>NSSet *aSet = Book.fromBundle;
</code>```

but for my dismay aSet contained zero objects

So I thought I was setting it in error.
I set it earlier doing

```<code>Book.fromBundle = [NSSet setWithObject:aBundle];
</code>```

(yes, all changes were saved to the database)

am I missing something? Thanks

答:
It is a normal set, but core data advises against directly assigning a new set (for this very reason). If you are using a custom class, the standard implementation would include addFromBundleObject: and removeFromBundleObject: methods for you to use. If you do not use a custom class, or choose not to implement these methods, then you can use the mutableSetValueForKey: method to get a set which you can modify.

```<code>NSMutableSet *mutableSet = [book mutableSetValueForKey:@"fromBundle"];
[mutableSet addObject:aBundle];
</code>```

Title: iPhone - core data NSSet relationship

Body:
I have two entities Books and Bundles. A book can belong to none, to one or more bundles. So I have a bi-directional to-many relationship between these entities.

I am about to setup the value of this relationship on the Book part.

If the attribute was a regular one, I would simply do something like

aBook.title = @"this is my title";

If I wanted to set the title for a book. But as this is a bi-directional to-many relationship, core data says it is a NSSet attribute.

My question is: how do I set and read values from this attribute?

I first thought it was a regular NSSet. So, after reading the product I simple did

NSSet *aSet = Book.fromBundle;

but for my dismay aSet contained zero objects

So I thought I was setting it in error.
I set it earlier doing

Book.fromBundle = [NSSet setWithObject:aBundle];

(yes, all changes were saved to the database)

am I missing something? Thanks

Body:
It is a normal set, but core data advises against directly assigning a new set (for this very reason). If you are using a custom class, the standard implementation would include addFromBundleObject: and removeFromBundleObject: methods for you to use. If you do not use a custom class, or choose not to implement these methods, then you can use the mutableSetValueForKey: method to get a set which you can modify.

NSMutableSet *mutableSet = [book mutableSetValueForKey:@"fromBundle"];
[mutableSet addObject:aBundle];


问:
c-sharp Get working hours within a time span
Given multiple time span, how can I get an array that gives me number of working hours for a day.

The working hours start at 09:00 and end at 17:00

Examples:

15-Nov-2017 16:00 - 17-Nov-2017 12:00 -> Should give me an array of [1,8,3]

15-Nov-2017 09:00 - 17-Nov-2017 12:00 -> Should give me an array of [8,8,1] (This seems easy as I can do Hrs / 8 and Hrs % 8 to get the result.)

16-Nov-2017 15:00 - 17-Nov-2017 15:00 -> Should give me an array of [2,6]

This is the method that currently gives me total working hours between the start time and end time:

```<code>protected double getWorkingHrs(DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    double count = 0;

    for (var i = _dtTaskStart; i < _dtTaskEnd; i = i.AddHours(1))
    {
        if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        {
            if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)
            {
                count++;
            }
        }
    }

    return count;
}
</code>```

Any help would be appreciated.

Task showed like this in 8 hour blocks. So when I add a 20 Hour task, I have to break them down into sets and display them in the grid. I have to split them as chances are the task on different day might get assigned to a different user and may have different notes etc.

Cheers

答:
While not the prettiest (doing a ratcheting loop over datetimes by adding hours is a tad inelegant IMHO.), your function can be adapted to provide an enumerable with the number of working hours (or business hours as they are more commonly called) for each day as follows : </p>

```<code>protected IEnumerable<double> getWorkingHrsPerDay(DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    double count = 0;
    DateTime lastHandledDate = _dtTaskStart.Date;
    for (var i = _dtTaskStart; i < _dtTaskEnd; i = i.AddHours(1))
    {
        if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        {
            if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)
            {
                count++;
            }
        }
        //if we have started to count the hours for a new day
        if (lastHandledDate.Date != i.Date)
        {
            lastHandledDate = i.Date;
            double hourCount = count;
            //reset our hour count
            count = 0;
            //we return the count of the last day
            yield return hourCount;
        }
        lastHandledDate = i.Date;
    }
}
</code>```

<p>you could then do the following with LINQ's ToArray method : </p>

```<code>double[] hoursPerDay = getWorkingHrsPerDay(beginDate, endDate).ToArray();
</code>```

Body:
Given multiple time span, how can I get an array that gives me number of working hours for a day.

The working hours start at 09:00 and end at 17:00

Examples:

15-Nov-2017 16:00 - 17-Nov-2017 12:00 -> Should give me an array of [1,8,3]

15-Nov-2017 09:00 - 17-Nov-2017 12:00 -> Should give me an array of [8,8,1] (This seems easy as I can do Hrs / 8 and Hrs % 8 to get the result.)

16-Nov-2017 15:00 - 17-Nov-2017 15:00 -> Should give me an array of [2,6]

This is the method that currently gives me total working hours between the start time and end time:

protected double getWorkingHrs(DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    double count = 0;

    for (var i = _dtTaskStart; i < _dtTaskEnd; i = i.AddHours(1))
    {
        if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        {
            if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)
            {
                count++;
            }
        }
    }

    return count;
}

Any help would be appreciated.

Task showed like this in 8 hour blocks. So when I add a 20 Hour task, I have to break them down into sets and display them in the grid. I have to split them as chances are the task on different day might get assigned to a different user and may have different notes etc.

Cheers

Body:
While not the prettiest (doing a ratcheting loop over datetimes by adding hours is a tad inelegant IMHO.), your function can be adapted to provide an enumerable with the number of working hours (or business hours as they are more commonly called) for each day as follows :

protected IEnumerable<double> getWorkingHrsPerDay(DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    double count = 0;
    DateTime lastHandledDate = _dtTaskStart.Date;
    for (var i = _dtTaskStart; i < _dtTaskEnd; i = i.AddHours(1))
    {
        if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        {
            if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)
            {
                count++;
            }
        }
        //if we have started to count the hours for a new day
        if (lastHandledDate.Date != i.Date)
        {
            lastHandledDate = i.Date;
            double hourCount = count;
            //reset our hour count
            count = 0;
            //we return the count of the last day
            yield return hourCount;
        }
        lastHandledDate = i.Date;
    }
}

you could then do the following with LINQ's ToArray method :

double[] hoursPerDay = getWorkingHrsPerDay(beginDate, endDate).ToArray();


问:
jtextfield increment by 1 starting from B3001 when click add button in swing
My bill number(using jtextfield) must auto increment by 1 after clicking submit button. I need sequtenial values in format like B3001,B3002, and so on.... Kindly plz help me</p>

```<code>public static class SequentialNumber
{
       private static int currentNumber=3000;
       public static String GetNextNumber()
       {
            currentNumber++;
            return "B"+currentNumber;
       }
}
public Printbill() {

    contentPane1 = new JPanel();
    contentPane1.setBackground(Color.WHITE);
    contentPane1.setBorder(new EmptyBorder(5, 5, 5, 5));

    contentPane1.setLayout(null);

    dcfield = new JTextField();

    dcfield.setBounds(553, 109, 86, 20);
    contentPane1.add(dcfield);
    dcfield.setColumns(10);
    String ContractNo=SequentialNumber.GetNextNumber();
    dcfield.setText(ContractNo);
    JButton btnAdd = new JButton("ADD");
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
          Printbill p=new Printbill();
          dispose();
            p.setVisible(true);
            SequentialNumber s=new SequentialNumber();
            String stt=s.GetNextNumber();
           dcfield.setText(stt);
        }
    });

 }
}
</code>```

答:
Here is the working code

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

public class Printbill extends JFrame {
    public static class SequentialNumber {
        private static int currentNumber = 3000;

        public static String GetNextNumber() {
            currentNumber++;
            return "B" + currentNumber;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Printbill();
            }
        });
    }

    public Printbill() {

        JPanel contentPane1 = new JPanel();
        contentPane1.setBackground(Color.WHITE);
        contentPane1.setBorder(new EmptyBorder(5, 5, 5, 5));

        contentPane1.setLayout(new BorderLayout(5, 5));

        final JTextField dcfield = new JTextField();

        contentPane1.add(dcfield);
        dcfield.setColumns(10);
        String contractNo = SequentialNumber.GetNextNumber();
        dcfield.setText(contractNo);
        JButton btnAdd = new JButton("ADD");
        contentPane1.add(btnAdd, BorderLayout.EAST);
        getContentPane().add(contentPane1);
        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                String stt = SequentialNumber.GetNextNumber();
                dcfield.setText(stt);
            }
        });
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

    }
}
</code>```

What's wrong with your code:

You've tried to use absolute layout (setLayout(null)). It's bad practice, so I've change the layout to BorderLayout. After that I've added pack() to set the appropriate size for window (this method works only with a non-null layout). For more information read here.

I've changed action listener so it only update text field.

SwingUtilities.invokeLater is required for correct start of Swing application. All widget initialisation/manipulation must be performed in Event Dispatcher Thread (EDT). SwingUtilities.invokeLater allows to call a piece of code in EDT.

Body:
My bill number(using jtextfield) must auto increment by 1 after clicking submit button. I need sequtenial values in format like B3001,B3002, and so on.... Kindly plz help me

public static class SequentialNumber
{
       private static int currentNumber=3000;
       public static String GetNextNumber()
       {
            currentNumber++;
            return "B"+currentNumber;
       }
}
public Printbill() {

    contentPane1 = new JPanel();
    contentPane1.setBackground(Color.WHITE);
    contentPane1.setBorder(new EmptyBorder(5, 5, 5, 5));

    contentPane1.setLayout(null);

    dcfield = new JTextField();

    dcfield.setBounds(553, 109, 86, 20);
    contentPane1.add(dcfield);
    dcfield.setColumns(10);
    String ContractNo=SequentialNumber.GetNextNumber();
    dcfield.setText(ContractNo);
    JButton btnAdd = new JButton("ADD");
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
          Printbill p=new Printbill();
          dispose();
            p.setVisible(true);
            SequentialNumber s=new SequentialNumber();
            String stt=s.GetNextNumber();
           dcfield.setText(stt);
        }
    });

 }
}

Body:
Here is the working code

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

public class Printbill extends JFrame {
    public static class SequentialNumber {
        private static int currentNumber = 3000;

        public static String GetNextNumber() {
            currentNumber++;
            return "B" + currentNumber;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Printbill();
            }
        });
    }

    public Printbill() {

        JPanel contentPane1 = new JPanel();
        contentPane1.setBackground(Color.WHITE);
        contentPane1.setBorder(new EmptyBorder(5, 5, 5, 5));

        contentPane1.setLayout(new BorderLayout(5, 5));

        final JTextField dcfield = new JTextField();

        contentPane1.add(dcfield);
        dcfield.setColumns(10);
        String contractNo = SequentialNumber.GetNextNumber();
        dcfield.setText(contractNo);
        JButton btnAdd = new JButton("ADD");
        contentPane1.add(btnAdd, BorderLayout.EAST);
        getContentPane().add(contentPane1);
        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                String stt = SequentialNumber.GetNextNumber();
                dcfield.setText(stt);
            }
        });
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

    }
}

What's wrong with your code:

You've tried to use absolute layout (setLayout(null)). It's bad practice, so I've change the layout to BorderLayout. After that I've added pack() to set the appropriate size for window (this method works only with a non-null layout). For more information read here.

I've changed action listener so it only update text field.

SwingUtilities.invokeLater is required for correct start of Swing application. All widget initialisation/manipulation must be performed in Event Dispatcher Thread (EDT). SwingUtilities.invokeLater allows to call a piece of code in EDT.


问:
How do I get a Spring boot to parse thymeleaf-extras-springsecurity tags?
I am creating a website using Spring Boot for the first time. I am using a test page to show that once the user has logged in, the words, "Authenticated" to appear on the screen when the user has logged in.

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<h2>Thymleaf example</h2>
<p sec:authorize="hasRole('ROLE_USER')">
    Authenticated
</p>
</body>
</html>
</code>```

However, problem is that the tag with the sec:authorize remains unedited and unparsed. As a result, the Authenticated word appears regardless of whether a user logged in or not. Printing the user's authorities from controller confirms this.

my pom.xml file has the following dependencies.

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    ... dependencies for mysql and jdbc are omitted.
</code>```

Any help is appreciated.
Note, I am using Spring Boot, so JAVA configurations are preferred over XML configurations.

答:
1) Please add following into your prom.xml file within the  tag to resolve java.lang.ClassNotFoundException: org.thymeleaf.dom.Attribute Exeption.

```<code><thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>
</code>```

2) Add mentioned in the last post, add the following bean into your WebSecurityConfig class which extends WebSecurityConfigurerAdapter

```<code>@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver, SpringSecurityDialect sec) {
    final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    templateEngine.addDialect(sec); // Enable use of "sec"
    return templateEngine;
}
</code>```

3) Add following dependency, please note about the version, you need to force 3.0.1.RELEASE version

```<code><dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.1.RELEASE</version>
</dependency>
</code>```

Body:
I am creating a website using Spring Boot for the first time. I am using a test page to show that once the user has logged in, the words, "Authenticated" to appear on the screen when the user has logged in.

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

Thymleaf example

    Authenticated

However, problem is that the tag with the sec:authorize remains unedited and unparsed. As a result, the Authenticated word appears regardless of whether a user logged in or not. Printing the user's authorities from controller confirms this.

my pom.xml file has the following dependencies.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    ... dependencies for mysql and jdbc are omitted.

Any help is appreciated.
Note, I am using Spring Boot, so JAVA configurations are preferred over XML configurations.

Body:
1) Please add following into your prom.xml file within the  tag to resolve java.lang.ClassNotFoundException: org.thymeleaf.dom.Attribute Exeption.

<thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>

2) Add mentioned in the last post, add the following bean into your WebSecurityConfig class which extends WebSecurityConfigurerAdapter

@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver, SpringSecurityDialect sec) {
    final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    templateEngine.addDialect(sec); // Enable use of "sec"
    return templateEngine;
}

3) Add following dependency, please note about the version, you need to force 3.0.1.RELEASE version

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.1.RELEASE</version>
</dependency>


问:
How do I fetch the value from a key in firebase for my android app?
I am very new to firebase and I am unable to fetch the content of the key value. I tried out few things but all were unsuccessful.

Can anyone help me out in fetching the data please?

My firebase database - Firebase Database Structure:

My code -

```<code>public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar dashboard_toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private FirebaseAuth mAuth;
    DatabaseReference rootRef, teacher, teacherPost;

    String str;
    TextView textView;

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

      /*  str = (String) getIntent().getExtras().get("temp");*/
        textView = (TextView) findViewById(R.id.institute_news);

        mAuth = FirebaseAuth.getInstance();
        dashboard_toolbar = (Toolbar) findViewById(R.id.dashboard_toolbar);
        setSupportActionBar(dashboard_toolbar);
        getSupportActionBar().setTitle("Dashboard");
        dashboard_toolbar.setTitleTextColor(0xFFFFFFFF);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawable);
        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, dashboard_toolbar, R.string.open, R.string.close);
        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
        mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
        mActionBarDrawerToggle.syncState();

        dashboard_toolbar.post(new Runnable() {
            @Override
            public void run() {
                Drawable d = ResourcesCompat.getDrawable(getResources(), R.drawable.actionmenu, null);
                dashboard_toolbar.setNavigationIcon(d);
            }
        });

        NavigationView navigationView = (NavigationView) mDrawerLayout.findViewById(R.id.navigationView);
        navigationView.setNavigationItemSelectedListener(this);

        rootRef = FirebaseDatabase.getInstance().getReference();
        teacher = rootRef.child("admin").child("classPost");
        teacherPost = teacher.child("post");

        String mGroupId = teacherPost.push().getKey();
        Toast.makeText(this, "" + teacherPost, Toast.LENGTH_SHORT).show();
        textView.setText(mGroupId);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.nav_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mActionBarDrawerToggle.onOptionsItemSelected(item))
            return  true;
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.aboutUs) {

        } else if (id == R.id.help) {

        } else if (id == R.id.report) {

        } else if (id == R.id.logoutmenu) {

            mAuth.signOut();
            sendToStart();
        } else if (id == R.id.setting) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void getAttendance(View view) {
        Toast.makeText(this, "Attendance Details Apk Fire here", Toast.LENGTH_LONG).show();
    }

    public void trackChild(View view) {

        Toast.makeText(this, "child tracker apk fire here Here", Toast.LENGTH_LONG).show();
    }

    public void getEwallet(View view) {

        Toast.makeText(this, "Ewallet Apk Fire Here", Toast.LENGTH_LONG).show();

    }

    public void getHealth(View view) {
        Toast.makeText(this, "Health apk fire here", Toast.LENGTH_LONG).show();

    }

    public void getMessageBoardDetails(View view) {
        startActivity(new Intent(this,MessageBoard.class));
    }

    public void startChat(View view) {

        startActivity(new Intent(this,Chat.class));
    }

    private void sendToStart() {
        startActivity(new Intent(Dashboard.this,Start.class));
        finish();
    }

    public void readMore(View view) {

        startActivity(new Intent(this,InstituteMessageBoard.class));
    }
}
</code>```

答:
```<code>DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("admin").child("classPost");
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot data : dataSnapshot.getChildren()){
     String retrieveposts=data.child("posts").getValue().toString();
    }
    }
 @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
</code>```

I'am assuming you want the post's values inside the classPost.

Explaining the code:

```<code> DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("admin").child("classPost");
</code>```

The above is a reference to the location in the database. So child("admin").child("classPost"). You are referring to the location of the node classPost that is under the node admin, thus using child(node_name).

Now this:

```<code>ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot data : dataSnapshot.getChildren()){
     String retrieveposts=data.child("posts").getValue().toString();
    }
    }
</code>```

is a listener to be able to retrieve the values from the database. dataSnapshot here is the classPost. So when you write dataSnapshot.getChildren() it means you are getting the children of classPost and then data will iterate inside the children thus giving you the values of posts

Body:
I am very new to firebase and I am unable to fetch the content of the key value. I tried out few things but all were unsuccessful.

Can anyone help me out in fetching the data please?

My firebase database - Firebase Database Structure:

My code -

public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar dashboard_toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private FirebaseAuth mAuth;
    DatabaseReference rootRef, teacher, teacherPost;

    String str;
    TextView textView;

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

      /*  str = (String) getIntent().getExtras().get("temp");*/
        textView = (TextView) findViewById(R.id.institute_news);

        mAuth = FirebaseAuth.getInstance();
        dashboard_toolbar = (Toolbar) findViewById(R.id.dashboard_toolbar);
        setSupportActionBar(dashboard_toolbar);
        getSupportActionBar().setTitle("Dashboard");
        dashboard_toolbar.setTitleTextColor(0xFFFFFFFF);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawable);
        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, dashboard_toolbar, R.string.open, R.string.close);
        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
        mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
        mActionBarDrawerToggle.syncState();

        dashboard_toolbar.post(new Runnable() {
            @Override
            public void run() {
                Drawable d = ResourcesCompat.getDrawable(getResources(), R.drawable.actionmenu, null);
                dashboard_toolbar.setNavigationIcon(d);
            }
        });

        NavigationView navigationView = (NavigationView) mDrawerLayout.findViewById(R.id.navigationView);
        navigationView.setNavigationItemSelectedListener(this);

        rootRef = FirebaseDatabase.getInstance().getReference();
        teacher = rootRef.child("admin").child("classPost");
        teacherPost = teacher.child("post");

        String mGroupId = teacherPost.push().getKey();
        Toast.makeText(this, "" + teacherPost, Toast.LENGTH_SHORT).show();
        textView.setText(mGroupId);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.nav_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mActionBarDrawerToggle.onOptionsItemSelected(item))
            return  true;
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.aboutUs) {

        } else if (id == R.id.help) {

        } else if (id == R.id.report) {

        } else if (id == R.id.logoutmenu) {

            mAuth.signOut();
            sendToStart();
        } else if (id == R.id.setting) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void getAttendance(View view) {
        Toast.makeText(this, "Attendance Details Apk Fire here", Toast.LENGTH_LONG).show();
    }

    public void trackChild(View view) {

        Toast.makeText(this, "child tracker apk fire here Here", Toast.LENGTH_LONG).show();
    }

    public void getEwallet(View view) {

        Toast.makeText(this, "Ewallet Apk Fire Here", Toast.LENGTH_LONG).show();

    }

    public void getHealth(View view) {
        Toast.makeText(this, "Health apk fire here", Toast.LENGTH_LONG).show();

    }

    public void getMessageBoardDetails(View view) {
        startActivity(new Intent(this,MessageBoard.class));
    }

    public void startChat(View view) {

        startActivity(new Intent(this,Chat.class));
    }

    private void sendToStart() {
        startActivity(new Intent(Dashboard.this,Start.class));
        finish();
    }

    public void readMore(View view) {

        startActivity(new Intent(this,InstituteMessageBoard.class));
    }
}

Body:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("admin").child("classPost");
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot data : dataSnapshot.getChildren()){
     String retrieveposts=data.child("posts").getValue().toString();
    }
    }
 @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

I'am assuming you want the post's values inside the classPost.

Explaining the code:

 DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("admin").child("classPost");

The above is a reference to the location in the database. So child("admin").child("classPost"). You are referring to the location of the node classPost that is under the node admin, thus using child(node_name).

Now this:

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot data : dataSnapshot.getChildren()){
     String retrieveposts=data.child("posts").getValue().toString();
    }
    }

is a listener to be able to retrieve the values from the database. dataSnapshot here is the classPost. So when you write dataSnapshot.getChildren() it means you are getting the children of classPost and then data will iterate inside the children thus giving you the values of posts


问:
Add class to parent when child get a new class?
How can I add class .myclass to li when its child (a.nav-link) get class .active?

       Home

       Profile

```

答:
if you want to do this by checking when user click on link -

```<code>$(".nav-link").click(function() {
  if($(this).hasClass('active'))
  $(this).parent('li').addClass('myclass');
});
</code>```

and second way is by running loop on all links -

```<code>$("ul li a").each(function(index) {
      if($(this).hasClass('active'))
      $(this).parent('li').addClass('myclass');
    });
</code>```

Body:
if you want to do this by checking when user click on link -

$(".nav-link").click(function() {
  if($(this).hasClass('active'))
  $(this).parent('li').addClass('myclass');
});

and second way is by running loop on all links -

$("ul li a").each(function(index) {
      if($(this).hasClass('active'))
      $(this).parent('li').addClass('myclass');
    });


问:
Is ProxyCreationEnabled = false is equal to AsNoTracking() in Entity framework?
Is ProxyCreationEnabled = false is equal to AsNoTracking() in Entity framework?

And we can use AsNoTracking() in table level. but how to use AsNoTracking() in stored procedures.

答:
Proxies and tracking are two different, but combinable concepts.

Proxies generate a derived class at runtime for advanced features like lazy loading, property changed, etc. While proxies are usually coupled with a tracking context, the don't necessarily have to.

Tracking indicates whether or not your open context saves a reference to the returned object and is able to detect changes to it. It can do this with or without proxies. Without proxies the context "simply compares" all tracked references to their initial state when you call Save().


问:
How to solve this Close this "FileOutputStream"
How to solve this?

I am getting the below error : Close this "FileOutputStream". but i have closes it already in finally block

```<code>public void initHistoryForOldFile(File oldFile, String filePath) throws PIDException {

        InputStream inStream = null;
        OutputStream outStream = null;

        try {

            File historyFile = new File(StringUtil.append(filePath, File.separator, "history"));
            FileUtils.ensureDirectory(historyFile);

            File oldHistoryFile = new File(StringUtil.append(filePath, File.separator, "history", File.separator, oldFile.getName()));
            oldHistoryFile.createNewFile();

            if (oldFile.exists()) {
                inStream = new FileInputStream(oldFile);
                outStream = new FileOutputStream(oldHistoryFile);

                byte[] buffer = new byte[PIDConstants.IMAGE_FILE_SIZE_LIMIT];

                int length;
                // copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {

                    outStream.write(buffer, 0, length);

                }

                // delete the original file
                oldFile.delete();
            }

        } catch (IOException e) {
            LOGGER.error("Exception occured in historyUpdateForOldFIle", e);
        } finally {
            if (null != inStream) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    LOGGER.error("Exception occured whole closing inStream", e);
                }
            }
            if (null != outStream) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    LOGGER.error("Exception occured whole closing outStream", e);
                }
            }
        }
    }
</code>```

答:
If using java 7

You can use Try with resources

```<code>try(InputStream inStream = new FileInputStream(oldFile)){}
</code>```

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

Body:
How to solve this?

I am getting the below error : Close this "FileOutputStream". but i have closes it already in finally block

public void initHistoryForOldFile(File oldFile, String filePath) throws PIDException {

        InputStream inStream = null;
        OutputStream outStream = null;

        try {

            File historyFile = new File(StringUtil.append(filePath, File.separator, "history"));
            FileUtils.ensureDirectory(historyFile);

            File oldHistoryFile = new File(StringUtil.append(filePath, File.separator, "history", File.separator, oldFile.getName()));
            oldHistoryFile.createNewFile();

            if (oldFile.exists()) {
                inStream = new FileInputStream(oldFile);
                outStream = new FileOutputStream(oldHistoryFile);

                byte[] buffer = new byte[PIDConstants.IMAGE_FILE_SIZE_LIMIT];

                int length;
                // copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {

                    outStream.write(buffer, 0, length);

                }

                // delete the original file
                oldFile.delete();
            }

        } catch (IOException e) {
            LOGGER.error("Exception occured in historyUpdateForOldFIle", e);
        } finally {
            if (null != inStream) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    LOGGER.error("Exception occured whole closing inStream", e);
                }
            }
            if (null != outStream) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    LOGGER.error("Exception occured whole closing outStream", e);
                }
            }
        }
    }

Body:
If using java 7

You can use Try with resources

try(InputStream inStream = new FileInputStream(oldFile)){}

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.


问:
Lodash groupBy with moment
I am trying to group a bunch of dates by today, this week, this month and then previous months. However before I even get to this point I am struggling to get even a basic grouping by month.

```<code>const data = [{
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test77.com",
 createdAt: "2017-11-06T20:45:56.931Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-09-06T20:45:56.931Z",
 _id: "6gsb42PSSJt7PgsDG"
}, {
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test66,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-10-06T20:46:27.744Z",
 _id: "Md4wCnEsrQrWApnLS"
}, {
 campaign: "Gary",
 company_ID: "1",
 coreURL: "http://www.test55,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-07-06T20:46:27.744Z",
 _id: "5p44uiwRgqp35YXRf"
}
];

const grouper = 'updatedAt';

let groupedData = _
  .chain(data)
  .groupBy(datum => moment(datum.grouper).format("MM"))
</code>```

EDIT: However this only seems to group by "11" (todays Month)

Any help would be really appreciated

答:
Maybe you can use filter if you only need to current month, day, year .

```<code>const today = _.filter(data, d => moment(d.updatedAt).isSame(moment(), 'day'));
console.log(today);

const thisWeek = _.filter(data, d => moment(d.updatedAt).isSame(moment(), 'week'));
console.log(thisWeek);

const thisMonth = _.filter(data, d => moment(d.updatedAt).isSame(moment(), 'month'));
console.log(thisMonth);
</code>```

Or groupBy if you need all months (for all years)

```<code>const byMonth = _.groupBy(data, d => moment(d.updatedAt).month());
console.log(byMonth);
</code>```

https://jsbin.com/xidido/edit?js,console

Title: Lodash groupBy with moment

Body:
I am trying to group a bunch of dates by today, this week, this month and then previous months. However before I even get to this point I am struggling to get even a basic grouping by month.

const data = [{
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test77.com",
 createdAt: "2017-11-06T20:45:56.931Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-09-06T20:45:56.931Z",
 _id: "6gsb42PSSJt7PgsDG"
}, {
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test66,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-10-06T20:46:27.744Z",
 _id: "Md4wCnEsrQrWApnLS"
}, {
 campaign: "Gary",
 company_ID: "1",
 coreURL: "http://www.test55,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-07-06T20:46:27.744Z",
 _id: "5p44uiwRgqp35YXRf"
}
];

const grouper = 'updatedAt';

let groupedData = _
  .chain(data)
  .groupBy(datum => moment(datum.grouper).format("MM"))

EDIT: However this only seems to group by "11" (todays Month)

Any help would be really appreciated

Body:
Maybe you can use filter if you only need to current month, day, year .

const today = _.filter(data, d => moment(d.updatedAt).isSame(moment(), 'day'));
console.log(today);

const thisWeek = _.filter(data, d => moment(d.updatedAt).isSame(moment(), 'week'));
console.log(thisWeek);

const thisMonth = _.filter(data, d => moment(d.updatedAt).isSame(moment(), 'month'));
console.log(thisMonth);

Or groupBy if you need all months (for all years)

const byMonth = _.groupBy(data, d => moment(d.updatedAt).month());
console.log(byMonth);

https://jsbin.com/xidido/edit?js,console


问:
How to query data from MYSQLdb with date time now in Python 2.7?
I have got a table called 'TEST' and I have got a column called 'UPLOAD_TIME' what is a varchar(100) and the format is the next :

```<code>"2017-11-14 14:59:05.243974"
</code>```

How can I query data from this table if i want to resemble my 'UPLOAD_TIME' column with the actual date now, and select data where year-month-day are equal with my data?

```<code>connection = MySQLdb.connect(host='localhost',
    user='admin',
    passwd='****',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select 'column1', 'column2', 'column3', 'column4', 'column5', 'column6', 'UPLOAD_TIME', 'ID'
    union all
    select `column1`, `column2`, `column3`, `column4`, `column5`, `column6`, `UPLOAD_TIME`, `ID`
    from TEST
    into outfile '/tmp/test.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()
</code>```

WHERE datetime ='2017-11-14' is not an option for me, I want to resemble always to the actual date.

答:
This should work.

```<code>WHERE DATE_FORMAT(UPLOAD_TIME,'%Y-%m-%d')='2017-11-14'
</code>```

Link from comment: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate

Body:
I have got a table called 'TEST' and I have got a column called 'UPLOAD_TIME' what is a varchar(100) and the format is the next :

"2017-11-14 14:59:05.243974"

How can I query data from this table if i want to resemble my 'UPLOAD_TIME' column with the actual date now, and select data where year-month-day are equal with my data?

connection = MySQLdb.connect(host='localhost',
    user='admin',
    passwd='****',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select 'column1', 'column2', 'column3', 'column4', 'column5', 'column6', 'UPLOAD_TIME', 'ID'
    union all
    select `column1`, `column2`, `column3`, `column4`, `column5`, `column6`, `UPLOAD_TIME`, `ID`
    from TEST
    into outfile '/tmp/test.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()

WHERE datetime ='2017-11-14' is not an option for me, I want to resemble always to the actual date.

Body:
This should work.

WHERE DATE_FORMAT(UPLOAD_TIME,'%Y-%m-%d')='2017-11-14'

Link from comment: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate


问:
How to use IF with And and OR in Excell?
I am using a FIFA 8 dataset for a project. There are various fields like age, rating, value and wage. Now I want to make a column of whether the player should be bought or not. I want to make this in Excel. I want to use a condition such as:

```<code>IF(Age<30 & Rating >90 & Value>100) OR If (Age<25 & Rating >85 & Value >70 ) then buy
</code>```

How can I use this kind of different situations in one formula in Excel?

答:
Your original formula can be converted into Excel without too much trouble:

```<code>IF(Age<30 & Rating >90 & Value>100) OR IF (Age<25 & Rating >85 & Value >70)
</code>```

This becomes:

```<code>=OR(AND(Age<30, Rating>90, Value>100), AND(Age<25, Rating>85, Value >70)
</code>```

Of course, you would need to replace the named variables with actual cell references, but for the purpose of an easy to read answer, it seems OK.

Body:
I am using a FIFA 8 dataset for a project. There are various fields like age, rating, value and wage. Now I want to make a column of whether the player should be bought or not. I want to make this in Excel. I want to use a condition such as:

IF(Age<30 & Rating >90 & Value>100) OR If (Age<25 & Rating >85 & Value >70 ) then buy

How can I use this kind of different situations in one formula in Excel?

Body:
Your original formula can be converted into Excel without too much trouble:

IF(Age<30 & Rating >90 & Value>100) OR IF (Age<25 & Rating >85 & Value >70)

This becomes:

=OR(AND(Age<30, Rating>90, Value>100), AND(Age<25, Rating>85, Value >70)

Of course, you would need to replace the named variables with actual cell references, but for the purpose of an easy to read answer, it seems OK.


问:
Latex cline won't work properly
I would make the following table on latex with tabular.

```<code> \begin{table}[]
    \centering
    \begin{tabular}{|c|c|c|c|}
     \hline
       \multicolumn{2}{|c|}{\cellcolor[HTML]{C0C0C0}Ext Col 1} & \multicolumn{2}{c|}{\cellcolor[HTML]{C0C0C0}Ext Col 2} \\ \hline
        \multicolumn{4}{|c|}{\cellcolor[HTML]{C0C0C0}Ext Row 1}                                                          \\ \hline
           & V11   & V12   &   \\ \cline{2-3}
           & \multicolumn{2}{c|}{\cellcolor[HTML]{C0C0C0}Int Row 1}    &                          \\ \cline{2-3}
           & V21    & V22   &   \\ \hline
     \end{tabular}
   \end{table}
</code>```

The problem here is that the cline command above "Int Row 1" does not display the line, resulting as shown in the following picture:

I have read similar issue on SO, but I can't figure out the problem. Many thanks.

答: As suggested in the question linked by @Bobo Carr, replacing \cline with \hhline solves the issue.</p>

Title: Latex cline won't work properly

Body:
I would make the following table on latex with tabular.

 \begin{table}[]
    \centering
    \begin{tabular}{|c|c|c|c|}
     \hline
       \multicolumn{2}{|c|}{\cellcolor[HTML]{C0C0C0}Ext Col 1} & \multicolumn{2}{c|}{\cellcolor[HTML]{C0C0C0}Ext Col 2} \\ \hline
        \multicolumn{4}{|c|}{\cellcolor[HTML]{C0C0C0}Ext Row 1}                                                          \\ \hline
           & V11   & V12   &   \\ \cline{2-3}
           & \multicolumn{2}{c|}{\cellcolor[HTML]{C0C0C0}Int Row 1}    &                          \\ \cline{2-3}
           & V21    & V22   &   \\ \hline
     \end{tabular}
   \end{table}

The problem here is that the cline command above "Int Row 1" does not display the line, resulting as shown in the following picture:

I have read similar issue on SO, but I can't figure out the problem. Many thanks.