问:
Django renders information to wrong database field
so I was implementing a database in Django to take in username and password using the given Users model. However, when I hit submit the password gets taken into the email field. Any suggestions on what I could be doing wrong? This is for user signup. Thank you! could it be that Users does not come with a passwords section? How would I Add that in?

forms.py

```<code>   class UserRegistrationForm(forms.Form):
        username = forms.CharField(
            required = True,
            label = 'Username',
            max_length = 32
        )
        password = forms.CharField(
            required = True,
            label = 'Password',
            max_length = 32,
            widget = forms.PasswordInput()
        )
</code>```

views.py

```<code># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django import forms
from .forms import UserRegistrationForm
#from django.contrib.auth import views as auth_views

#from . import views
# Create your views here.

def login(request):
    return render(request, 'login.html')

def profiles(request):
    return render(request, 'profiles.html')

def signup(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            userObj = form.cleaned_data
            print(userObj)
            username = userObj['username']
            password =  userObj['password']
            if not (User.objects.filter(username=username).exists()):
                User.objects.create_user(username,password)
                user = authenticate(username = username, password = password)
                login(request)
                return HttpResponseRedirect('/')
            else:
                raise forms.ValidationError('Looks like a username with that email or password already exists')
    else:
        form = UserRegistrationForm()
    return render(request, 'signup_form.html', {'form': form})

def home(request):
    return render(request, 'home.html')
</code>```

signup.html

```<code><!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Login</title>
  {% load staticfiles %}
    <link rel="stylesheet" href="{% static 'signup.css' %}">
  </head>
<body>
</div>
<div class='login'>
  <div class='login_title'>
    <span>Sign Up</span>
  </div>
  <div class='login_fields'>
    <div class='login_fields__user'>
      <div class='icon'>
        <img src='http://d2nysvt2e2u12u.cloudfront.net/img/NPLwebsite17_header_mobile_accountBtn.png?v=34534534'>
      </div>

      <input placeholder='Username' type='text' name = 'username'>
        <div class='validation'>
          <img src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/217233/tick.png'>
        </div>
      </input>
    </div>

    <div class='login_fields__password'>
      <div class='icon'>
        <img src='http://upload.wikimedia.org/wikipedia/commons/9/9e/Lock_icon.png'>
      </div>
      <input placeholder='Password' type='password' name = 'password'>
      <div class='validation'>
          </div>

    </div>
    <div class='login_fields__submit'>
      <input type='submit' formmethod="post" value='Submit'>

<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>

    <script  src="{% static 'signup.js' %}"></script>

</body>
</html>
</code>```

答:
As the documentation shows, the signature for create_user is:

```<code>create_user(username, email=None, password=None, **extra_fields)
</code>```

So you are passing the password as the email argument. Instead, use a keyword argument:

```<code>User.objects.create_user(username, password=password)
</code>```

Body:
so I was implementing a database in Django to take in username and password using the given Users model. However, when I hit submit the password gets taken into the email field. Any suggestions on what I could be doing wrong? This is for user signup. Thank you! could it be that Users does not come with a passwords section? How would I Add that in?

forms.py

   class UserRegistrationForm(forms.Form):
        username = forms.CharField(
            required = True,
            label = 'Username',
            max_length = 32
        )
        password = forms.CharField(
            required = True,
            label = 'Password',
            max_length = 32,
            widget = forms.PasswordInput()
        )

views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django import forms
from .forms import UserRegistrationForm
#from django.contrib.auth import views as auth_views

#from . import views
# Create your views here.

def login(request):
    return render(request, 'login.html')

def profiles(request):
    return render(request, 'profiles.html')

def signup(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            userObj = form.cleaned_data
            print(userObj)
            username = userObj['username']
            password =  userObj['password']
            if not (User.objects.filter(username=username).exists()):
                User.objects.create_user(username,password)
                user = authenticate(username = username, password = password)
                login(request)
                return HttpResponseRedirect('/')
            else:
                raise forms.ValidationError('Looks like a username with that email or password already exists')
    else:
        form = UserRegistrationForm()
    return render(request, 'signup_form.html', {'form': form})

def home(request):
    return render(request, 'home.html')

signup.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Login</title>
  {% load staticfiles %}
    <link rel="stylesheet" href="{% static 'signup.css' %}">

    Sign Up

      <input placeholder='Username' type='text' name = 'username'>

      </input>

      <input placeholder='Password' type='password' name = 'password'>

      <input type='submit' formmethod="post" value='Submit'>

Body:
As the documentation shows, the signature for create_user is:

create_user(username, email=None, password=None, **extra_fields)

So you are passing the password as the email argument. Instead, use a keyword argument:

User.objects.create_user(username, password=password)


来源: stackexchange

问:
MapStruct requires Impl class
I have next classes:

Mapper

```<code>public interface DeviceTokensMapper {

    DeviceTokensMapper INSTANCE = Mappers.getMapper(DeviceTokensMapper.class);

    @Mappings({
            @Mapping(source = "tokenName", target = "tokenName"),
            @Mapping(source = "userOsType", target = "osType"),
    })

    DeviceTokensDTO toDeviceTokensDTO(DeviceTokens deviceTokens);
}
</code>```

Entity:

```<code>@Entity
public class DeviceTokens {

    @Id
    @Column(name="token_name", nullable = false)
    private String tokenName;

    @Column(name = "os", nullable = false)
    @Enumerated
    private UserOSType userOsType;

    public DeviceTokens() {}

    public DeviceTokens(String tokenName, UserOSType userOSType) {
        this.tokenName = tokenName;
        this.userOsType = userOSType;
    }

    public String getTokenName() {
        return tokenName;
    }

    public void setTokenName(String tokenName) {
        this.tokenName = tokenName;
    }

    public UserOSType getUserOsType() {
        return userOsType;
    }

    public void setUserOsType(UserOSType userOsType) {
        this.userOsType = userOsType;
    }
}
</code>```

DTO:

```<code>public class DeviceTokensDTO {

    private String tokenName;

    private UserOSType osType;

    public DeviceTokensDTO() {}

    public DeviceTokensDTO(String tokenName, UserOSType osType) {
        this.tokenName = tokenName;
        this.osType = osType;
    }

    public UserOSType getOsType() {
        return osType;
    }

    public void setOsType(UserOSType osType) {
        this.osType = osType;
    }

    public String getTokenName() {
        return tokenName;
    }

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

And method from spring service class where I use this mapping:

```<code>@Transactional
public DeviceTokensDTO storeToken(String tokenId, UserOSType userOsType) {
    DeviceTokens deviceTokens = new DeviceTokens(tokenId, userOsType);
    DeviceTokens newDevice = deviceTokensRepository.save(deviceTokens);

    return DeviceTokensMapper.INSTANCE.toDeviceTokensDTO(newDevice);
}
</code>```

When I run above method I see next exception:

ERROR [dispatcherServlet]:? - Servlet.service() for servlet
  [dispatcherServlet] in context with path [] threw exception [Handler
  processing failed; nested exception is
  java.lang.ExceptionInInitializerError] with root cause
  java.lang.ClassNotFoundException:
  dto.DeviceTokensMapperImpl

So why mapper require implementation class? Could please someone advise?
Thanks.

答:
if you use maven, you need to add mapstruct-processor dependency as follows:</p>

```<code><dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-jdk8</artifactId>
    <version>1.2.0.Final</version>
</dependency>
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.2.0.Final</version>
</dependency>
</code>```

ContentLicense: CC BY-SA 3.0

Title: MapStruct requires Impl class

Body:
I have next classes:

Mapper

public interface DeviceTokensMapper {

    DeviceTokensMapper INSTANCE = Mappers.getMapper(DeviceTokensMapper.class);

    @Mappings({
            @Mapping(source = "tokenName", target = "tokenName"),
            @Mapping(source = "userOsType", target = "osType"),
    })

    DeviceTokensDTO toDeviceTokensDTO(DeviceTokens deviceTokens);
}

Entity:

@Entity
public class DeviceTokens {

    @Id
    @Column(name="token_name", nullable = false)
    private String tokenName;

    @Column(name = "os", nullable = false)
    @Enumerated
    private UserOSType userOsType;

    public DeviceTokens() {}

    public DeviceTokens(String tokenName, UserOSType userOSType) {
        this.tokenName = tokenName;
        this.userOsType = userOSType;
    }

    public String getTokenName() {
        return tokenName;
    }

    public void setTokenName(String tokenName) {
        this.tokenName = tokenName;
    }

    public UserOSType getUserOsType() {
        return userOsType;
    }

    public void setUserOsType(UserOSType userOsType) {
        this.userOsType = userOsType;
    }
}

DTO:

public class DeviceTokensDTO {

    private String tokenName;

    private UserOSType osType;

    public DeviceTokensDTO() {}

    public DeviceTokensDTO(String tokenName, UserOSType osType) {
        this.tokenName = tokenName;
        this.osType = osType;
    }

    public UserOSType getOsType() {
        return osType;
    }

    public void setOsType(UserOSType osType) {
        this.osType = osType;
    }

    public String getTokenName() {
        return tokenName;
    }

    public void setTokenName(String tokenName) {
        this.tokenName = tokenName;
    }
}

And method from spring service class where I use this mapping:

@Transactional
public DeviceTokensDTO storeToken(String tokenId, UserOSType userOsType) {
    DeviceTokens deviceTokens = new DeviceTokens(tokenId, userOsType);
    DeviceTokens newDevice = deviceTokensRepository.save(deviceTokens);

    return DeviceTokensMapper.INSTANCE.toDeviceTokensDTO(newDevice);
}

When I run above method I see next exception:

ERROR [dispatcherServlet]:? - Servlet.service() for servlet
  [dispatcherServlet] in context with path [] threw exception [Handler
  processing failed; nested exception is
  java.lang.ExceptionInInitializerError] with root cause
  java.lang.ClassNotFoundException:
  dto.DeviceTokensMapperImpl

So why mapper require implementation class? Could please someone advise?
Thanks.

Body:
if you use maven, you need to add mapstruct-processor dependency as follows:

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-jdk8</artifactId>
    <version>1.2.0.Final</version>
</dependency>
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.2.0.Final</version>
</dependency>


问:
Forwarding keyboard events from one Windows control to another
In Delphi XE, I'm trying to implement an "instant search" feature - one that resembles Firefox's "search as you type" somewhat, but is better illustrated by a similar feature in an open source clipboard extender, Ditto:

There is a list of items that handles typical navigation events. However, any alphanumeric keys as well as navigation and editing commands (right/left arrows, shift+arrows, backspace, delete etc.) should be rerouted to the edit box below the list. An OnChange event of the edit box will trigger a refresh of the list.

The point of the UI is that user does not have to tab or shift-tab between the controls. The two controls (the list and the edit box) should 'feel" as if they were a single control. The behavior of the search UI should not be contingent on which control has focus.

It seems my best option is to forward certain keyboard events from the list control (I'm using TcxTreeList) to the edit box, and forward a handful of navigation keys from the edit box to the list. How can I achieve that?

Notes:

TcxTreeList supports incremental search of course, but this is not what I'm after. The search goes to an SQLite database and looks for substring matches. The list displays only the matching items from the db.

There is some overlap, e.g. both controls would normally handle VK_HOME and VK_END, but that's OK - in this case the keys would go to the list. I'll need to decide whether to forward each individual keypress, or handle it in the control that received it.

On Edit:
One obvious way seemed to be to invoke the respective KeyDown, KeyUp and KeyPress methods of the edit control, like so:

```<code>type
  THackEdit = class( TEdit );

procedure TMainForm.cxTreeList1KeyDown(Sender: TObject; var Key: Word;
    Shift: TShiftState);
begin
  THackEdit( edit1 ).KeyDown( Key, Shift );
end;
</code>```

Unfortunately, this has no effect. My guess is TEdit won't process key events unless it is focused. Using SendMessage( THackEdit( edit1 ).Handle, WM_KEYDOWN, Key, 0 ) has no effect, either.

答:
Not exactly what you are asking for, but for similar results, I use the following trick.

Assume you have one TEdit Edit1 and one TListbox Listbox1.

In the OnEnter event of Listbox1, simply yield focus to Edit1

```<code>procedure TForm1.ListBox1Enter(Sender: TObject);
 begin
  edit1.SetFocus;
 end;
</code>```

And in the OnKeyDown event of Edit1, use the up and down arrows to navigate the items of the listbox and use the enter key to move the selected item to the edit box.

```<code>procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
 var k:word;
 begin
  if (Shift=[]) and (key=VK_DOWN) then
   begin
    listbox1.ItemIndex:=listbox1.ItemIndex+1;
    key:=0;
   end
  else if (Shift=[]) and (key=VK_UP) then
   begin
    listbox1.ItemIndex:=listbox1.ItemIndex-1;
    key:=0;
   end
  else if (Shift=[]) and (key=VK_RETURN) then
   begin
    edit1.text:=listbox1.items[listbox1.itemindex];
   end;
 end;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In Delphi XE, I'm trying to implement an "instant search" feature - one that resembles Firefox's "search as you type" somewhat, but is better illustrated by a similar feature in an open source clipboard extender, Ditto:

There is a list of items that handles typical navigation events. However, any alphanumeric keys as well as navigation and editing commands (right/left arrows, shift+arrows, backspace, delete etc.) should be rerouted to the edit box below the list. An OnChange event of the edit box will trigger a refresh of the list.

The point of the UI is that user does not have to tab or shift-tab between the controls. The two controls (the list and the edit box) should 'feel" as if they were a single control. The behavior of the search UI should not be contingent on which control has focus.

It seems my best option is to forward certain keyboard events from the list control (I'm using TcxTreeList) to the edit box, and forward a handful of navigation keys from the edit box to the list. How can I achieve that?

Notes:

TcxTreeList supports incremental search of course, but this is not what I'm after. The search goes to an SQLite database and looks for substring matches. The list displays only the matching items from the db.

There is some overlap, e.g. both controls would normally handle VK_HOME and VK_END, but that's OK - in this case the keys would go to the list. I'll need to decide whether to forward each individual keypress, or handle it in the control that received it.

On Edit:
One obvious way seemed to be to invoke the respective KeyDown, KeyUp and KeyPress methods of the edit control, like so:

type
  THackEdit = class( TEdit );

procedure TMainForm.cxTreeList1KeyDown(Sender: TObject; var Key: Word;
    Shift: TShiftState);
begin
  THackEdit( edit1 ).KeyDown( Key, Shift );
end;

Unfortunately, this has no effect. My guess is TEdit won't process key events unless it is focused. Using SendMessage( THackEdit( edit1 ).Handle, WM_KEYDOWN, Key, 0 ) has no effect, either.

Body:
Not exactly what you are asking for, but for similar results, I use the following trick.

Assume you have one TEdit Edit1 and one TListbox Listbox1.

In the OnEnter event of Listbox1, simply yield focus to Edit1

procedure TForm1.ListBox1Enter(Sender: TObject);
 begin
  edit1.SetFocus;
 end;

And in the OnKeyDown event of Edit1, use the up and down arrows to navigate the items of the listbox and use the enter key to move the selected item to the edit box.

procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
 var k:word;
 begin
  if (Shift=[]) and (key=VK_DOWN) then
   begin
    listbox1.ItemIndex:=listbox1.ItemIndex+1;
    key:=0;
   end
  else if (Shift=[]) and (key=VK_UP) then
   begin
    listbox1.ItemIndex:=listbox1.ItemIndex-1;
    key:=0;
   end
  else if (Shift=[]) and (key=VK_RETURN) then
   begin
    edit1.text:=listbox1.items[listbox1.itemindex];
   end;
 end;


问:
Assigning all controllers with one register In DI Container
I have a fairly simple question, I am testing Autofac DI container under .net core 2.0 now for example i have a controller

```<code>public class ValuesController : Controller
{
    private readonly ITestModel _testModel;

    public ValuesController(ITestModel testModel)
    {
        _testModel = testModel;
    }
}
</code>```

And registered DI in startup:

```<code>    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        var builder = new ContainerBuilder();

        builder.RegisterType<TestModel>().As<ITestModel>();
        builder.Populate(services);
        var container = builder.Build();

        return container.Resolve<IServiceProvider>();
    }
</code>```

It works fine, but I've been wondering, what about if ill have twenty of those controllers and some 20 more logic classes with constructor with parameters with some interface do i need to register them in same manner, It would get really ugly in no time. So my question is, is it possible to register all controllers and classes that has only interfaces as parameters at once in this environment??

答: As the in comment was said, assembly scanning but with all referenced(filtered by interface of course), assembles did work as planned.</p>

Body:
I have a fairly simple question, I am testing Autofac DI container under .net core 2.0 now for example i have a controller

public class ValuesController : Controller
{
    private readonly ITestModel _testModel;

    public ValuesController(ITestModel testModel)
    {
        _testModel = testModel;
    }
}

And registered DI in startup:

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        var builder = new ContainerBuilder();

        builder.RegisterType<TestModel>().As<ITestModel>();
        builder.Populate(services);
        var container = builder.Build();

        return container.Resolve<IServiceProvider>();
    }

It works fine, but I've been wondering, what about if ill have twenty of those controllers and some 20 more logic classes with constructor with parameters with some interface do i need to register them in same manner, It would get really ugly in no time. So my question is, is it possible to register all controllers and classes that has only interfaces as parameters at once in this environment??


问:
Query in SQL from single table
I have a table with field Document Type. I want those records of Customer whose Sum(Amount) of Document Type 4 - Sum(Amount) of Document type 6 > 0 then those records of that Customer whose Document Type in (4,6) should be displayed.

答:
Lets assume that your Table name is TableA and Customer column name is CustomerID. </p>

<p>We can achieve the requirement by below SQL logic.  </p>

```<code>   select x.* from TableA x

    join

    (select * from
    (select dt4.customerID, sum_amount_dt4-sum_amount_dt6 as dt4minusdt6
    from
    (select CustomerID,sum(Amount) as sum_amount_dt4 from TableA a
    where a.Docutype=4)dt4
    join
    (select CustomerID,sum(Amount) as sum_amount_dt6 from TableA a
    where a.Docutype=6)dt6
    on dt4.customerID=dt6.customerID
    )dt46
    where dt46.dt4minusdt6>0 ) y

on x.customerID=y.customerID
</code>```

Title: Query in SQL from single table

Body:
Lets assume that your Table name is TableA and Customer column name is CustomerID.

We can achieve the requirement by below SQL logic.

   select x.* from TableA x

    join

    (select * from
    (select dt4.customerID, sum_amount_dt4-sum_amount_dt6 as dt4minusdt6
    from
    (select CustomerID,sum(Amount) as sum_amount_dt4 from TableA a
    where a.Docutype=4)dt4
    join
    (select CustomerID,sum(Amount) as sum_amount_dt6 from TableA a
    where a.Docutype=6)dt6
    on dt4.customerID=dt6.customerID
    )dt46
    where dt46.dt4minusdt6>0 ) y

on x.customerID=y.customerID


问:
jQuery Flot.js: Line chart points not centered with x-axis grid line
My points do not appear centered with the grid line of the x-axis as visible in the screenshot below:

The options I am using are as follows:

```<code>    var options = {
      grid: {
        show: true,
        aboveData: false,
        color: "#3f3f3f",
        labelMargin: 10,
        axisMargin: 0,
        borderWidth: 0,
        borderColor: null,
        minBorderMargin: 5,
        clickable: true,
        hoverable: true,
        autoHighlight: true,
        mouseActiveRadius: 100
      },
      series: {
        lines: {
          show: true,
          fill: true,
          lineWidth: 2,
          steps: false
        },
        points: {
          show: true,
          radius: 4.5,
          symbol: "circle",
          lineWidth: 3.0
        }
      },
      legend: {
        position: "ne",
        margin: [0, -15],
        noColumns: 0,
        labelBoxBorderColor: null,
        labelFormatter: function(label, series) {
          // just add some space to labes
          return label + '  ';
        },
        width: 40,
        height: 1
      },
      colors: chartColours,
      shadowSize: 0,
      tooltip: true, //activate tooltip
      tooltipOpts: {
        content: "%s: %y.0",
        xDateFormat: "%d/%m",
        shifts: {
          x: -30,
          y: -50
        },
        defaultTheme: false
      },
      yaxis: {
        min: 0,
        tickDecimals:0
      },
      xaxis: {
        mode: "time",
        minTickSize: tickSize,
        timeformat: tformat,
        min: chartMinDate,
        max: chartMaxDate
      }
    };
</code>```

My data set is a time-series, and the labels values is also coming from the same data set so the dates should line up with the points. However it is offset while no option for this exists. What am I doing wrong?

答:
I got the solution from this link

points aren't aligned with the x axis on flot chart

And

https://code.google.com/archive/p/flot/issues/608

It seems Flot chart requires the time in UTC format.

For me it worked by just adding the "timezone:"browser"" in "xaxis".

After addition, my "xaxis" looks like below :

```<code> xaxis: {
           mode: "time",
           minTickSize: [1, "day"],
           timeformat: "%d-%b-%y",
           timezone:"browser",
           min: min date value define here,
           max: max date value define here
        }
</code>```

Body:
My points do not appear centered with the grid line of the x-axis as visible in the screenshot below:

The options I am using are as follows:

    var options = {
      grid: {
        show: true,
        aboveData: false,
        color: "#3f3f3f",
        labelMargin: 10,
        axisMargin: 0,
        borderWidth: 0,
        borderColor: null,
        minBorderMargin: 5,
        clickable: true,
        hoverable: true,
        autoHighlight: true,
        mouseActiveRadius: 100
      },
      series: {
        lines: {
          show: true,
          fill: true,
          lineWidth: 2,
          steps: false
        },
        points: {
          show: true,
          radius: 4.5,
          symbol: "circle",
          lineWidth: 3.0
        }
      },
      legend: {
        position: "ne",
        margin: [0, -15],
        noColumns: 0,
        labelBoxBorderColor: null,
        labelFormatter: function(label, series) {
          // just add some space to labes
          return label + '  ';
        },
        width: 40,
        height: 1
      },
      colors: chartColours,
      shadowSize: 0,
      tooltip: true, //activate tooltip
      tooltipOpts: {
        content: "%s: %y.0",
        xDateFormat: "%d/%m",
        shifts: {
          x: -30,
          y: -50
        },
        defaultTheme: false
      },
      yaxis: {
        min: 0,
        tickDecimals:0
      },
      xaxis: {
        mode: "time",
        minTickSize: tickSize,
        timeformat: tformat,
        min: chartMinDate,
        max: chartMaxDate
      }
    };

My data set is a time-series, and the labels values is also coming from the same data set so the dates should line up with the points. However it is offset while no option for this exists. What am I doing wrong?

Body:
I got the solution from this link

points aren't aligned with the x axis on flot chart

And

https://code.google.com/archive/p/flot/issues/608

It seems Flot chart requires the time in UTC format.

For me it worked by just adding the "timezone:"browser"" in "xaxis".

After addition, my "xaxis" looks like below :

 xaxis: {
           mode: "time",
           minTickSize: [1, "day"],
           timeformat: "%d-%b-%y",
           timezone:"browser",
           min: min date value define here,
           max: max date value define here
        }


问:
Removing all line breaks and adding them after certain text
I have text file in which I have to remove all line breaks, and later add new ones after each text </row>. how could I do that using replace tool?

答:
You can also try this in Notepad++

Highlight the lines you want to join (ctrl + a to select all)

Choose Edit -> Line Operations -> Join Lines

ContentLicense: CC BY-SA 4.0


问:
Error about sun/misc/BASE64Encoder on Eclipse
when i run my app in mac, and show up this message

Errors occurred during the build.
Errors running builder 'Android Package Builder' on project 'IMPEXP'.
sun/misc/BASE64Encoder

but this project is work fine in windows 10 computer, and i don't use any about base64Encoder

eclipse Version: Photon Milestone 3 (4.8.0M3)
JRE java se 9.0

edit!

i found something like below

!ENTRY org.eclipse.core.resources 4 2 2017-11-09 11:50:09.047
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.resources".
!STACK 0
java.lang.NoClassDefFoundError: sun/misc/BASE64Encoder
    at com.android.sdklib.internal.build.SignedJarBuilder.<init>(SignedJarBuilder.java:177)
    at com.android.sdklib.build.ApkBuilder.init(ApkBuilder.java:446)
    at com.android.sdklib.build.ApkBuilder.<init>(ApkBuilder.java:422)
    at com.android.sdklib.build.ApkBuilder.<init>(ApkBuilder.java:362)
    at com.android.ide.eclipse.adt.internal.build.BuildHelper.finalPackage(BuildHelper.java:391)
    at com.android.ide.eclipse.adt.internal.build.BuildHelper.finalDebugPackage(BuildHelper.java:359)
    at com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder.build(PostCompilerBuilder.java:632)
    at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:735)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:206)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:330)
    at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:405)
    at org.eclipse.core.internal.resources.Project$1.run(Project.java:566)
    at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2240)
    at org.eclipse.core.internal.resources.Project.internalBuild(Project.java:544)
    at org.eclipse.core.internal.resources.Project.build(Project.java:120)
    at com.android.ide.eclipse.adt.internal.project.ProjectHelper.doFullIncrementalDebugBuild(ProjectHelper.java:1143)
    at com.android.ide.eclipse.adt.internal.launch.LaunchConfigDelegate.launch(LaunchConfigDelegate.java:155)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:885)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:739)
    at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1039)
    at org.eclipse.debug.internal.ui.DebugUIPlugin$8.run(DebugUIPlugin.java:1256)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:56)
Caused by: java.lang.ClassNotFoundException: sun.misc.BASE64Encoder cannot be found by com.android.ide.eclipse.base_23.0.7.2120684
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:484)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:395)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:150)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 23 more
```

答:
The Android code you are using is trying to use the sun.misc.BASE64Encoder class.

This deprecated class has been removed from Java 9 so this is not going to work.

You will need to switch back to Java 8 or find an update to the Android code (if there is one).


问:
"Predefined type 'System.*' is not defined or imported" Error, visual studio code, omnisharp
I'm having an issue with the mentioned error in several .net core applications. I'm using vs code version 1.18.0 but the error started to appear already in the previous version.

The error appears in every .cs file for every datatype like string, int, void etc. and also for class imports.

All the projects still compile and run properly. Also on another workstation I'm not having the issue in the same projects, so it seems to be a local omnisharp/ vs code or windows? problem.

Has anyone had something like this and managed to fix it or any suggestions on what i could try?

I've reinstalled vs code and omnisharp already, but I'm still having the problem.

example Error:
Predefined type 'System.Object' is not defined or imported [GG]

答:
I found a fix ( or workaround) for my problem:

short version: I changed the omnisharp msbuild instance by uninstalling Visual Studio 2017 Pro.

long version: A few months ago I installed VS 2017 Pro to check out the features, used it for 2 weeks in trial mode and forgot about it for several months.

Around one week ago I opened it (by accident :D) and got a notification, that my trial period expired, also VS locked itself.
It didn't bother me , because I wasn't using it. In @VahidN 's Link I found out that omnisharp is using "the most native" msbuild instance that is installed, which in my case was the one of the locked VS 2017 Pro. 1+1 I unsinstalled VS and I'm good.

I'll reinstall VS 2017 ( Comunity) and post a comment if it still works fine.

EDIT:: I reinstalled VS 2017, everything works fine, so the actual solution is updating VS 2017, which i couldnt do besause it was locked prieviously.


问:
jQuery show hide parent item on click by class
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

```<code><div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <a href="#" class="list-avatar"><img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40"></a>
            <a href="#"><i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i></a>
        </div>
        <div class="item-title"><a href="#"><?php echo $questions[ $i ] ?></a>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info"><a href="#">commented</a> 1 hour ago in <a href="#">Plugins</a> by
            <a href="#">gurjyot</a>
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item -->

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});
</code>```

答:
Try This

```<code>$('.list-content .meta-info-btn').click(function () {
    $(this).parents('.list-content').next('.metas').slideToggle();
});
</code>```

$('.list-content .meta-info-btn').click(function () {

    $(this).parents('.list-content').next('.metas').slideToggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40">
            <i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i>
        </div>
        <div class="item-title"><?php echo $questions[ $i ] ?>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info">commented 1 hour ago in Plugins by
            gurjyot
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
    <div class="list-content">
        <div class="list-updates">
            <img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40">
            <i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i>
        </div>
        <div class="item-title"><?php echo $questions[ $i ] ?>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down 1</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info">commented 1 hour ago in Plugins by
            gurjyot
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item --></code>```

Body:
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

            <img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40">
            <?php echo get_icon( $update[ $i ] ) ?>

<?php echo $questions[ $i ] ?>

<?php echo $ans[ $i ] ?>

            keyboard_arrow_down

commented 1 hour ago in Plugins by
            gurjyot

            arrow_upward +1245
            remove_red_eye 50.2k

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});

Body:
Try This

$('.list-content .meta-info-btn').click(function () {
    $(this).parents('.list-content').next('.metas').slideToggle();
});

$('.list-content .meta-info-btn').click(function () {

    $(this).parents('.list-content').next('.metas').slideToggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <a href="#" class="list-avatar"><img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40"></a>
            <a href="#"><i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i></a>
        </div>
        <div class="item-title"><a href="#"><?php echo $questions[ $i ] ?></a>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info"><a href="#">commented</a> 1 hour ago in <a href="#">Plugins</a> by
            <a href="#">gurjyot</a>
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
    <div class="list-content">
        <div class="list-updates">
            <a href="#" class="list-avatar"><img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40"></a>
            <a href="#"><i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i></a>
        </div>
        <div class="item-title"><a href="#"><?php echo $questions[ $i ] ?></a>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down 1</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info"><a href="#">commented</a> 1 hour ago in <a href="#">Plugins</a> by
            <a href="#">gurjyot</a>
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item -->


问:
Making a Zurb Foundation theme for Mezzanine (django-compressor + SASS integration)
I'm building a bilingual site, which has both RTL and LRT content. Mezzanine comes with a twitter-bootstrap theme, which doesn't support RTL as well as zurb-foundation does. So I'm trying to create a new Mezzanine theme that would use foundation for sites.

I'm having trouble structuring my project in a way that django-compressor would understand, with minimal 3rd party dependencies.

The structure that I'd like to emulate is the one in mezzanine-themes. However, it is not setup to use SCSS. I've also installed django-compressor-toolkit to deal with SCSS.

The problem now is that I don't know how to structure the static files in the theme app to get compressor to find them.

My hunch is that I have to make compressor-toolkit find the foundation-sites file in node_modules, but I can't figure how to do that out from reading the docs.

I could put all of the foundation files in the same static folder, but then I lose the nice package management (along with other drawbacks).

Any recommendations?

Many thanks in advance.

Below is the error that compressor gives when it reaches the {% compress css %} template tag.

```<code>{
  "status": 1,
  "file": "/Users/majdal/Projects/dar/nimer/static/scss/_settings.scss",
  "line": 63,
  "column": 1,
  "message": "File to import not found or unreadable: util/util.\nParent style sheet: /Users/majdal/Projects/dar/nimer/static/scss/_settings.scss",
  "formatted": "Error: File to import not found or unreadable: util/util.\n       Parent style sheet: /Users/majdal/Projects/dar/nimer/static/scss/_settings.scss\n        on line 63 of nimer/static/scss/_settings.scss\n>> @import 'util/util';\n   ^\n"
}
</code>```

答:
Found it! I had to use --include-path for the node-sass module.

```<code>COMPRESS_PRECOMPILERS = (
    ('text/x-scss', 'node-sass --scss  --include-path ./node_modules/foundation-sites/scss/ --include-path ./node_modules/motion-ui {infile} {outfile}'),
)
</code>```

Body:
I'm building a bilingual site, which has both RTL and LRT content. Mezzanine comes with a twitter-bootstrap theme, which doesn't support RTL as well as zurb-foundation does. So I'm trying to create a new Mezzanine theme that would use foundation for sites.

I'm having trouble structuring my project in a way that django-compressor would understand, with minimal 3rd party dependencies.

The structure that I'd like to emulate is the one in mezzanine-themes. However, it is not setup to use SCSS. I've also installed django-compressor-toolkit to deal with SCSS.

The problem now is that I don't know how to structure the static files in the theme app to get compressor to find them.

My hunch is that I have to make compressor-toolkit find the foundation-sites file in node_modules, but I can't figure how to do that out from reading the docs.

I could put all of the foundation files in the same static folder, but then I lose the nice package management (along with other drawbacks).

Any recommendations?

Many thanks in advance.

Below is the error that compressor gives when it reaches the {% compress css %} template tag.

{
  "status": 1,
  "file": "/Users/majdal/Projects/dar/nimer/static/scss/_settings.scss",
  "line": 63,
  "column": 1,
  "message": "File to import not found or unreadable: util/util.\nParent style sheet: /Users/majdal/Projects/dar/nimer/static/scss/_settings.scss",
  "formatted": "Error: File to import not found or unreadable: util/util.\n       Parent style sheet: /Users/majdal/Projects/dar/nimer/static/scss/_settings.scss\n        on line 63 of nimer/static/scss/_settings.scss\n>> @import 'util/util';\n   ^\n"
}

Body:
Found it! I had to use --include-path for the node-sass module.

COMPRESS_PRECOMPILERS = (
    ('text/x-scss', 'node-sass --scss  --include-path ./node_modules/foundation-sites/scss/ --include-path ./node_modules/motion-ui {infile} {outfile}'),
)


问:
List to Dictionary - Python
I have the following list:

```<code>[{'ext': '193', 'value': 'Name1'},
 {'ext': '194', 'value': 'Name 2'},
 {'ext': '192', 'value': 'Name3'},
 {'ext': '195', 'value': 'Name4'}]
</code>```

How to create a dictionary of this to look like the following:

```<code>{'193': 'Name1', '194': 'Name 2'}
</code>```

etc.

答:
Since list has collection of tuple, You can achieve the same in below way:</p>

```<code>mappings
[{'ext': '193', 'value': 'Name1'}, {'ext': '194', 'value': 'Name 2'},
{'ext': '192', 'value': 'Name3'}, {'ext': '195', 'value': 'Name4'}]
dict={}
for i in mappings:
    dict[i["ext"]] = i["value"]

dict
{'195': 'Name4', '194': 'Name 2', '193': 'Name1', '192': 'Name3'}
</code>```

Title: List to Dictionary - Python

Body:
I have the following list:

[{'ext': '193', 'value': 'Name1'},
 {'ext': '194', 'value': 'Name 2'},
 {'ext': '192', 'value': 'Name3'},
 {'ext': '195', 'value': 'Name4'}]

How to create a dictionary of this to look like the following:

{'193': 'Name1', '194': 'Name 2'}

etc.

Body:
Since list has collection of tuple, You can achieve the same in below way:

mappings
[{'ext': '193', 'value': 'Name1'}, {'ext': '194', 'value': 'Name 2'},
{'ext': '192', 'value': 'Name3'}, {'ext': '195', 'value': 'Name4'}]
dict={}
for i in mappings:
    dict[i["ext"]] = i["value"]

dict
{'195': 'Name4', '194': 'Name 2', '193': 'Name1', '192': 'Name3'}


问:
Getting Test Case Run time error
Im working on this question(not Homework)
Given a list of unsorted integers,A = {a1, a2, ...,an) can you find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.

This is what i came up with:

```<code>num = int(input())
array = [int(x) for x in input().split()]
diff = []
for i in range(len(array)):
    for j in array:
        diff.append(array[i]- j)

total = []
for i in diff:
    if i > 0:
        total.append(i)

grail = min(total)
holy = []
for i in range(len(array)):
     for j in array:
        if ((array[i] - j) == grail):
            holy.append(array[i])
            holy.append(j)

final = sorted(holy)
for item in final:
    print(item, end = ' ')
</code>```

This runs for few cases but gets runtime error on large inputs,any suggestion i might try?

Ex:

```<code>Input = [-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470 ]

Output = -520 -470 -20 30
</code>```

Explanation = (-470) - (-520) = 30 - (-20) = 50, which is the smallest difference.

Thanks in advance

答:
I did not bother to check your code for correctness because the implementation has complexity of O(n^2)

```<code>for i in range(len(array)):
 for j in array:
    if ((array[i] - j) == grail):
        holy.append(array[i])
        holy.append(j)
</code>```

The required answer needs to have preferable complexity of O(log n). For achieving that you need to sort the list upfront.

```<code>from unittest import TestCase
import unittest
from sys import maxsize
from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def solution(n):
    n = sorted(n)
    pairs = []
    diff = maxsize
    for l, u in pairwise(n):
        if u - l <= diff:
            diff = u - l
            pairs.append((diff, (l,u)))
    pairs = sorted(pairs)
    least = pairs[0][0]
    return list(map(lambda x: x[1], filter(lambda x: x[0] == least, pairs)))

class TestLeastDiffrence(TestCase):
    def testSimple(self):
        n = [-20, -3916237, -357920, -3620601, 7374819, -7330761, 30, 6246457, -6461594, 266854, -520, -470]
        self.assertEqual(solution(n),[(-520, -470), (-20, 30)])

if __name__ == '__main__':
    unittest.main()
</code>```

Title: Getting Test Case Run time error

Body:
Im working on this question(not Homework)
Given a list of unsorted integers,A = {a1, a2, ...,an) can you find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.

This is what i came up with:

num = int(input())
array = [int(x) for x in input().split()]
diff = []
for i in range(len(array)):
    for j in array:
        diff.append(array[i]- j)

total = []
for i in diff:
    if i > 0:
        total.append(i)

grail = min(total)
holy = []
for i in range(len(array)):
     for j in array:
        if ((array[i] - j) == grail):
            holy.append(array[i])
            holy.append(j)

final = sorted(holy)
for item in final:
    print(item, end = ' ')

This runs for few cases but gets runtime error on large inputs,any suggestion i might try?

Ex:

Input = [-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470 ]

Output = -520 -470 -20 30

Explanation = (-470) - (-520) = 30 - (-20) = 50, which is the smallest difference.

Thanks in advance

Body:
I did not bother to check your code for correctness because the implementation has complexity of O(n^2)

for i in range(len(array)):
 for j in array:
    if ((array[i] - j) == grail):
        holy.append(array[i])
        holy.append(j)

The required answer needs to have preferable complexity of O(log n). For achieving that you need to sort the list upfront.

from unittest import TestCase
import unittest
from sys import maxsize
from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def solution(n):
    n = sorted(n)
    pairs = []
    diff = maxsize
    for l, u in pairwise(n):
        if u - l <= diff:
            diff = u - l
            pairs.append((diff, (l,u)))
    pairs = sorted(pairs)
    least = pairs[0][0]
    return list(map(lambda x: x[1], filter(lambda x: x[0] == least, pairs)))

class TestLeastDiffrence(TestCase):
    def testSimple(self):
        n = [-20, -3916237, -357920, -3620601, 7374819, -7330761, 30, 6246457, -6461594, 266854, -520, -470]
        self.assertEqual(solution(n),[(-520, -470), (-20, 30)])

if __name__ == '__main__':
    unittest.main()


问:
Should I call a single sql statement to retrieve data for a service or different distinct calls
I have a requirement where I need to return some data from a web service (in .net). The response of the service would be a class having different attributes. Some of the attributes are complex and need data to be fetched for such types need separate call.
Ex:

```<code>Class getServiceData

{

    public int SimpleProperty1 {get;set;}

    public int SimpleProperty2 {get;set;}

    public IEnumerable<ComplexProperty> {get;set;}
  ...

}
</code>```

For getting the data for such class, I need to call the Oracle database. My question is whether I should bring all the data for the service in a single sql statement (please note the structure involves some hierarchy) or call separate statements for different attributes of the class.

thanks in advance

答:
Hierarchical queries done by the client involve probably many roundtrips between the application-code and the server. (at least if you do not use PSQL)

Since oracle is perfectly capable to handle hierarchical queries in one statement, I recommend to use that feature. It is much more performant, imO does not put more load onto the server than multiple regular queries and produces the same results.

The downsides I see, are

if you use some mapping library you might need to use native statements and therefore drop the support of the framework.

the query might be complex and not easily understandable for people who later have to maintain your code.

The code is not easily portable to other databases, if you decide to switch. Since the oracle hierarchical (connect by prior) feature came quite early on the market,  it has not so much in common with recursive CTE-queries, other dbms support.

Body:
I have a requirement where I need to return some data from a web service (in .net). The response of the service would be a class having different attributes. Some of the attributes are complex and need data to be fetched for such types need separate call.
Ex:

Class getServiceData

{

    public int SimpleProperty1 {get;set;}

    public int SimpleProperty2 {get;set;}

    public IEnumerable<ComplexProperty> {get;set;}
  ...

}

For getting the data for such class, I need to call the Oracle database. My question is whether I should bring all the data for the service in a single sql statement (please note the structure involves some hierarchy) or call separate statements for different attributes of the class.

thanks in advance


问:
Sorting Java case statements
I came through here a little while ago trying to find out if there was in fact a way to auto sort case statements.. Eclipse doesn't have the answer to do this automatically. So I wanted to find out a way to do this. Sadly this doesn't appear to be something addressed anywhere. Is this something everyone will need to do... probably not.</p>

答:
Here is my solution:

Main call:

```<code>package com.debug;

import java.io.IOException;

public class DebugMain {

    public static void main(String[] args) {
        fixCases();
    }

    public static void fixCases() {
        String filePath = System.getProperty("user.home").replace("\\", "/") + "/Documents/";
        String fileName = "case.txt";
        System.out.println("Organizing cases: " + filePath + fileName);

        CaseHandler ch = new CaseHandler(filePath + fileName, CaseType.Integer);
        try {
            ch.readFile();
            ch.sortCases();
            ch.writeCases(filePath + "casetest.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Organizing complete.");
    }
}
</code>```

CaseHandler:

```<code>package com.debug;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * This handler allows you to read from a text file a list of case statements, sort the case statements<br />
 * in natural order, and write to a file.
 *
 * @author Vincent
 */
public class CaseHandler {

    /**
     * This denotes the use of numerical or text based case statements.
     */
    public enum CaseType {
        String, Integer;
    }

    private boolean autoSort = false;
    private ArrayList<Case> cases = new ArrayList<Case>();
    private CaseType caseType;
    private File file;

    /**
     * This construcs a basic <code>CaseHandler</code> in which a file must be provided
     * within the {@link #readFile(String)} method.
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     *
     * @param caseType The type of case this instance should use.
     * @see {@link CaseType}, {@link CaseHandler}
     */
    public CaseHandler(CaseType caseType) {
        this.caseType = caseType;
    }

    /**
     * This construcs a <code>CaseHandler</code> with a file provided.<br />
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @param caseType The type of case this instance should use.
     * @see {@link CaseType}, {@link CaseHandler}
     */
    public CaseHandler(String fileName, CaseType caseType) {
        this.caseType = caseType;
        this.file = new File(fileName);
    }

    /**
     * This construcs a <code>CaseHandler</code> with a file provided.<br />
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @param caseType The type of case this instance should use.
     * @param autoSort Enables auto sorting in the {@link #readFile()}
     */
    public CaseHandler(String fileName, CaseType caseType, boolean autoSort) {
        this.caseType = caseType;
        this.file = new File(fileName);
        this.autoSort = autoSort;
    }

    /**
     * Reads the file where the case statements are stored line by line.<br />
     * When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
     * If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
     * When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
     * This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
     * If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
     *
     * @throws IOException
     * @see {@link ArrayList}, {@link FileReader}, {@link BufferedReader}, {@link Case}
     */
    public void readFile() throws IOException {
        if (this.file != null && this.file.exists()) {
            FileReader fr = null;
            BufferedReader br = null;
            try {
                fr = new FileReader(this.file);
                br = new BufferedReader(fr);
                String line = "";
                ArrayList<String> lines = null;
                while ((line = br.readLine()) != null) {
                    if (line.contains("case")) {
                        if (lines != null && lines.get(lines.size() - 1).contains("break")) {
                            lines = new ArrayList<String>();
                        } else {
                            lines = new ArrayList<String>();
                        }
                    }
                    lines.add(line);
                    if (line.contains("break")) {
                        String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
                        Case aCase = null;
                        if (caseType == CaseType.Integer) {
                            aCase = new Case(Integer.parseInt(caseName), lines);
                        } else if (caseType == CaseType.String) {
                            aCase = new Case(caseName, lines);
                        }
                        cases.add(aCase);
                    }
                }
                if (this.autoSort) {
                    this.sortCases();
                }
            } finally {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            }
        } else {
            System.out.println("File " + this.file.getName() + " does not exist!");
        }
    }

    /**
     * Reads the file where the case statements are stored line by line.<br />
     * When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
     * If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
     * When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
     * This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
     * If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @throws IOException
     * @see {@link ArrayList}, {@link FileReader}, {@link BufferedReader}, {@link Case}
     */
    public void readFile(String fileName) throws IOException {
        this.file = new File(fileName);
        if (this.file != null && this.file.exists()) {
            FileReader fr = null;
            BufferedReader br = null;
            try {
                fr = new FileReader(this.file);
                br = new BufferedReader(fr);
                String line = "";
                ArrayList<String> lines = null;
                while ((line = br.readLine()) != null) {
                    if (line.contains("case")) {
                        if (lines != null && lines.get(lines.size() - 1).contains("break")) {
                            lines = new ArrayList<String>();
                        } else {
                            lines = new ArrayList<String>();
                        }
                    }
                    lines.add(line);
                    if (line.contains("break")) {
                        String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
                        Case aCase = null;
                        if (caseType == CaseType.Integer) {
                            aCase = new Case(Integer.parseInt(caseName), lines);
                        } else if (caseType == CaseType.String) {
                            aCase = new Case(caseName, lines);
                        }
                        cases.add(aCase);
                    }
                }
                if (this.autoSort) {
                    this.sortCases();
                }
            } finally {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            }
        } else {
            System.out.println("File " + this.file.getName() + " does not exist!");
        }
    }

    /**
     * Sorts the {@link ArrayList} in alphabetical or numerical order.<br />
     * <b>Note:</b> This will <b>NOT</b> sort clusters of case statements.
     * @see {@link Collections#sort(java.util.List)}
     */
    public void sortCases() {
        if (cases.size() > 0) {
            Collections.sort(cases, Comparator.naturalOrder());
        }
    }

    /**
     * Overwrites the file provided to the <code>CaseHandler</code> with the cases list.
     *
     * @throws IOException
     * @see {@link ArrayList}, {@link FileWriter}, {@link BufferedWriter}, {@link Case}
     */
    public void writeCases() throws IOException {
        if (this.file.exists()) {
            FileWriter fw = null;
            BufferedWriter bw = null;
            try {
                fw = new FileWriter(this.file);
                bw = new BufferedWriter(fw);
                for (Case aCase : cases) {
                    for (String line : aCase.getLines()) {
                        bw.write(line);
                        bw.newLine();
                    }
                }
            } finally {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }

    /**
     * Overwrites the file provided to with the cases list.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @throws IOException
     * @see {@link ArrayList}, {@link FileWriter}, {@link BufferedWriter}, {@link Case}
     */
    public void writeCases(String fileName) throws IOException {
        File outFile = new File(fileName);
        if (!outFile.exists()) {
            outFile.createNewFile();
        }
        if (outFile.exists()) {
            FileWriter fw = null;
            BufferedWriter bw = null;
            try {
                fw = new FileWriter(outFile);
                bw = new BufferedWriter(fw);
                for (Case aCase : cases) {
                    for (String line : aCase.getLines()) {
                        bw.write(line);
                        bw.newLine();
                    }
                }
            } finally {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }

    /**
     * Changes the case type.
     *
     * @param caseType The new type of case this instance should use.
     * @see {@link CaseType}
     */
    public void setCaseType(CaseType caseType) {
        this.caseType = caseType;
    }
}
</code>```

Case:

```<code>package com.debug;

import java.util.ArrayList;

/**
 * This is the individual case statement starting at <code>case (Integer or String):</code> <br />
 * The last line stored in the instance will be the <code>break;</code> statement.
 *
 * @author Vincent
 *
 */
public class Case implements Comparable<Case> {

    private int nameInt;
    private String nameStr = null;
    private ArrayList<String> lines;

    /**
     * Constructs a new <code>Case</code> using integer values as the name.
     *
     * @param nameInt The integer value name
     * @param lines The lines within this case statement
     * @see {@link ArrayList}
     */
    public Case(int nameInt, ArrayList<String> lines) {
        this.nameInt = nameInt;
        this.lines = lines;
    }

    /**
     * Constructs a new <code>Case</code> using string values as the name.
     *
     * @param nameStr The string value name
     * @param lines The lines within this case statement
     * @see {@link ArrayList}
     */
    public Case(String nameStr, ArrayList<String> lines) {
        this.nameStr = nameStr;
        this.lines = lines;
    }

    @Override
    public int compareTo(Case aCase) {
        if (this.nameStr != null) {
            return this.nameStr.compareTo(aCase.getNameStr());
        } else {
            if (this.nameInt < aCase.getNameInt()) {
                return -1;
            } else if (this.nameInt > aCase.getNameInt()) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    /**
     * Returns the lines stored in this <code>Case</code> instance.
     *
     * @return {@link ArrayList}
     */
    public ArrayList<String> getLines() {
        return this.lines;
    }

    /**
     * Returns the integer name of this <code>Case</code> instance.
     *
     * @return {@link Integer}
     */
    public int getNameInt() {
        return this.nameInt;
    }

    /**
     * Returns the string name of this <code>Case</code> instance.
     *
     * @return {@link String}
     */
    public String getNameStr() {
        return this.nameStr;
    }
}
</code>```

Example input:

```<code>case 338:
    // Code
    break;
case 852:
    // Code
    break;
case 2:
    // Code
    break;
case 696:
    // Code
    break;
</code>```

Example output:

```<code>case 2:
    // Code
    break;
case 338:
    // Code
    break;
case 696:
    // Code
    break;
case 852:
    // Code
    break;
</code>```

Hope this potentially helps someone out. I needed this cause I was looking at a long list of cases (1000 of them to be exact) that were sorted in no particular order or with any reason to be sorted that way. So I wanted to see them in natural order.

Title: Sorting Java case statements

Body:
Here is my solution:

Main call:

package com.debug;

import java.io.IOException;

public class DebugMain {

    public static void main(String[] args) {
        fixCases();
    }

    public static void fixCases() {
        String filePath = System.getProperty("user.home").replace("\\", "/") + "/Documents/";
        String fileName = "case.txt";
        System.out.println("Organizing cases: " + filePath + fileName);

        CaseHandler ch = new CaseHandler(filePath + fileName, CaseType.Integer);
        try {
            ch.readFile();
            ch.sortCases();
            ch.writeCases(filePath + "casetest.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Organizing complete.");
    }
}

CaseHandler:

package com.debug;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * This handler allows you to read from a text file a list of case statements, sort the case statements<br />
 * in natural order, and write to a file.
 *
 * @author Vincent
 */
public class CaseHandler {

    /**
     * This denotes the use of numerical or text based case statements.
     */
    public enum CaseType {
        String, Integer;
    }

    private boolean autoSort = false;
    private ArrayList<Case> cases = new ArrayList<Case>();
    private CaseType caseType;
    private File file;

    /**
     * This construcs a basic <code>CaseHandler</code> in which a file must be provided
     * within the {@link #readFile(String)} method.
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     *
     * @param caseType The type of case this instance should use.
     * @see {@link CaseType}, {@link CaseHandler}
     */
    public CaseHandler(CaseType caseType) {
        this.caseType = caseType;
    }

    /**
     * This construcs a <code>CaseHandler</code> with a file provided.<br />
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @param caseType The type of case this instance should use.
     * @see {@link CaseType}, {@link CaseHandler}
     */
    public CaseHandler(String fileName, CaseType caseType) {
        this.caseType = caseType;
        this.file = new File(fileName);
    }

    /**
     * This construcs a <code>CaseHandler</code> with a file provided.<br />
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @param caseType The type of case this instance should use.
     * @param autoSort Enables auto sorting in the {@link #readFile()}
     */
    public CaseHandler(String fileName, CaseType caseType, boolean autoSort) {
        this.caseType = caseType;
        this.file = new File(fileName);
        this.autoSort = autoSort;
    }

    /**
     * Reads the file where the case statements are stored line by line.<br />
     * When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
     * If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
     * When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
     * This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
     * If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
     *
     * @throws IOException
     * @see {@link ArrayList}, {@link FileReader}, {@link BufferedReader}, {@link Case}
     */
    public void readFile() throws IOException {
        if (this.file != null && this.file.exists()) {
            FileReader fr = null;
            BufferedReader br = null;
            try {
                fr = new FileReader(this.file);
                br = new BufferedReader(fr);
                String line = "";
                ArrayList<String> lines = null;
                while ((line = br.readLine()) != null) {
                    if (line.contains("case")) {
                        if (lines != null && lines.get(lines.size() - 1).contains("break")) {
                            lines = new ArrayList<String>();
                        } else {
                            lines = new ArrayList<String>();
                        }
                    }
                    lines.add(line);
                    if (line.contains("break")) {
                        String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
                        Case aCase = null;
                        if (caseType == CaseType.Integer) {
                            aCase = new Case(Integer.parseInt(caseName), lines);
                        } else if (caseType == CaseType.String) {
                            aCase = new Case(caseName, lines);
                        }
                        cases.add(aCase);
                    }
                }
                if (this.autoSort) {
                    this.sortCases();
                }
            } finally {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            }
        } else {
            System.out.println("File " + this.file.getName() + " does not exist!");
        }
    }

    /**
     * Reads the file where the case statements are stored line by line.<br />
     * When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
     * If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
     * When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
     * This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
     * If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @throws IOException
     * @see {@link ArrayList}, {@link FileReader}, {@link BufferedReader}, {@link Case}
     */
    public void readFile(String fileName) throws IOException {
        this.file = new File(fileName);
        if (this.file != null && this.file.exists()) {
            FileReader fr = null;
            BufferedReader br = null;
            try {
                fr = new FileReader(this.file);
                br = new BufferedReader(fr);
                String line = "";
                ArrayList<String> lines = null;
                while ((line = br.readLine()) != null) {
                    if (line.contains("case")) {
                        if (lines != null && lines.get(lines.size() - 1).contains("break")) {
                            lines = new ArrayList<String>();
                        } else {
                            lines = new ArrayList<String>();
                        }
                    }
                    lines.add(line);
                    if (line.contains("break")) {
                        String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
                        Case aCase = null;
                        if (caseType == CaseType.Integer) {
                            aCase = new Case(Integer.parseInt(caseName), lines);
                        } else if (caseType == CaseType.String) {
                            aCase = new Case(caseName, lines);
                        }
                        cases.add(aCase);
                    }
                }
                if (this.autoSort) {
                    this.sortCases();
                }
            } finally {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            }
        } else {
            System.out.println("File " + this.file.getName() + " does not exist!");
        }
    }

    /**
     * Sorts the {@link ArrayList} in alphabetical or numerical order.<br />
     * <b>Note:</b> This will <b>NOT</b> sort clusters of case statements.
     * @see {@link Collections#sort(java.util.List)}
     */
    public void sortCases() {
        if (cases.size() > 0) {
            Collections.sort(cases, Comparator.naturalOrder());
        }
    }

    /**
     * Overwrites the file provided to the <code>CaseHandler</code> with the cases list.
     *
     * @throws IOException
     * @see {@link ArrayList}, {@link FileWriter}, {@link BufferedWriter}, {@link Case}
     */
    public void writeCases() throws IOException {
        if (this.file.exists()) {
            FileWriter fw = null;
            BufferedWriter bw = null;
            try {
                fw = new FileWriter(this.file);
                bw = new BufferedWriter(fw);
                for (Case aCase : cases) {
                    for (String line : aCase.getLines()) {
                        bw.write(line);
                        bw.newLine();
                    }
                }
            } finally {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }

    /**
     * Overwrites the file provided to with the cases list.
     *
     * @param fileName The full file path and name to be read from and/or written to.
     * @throws IOException
     * @see {@link ArrayList}, {@link FileWriter}, {@link BufferedWriter}, {@link Case}
     */
    public void writeCases(String fileName) throws IOException {
        File outFile = new File(fileName);
        if (!outFile.exists()) {
            outFile.createNewFile();
        }
        if (outFile.exists()) {
            FileWriter fw = null;
            BufferedWriter bw = null;
            try {
                fw = new FileWriter(outFile);
                bw = new BufferedWriter(fw);
                for (Case aCase : cases) {
                    for (String line : aCase.getLines()) {
                        bw.write(line);
                        bw.newLine();
                    }
                }
            } finally {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }

    /**
     * Changes the case type.
     *
     * @param caseType The new type of case this instance should use.
     * @see {@link CaseType}
     */
    public void setCaseType(CaseType caseType) {
        this.caseType = caseType;
    }
}

Case:

package com.debug;

import java.util.ArrayList;

/**
 * This is the individual case statement starting at <code>case (Integer or String):</code> <br />
 * The last line stored in the instance will be the <code>break;</code> statement.
 *
 * @author Vincent
 *
 */
public class Case implements Comparable<Case> {

    private int nameInt;
    private String nameStr = null;
    private ArrayList<String> lines;

    /**
     * Constructs a new <code>Case</code> using integer values as the name.
     *
     * @param nameInt The integer value name
     * @param lines The lines within this case statement
     * @see {@link ArrayList}
     */
    public Case(int nameInt, ArrayList<String> lines) {
        this.nameInt = nameInt;
        this.lines = lines;
    }

    /**
     * Constructs a new <code>Case</code> using string values as the name.
     *
     * @param nameStr The string value name
     * @param lines The lines within this case statement
     * @see {@link ArrayList}
     */
    public Case(String nameStr, ArrayList<String> lines) {
        this.nameStr = nameStr;
        this.lines = lines;
    }

    @Override
    public int compareTo(Case aCase) {
        if (this.nameStr != null) {
            return this.nameStr.compareTo(aCase.getNameStr());
        } else {
            if (this.nameInt < aCase.getNameInt()) {
                return -1;
            } else if (this.nameInt > aCase.getNameInt()) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    /**
     * Returns the lines stored in this <code>Case</code> instance.
     *
     * @return {@link ArrayList}
     */
    public ArrayList<String> getLines() {
        return this.lines;
    }

    /**
     * Returns the integer name of this <code>Case</code> instance.
     *
     * @return {@link Integer}
     */
    public int getNameInt() {
        return this.nameInt;
    }

    /**
     * Returns the string name of this <code>Case</code> instance.
     *
     * @return {@link String}
     */
    public String getNameStr() {
        return this.nameStr;
    }
}

Example input:

case 338:
    // Code
    break;
case 852:
    // Code
    break;
case 2:
    // Code
    break;
case 696:
    // Code
    break;

Example output:

case 2:
    // Code
    break;
case 338:
    // Code
    break;
case 696:
    // Code
    break;
case 852:
    // Code
    break;

Hope this potentially helps someone out. I needed this cause I was looking at a long list of cases (1000 of them to be exact) that were sorted in no particular order or with any reason to be sorted that way. So I wanted to see them in natural order.


问:
How to display the answer direction for a questionarie based on Direction
We are creating a quiz using angularjs.
We want to show the radiobutton list direction vertically or horizontally.
If it is horizontally we want do show in 2 columns.
Help me to show horizontally or vertically

Have provided the code in

  var app = angular.module("quizApp", []);

        app.controller("quizCtrl", function ($scope) {
            $scope.questions = [
                {
                    question: "Which is the largest country in the world by population?",
                    options: ["India", "USA", "China", "Russia"],
                    answer: 2,
                    direction:0
                },
                {
                    question: "When did the second world war end?",
                    options: ["1945", "1939", "1944", "1942"],
                    answer: 0,
                    direction: 1
                }
            ];
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

<body>
    <div ng-app="quizApp" ng-controller="quizCtrl">
        <div data-ng-repeat="quiz in questions track by $index" data-ng-init="quizIndex = $index" layout="column">
            <div layout="row">
                <span data-ng-bind="quiz.question"></span>
            </div>
            <div layout="row" data-ng-repeat="option in quiz.options track by $index" data-ng-init="optionIndex = $index">
                <input type="radio" data-ng-value="{{option}}" style="margin-right: 5px;"
                                name="Options_{{quizIndex}}_Response_{{optionIndex}}" />
                 <span id="spnAnswer_{{quizIndex}}_{{optionIndex}}" data-ng-bind="option" />
            </div>
        </div>
    </div>
</body></code>```

答:
You can use ng-class in the div of your repeater to show horizontal or vertical way.

Your HTML template might be look like following:

```<code><div ng-class="'class-for-horizontal-display': !showVertical, 'class-for-vertical-display': showVertical" data-ng-repeat="quiz in questions track by $index" data-ng-init="quizIndex = $index" layout="column">

    </div>
</code>```

and in your controller you should have a $scope variable "showVertical" like:

```<code>$scope.showVertical = false
</code>```

Body:
We are creating a quiz using angularjs.
We want to show the radiobutton list direction vertically or horizontally.
If it is horizontally we want do show in 2 columns.
Help me to show horizontally or vertically

Have provided the code in

  var app = angular.module("quizApp", []);

        app.controller("quizCtrl", function ($scope) {
            $scope.questions = [
                {
                    question: "Which is the largest country in the world by population?",
                    options: ["India", "USA", "China", "Russia"],
                    answer: 2,
                    direction:0
                },
                {
                    question: "When did the second world war end?",
                    options: ["1945", "1939", "1944", "1942"],
                    answer: 0,
                    direction: 1
                }
            ];
        });

                <input type="radio" data-ng-value="{{option}}" style="margin-right: 5px;"
                                name="Options_{{quizIndex}}_Response_{{optionIndex}}" />

Body:
You can use ng-class in the div of your repeater to show horizontal or vertical way.

Your HTML template might be look like following:

<div ng-class="'class-for-horizontal-display': !showVertical, 'class-for-vertical-display': showVertical" data-ng-repeat="quiz in questions track by $index" data-ng-init="quizIndex = $index" layout="column">

    </div>

and in your controller you should have a $scope variable "showVertical" like:

$scope.showVertical = false


问:
Aligning text centrally in sap.m.Button
I am trying to align the text inside sap.m.Button. I used this -
"textAlign : sap.ui.core.TextAlign.Center," property, I also tried it through css by setting "align-content" property. But couldn't do it.

答:
put a class in the button and write custom css for the class.

use text-align:center in css.

Title: Aligning text centrally in sap.m.Button


问:
How to make an input have more than one event?
I have a button and a select in my form. The button has onclick event while the select has onchange event. How to make the select has both onclick and onchange event?

This is the script:

```<code>$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});
</code>```

When the select is changed, it should do alert('Event 1'); alert('Event 2');. I do not want to rewrite the onclick code in onchange

答:
Write your events as separate functions :</p>

```<code>$('#i_btn').on('click', event1);
$('#i_sel')
     .on('change', event1)
     .on('change', event2);

function event1(){
     alert('Event 1');
}

function event2(){
     alert('Event 2');
}
</code>```

Body:
I have a button and a select in my form. The button has onclick event while the select has onchange event. How to make the select has both onclick and onchange event?

This is the script:

$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});

When the select is changed, it should do alert('Event 1'); alert('Event 2');. I do not want to rewrite the onclick code in onchange

Body:
Write your events as separate functions :

$('#i_btn').on('click', event1);
$('#i_sel')
     .on('change', event1)
     .on('change', event2);

function event1(){
     alert('Event 1');
}

function event2(){
     alert('Event 2');
}


问:
jQuery doesn't removing class before .each function
I got small problem with my script.

The script looks like it works, but each time it adds the selected class. It resets it before the onclick, but the class does not remove it. What could be a problem?

Only one element of the .payment class from the collection should have a .selected class

$(".payment").each(function() {
    $(".payment").removeClass("selected");
    $(this).on("click", function() {
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true);
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
background: #eaeaea;
}</code>```

 <input type="radio" /> example

 <input type="radio" /> of my

 <input type="radio" /> problem

```

答:
You were removing the selected class only on the beginning. I assume you want it to be removed every time a checkbox is checked as does the code below.

$(".payment").each(function() {

   $(this).on("click", function() {
   $(".payment").removeClass("selected");
  $(this).addClass("selected");
  $(this).find('input[type="radio"]').prop("checked", true);
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
background: #eaeaea;
}</code>```

 <input type="radio" /> example

 <input type="radio" /> of my

 <input type="radio" /> problem

```

Body:
I got small problem with my script.

The script looks like it works, but each time it adds the selected class. It resets it before the onclick, but the class does not remove it. What could be a problem?

Only one element of the .payment class from the collection should have a .selected class

$(".payment").each(function() {
    $(".payment").removeClass("selected");
    $(this).on("click", function() {
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true);
   });
});

.selected {
background: #eaeaea;
}

 <input type="radio" /> example

 <input type="radio" /> of my

 <input type="radio" /> problem

Body:
You were removing the selected class only on the beginning. I assume you want it to be removed every time a checkbox is checked as does the code below.

$(".payment").each(function() {

   $(this).on("click", function() {
   $(".payment").removeClass("selected");
  $(this).addClass("selected");
  $(this).find('input[type="radio"]').prop("checked", true);
   });
});

.selected {
background: #eaeaea;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="payment">
 <input type="radio" /> example
</div>

<div class="payment">
 <input type="radio" /> of my
</div>

<div class="payment">
 <input type="radio" /> problem
</div>


问:
Customizing an Admin form in Django while also using autodiscover
I want to modify a few tiny details of Django's built-in django.contrib.auth module.  Specifically, I want a different form that makes username an email field (and email an alternate email address.   (I'd rather not modify auth any more than necessary -- a simple form change seems to be all that's needed.)

When I use autodiscover with a customized ModelAdmin for auth I wind up conflicting with auth's own admin interface and get an "already registered" error.

It looks like I have to create my own admin site, enumerating all of my Models.  It's only 18 classes, but it seems like a DRY problem -- every change requires both adding to the Model and adding to the customized admin site.

Or, should I write my own version of "autodiscover with exclusions" to essentially import all the admin modules except auth?

答:
I think it might be easier to do this with a custom auth backend and thus remove the need for a customized ModelAdmin.

I did something similar with this snippet:
http://www.djangosnippets.org/snippets/74/

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: andybak


问:
How to decode data from scapy Dot11 Packet
I am writing a program that captures Dot11 Packets for network security testing, in these captured packets I get data as in the following for example:

```<code><RadioTap  version=0 pad=0 len=36    present=TSFT+Flags+Rate+Channel+dBm_AntSignal+b14+b29+Ext notdecoded=' \x08\x00\x00\x00\x00\x00\x00\xd5~\xbb*\x00\x00\x00\x00\x10\x02\x99\t\xa0\x00\xbd\x00\x00\x00\xbd\x00' |<Dot11  subtype=11L type=Management proto=0L FCfield=retry ID=14849 addr1=48:ee:0c:f4:b7:ea addr2=00:26:82:8e:9a:d4 addr3=48:ee:0c:f4:b7:ea SC=46176 addr4=None |<Dot11Auth  algo=open seqnum=1 status=success |<Dot11Elt  ID=220 len=46 info='7\x94' |>>>>
</code>```

I would like to better understand the part that reads:

```<code>\x08\x00\x00\x00\x00\x00\x00\xd5~\xbb*\x00\x00\x00\x00\x10\x02\x99\t\xa0\x00\xbd\x00\x00\x00\xbd\x00
</code>```

I get these types of packets in many different captures, I want to be able to 'decode' them to read the data. Is there a way to do this, perhaps a code sample?

答:
As the field name lets you guess, it contains data that cannot be decoded. If you really want to decode it, you have to either write (and maybe contribute!) your own dissector, or use Wireshark (or Tshark, same dissectors, command line interface) to parse the packet for you.

For the second option, you can use wireshark(pkt) from Scapy for Wireshark, and tcpdump(pkt, prog="tshark") for Tshark.

Body:
I am writing a program that captures Dot11 Packets for network security testing, in these captured packets I get data as in the following for example:

<RadioTap  version=0 pad=0 len=36    present=TSFT+Flags+Rate+Channel+dBm_AntSignal+b14+b29+Ext notdecoded=' \x08\x00\x00\x00\x00\x00\x00\xd5~\xbb*\x00\x00\x00\x00\x10\x02\x99\t\xa0\x00\xbd\x00\x00\x00\xbd\x00' |<Dot11  subtype=11L type=Management proto=0L FCfield=retry ID=14849 addr1=48:ee:0c:f4:b7:ea addr2=00:26:82:8e:9a:d4 addr3=48:ee:0c:f4:b7:ea SC=46176 addr4=None |<Dot11Auth  algo=open seqnum=1 status=success |<Dot11Elt  ID=220 len=46 info='7\x94' |>>>>

I would like to better understand the part that reads:

\x08\x00\x00\x00\x00\x00\x00\xd5~\xbb*\x00\x00\x00\x00\x10\x02\x99\t\xa0\x00\xbd\x00\x00\x00\xbd\x00

I get these types of packets in many different captures, I want to be able to 'decode' them to read the data. Is there a way to do this, perhaps a code sample?


问:
GridView text field data posting issue
I am Not getting text field values into grid view. Only row increases but I do not get the text.

This is the code that I have for the purpose.

```<code>    DataTable dt1 = new DataTable();
    bool flag = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gridVIEWData();
            Gridview1.DataSource = dt1;
            Gridview1.DataBind();
        }
    }
    protected void gobtn_Click(object sender, EventArgs e)
    {

        if (Session["dtInSession"] != null)
        dt1 = (DataTable)Session["dtInSession"];

        DataRow dr = dt1.NewRow();
        dr["Product"] = DropDownList1.SelectedItem;
        dr["Size"] = DropDownList2.SelectedItem;
        dr["Case"] = casetxt.Text;
        dr["Weight"] = TextBox1.Text;
        dr["Price"] = TextBox2.Text;
        dt1.Rows.Add(dr);

        Session["dtInSession"] = dt1;
        Gridview1.DataSource = dt1;
        Gridview1.DataBind();
    }

    private void gridVIEWData()
    {
        dt1.Columns.Add("Product", typeof(string));
        dt1.Columns.Add("Size", typeof(string));
        dt1.Columns.Add("Case", typeof(string));
        dt1.Columns.Add("Weight", typeof(string));
        dt1.Columns.Add("Price", typeof(string));
        Session["dtInSession"] = dt1;
    }
</code>```

Please Can any one help me

答:
```<code> **I hope you looking for something like this**

 protected void BindGridview1()
{
    DataTable dtt = new DataTable();
    DataTable dt = (DataTable)Session["od"];
    dtt.Columns.Add("BookingNO", typeof(string));
    dtt.Columns.Add("ItemName", typeof(string));
    dtt.Columns.Add("Size", typeof(string));
    dtt.Columns.Add("Unit", typeof(string));
    dtt.Columns.Add("Price", typeof(string));
    dtt.Columns.Add("PendingQty", typeof(string));

    for (int i = 0; i < dtt.Rows.Count; i++)
    {
        DataRow dr = dtt.NewRow();
        dr["BookingNO"] = string.Empty;
        dr["ItemName"] = string.Empty;
        dr["Size"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Price"] = string.Empty;
        dr["PendingQty"] = string.Empty;
        dtt.Rows.Add(dr);
    }
    dtt = dt;
    gvDetails.DataSource = dtt;
    gvDetails.DataBind();

    for (int i = 0; i <= dt.Rows.Count - 1; i++)
    {
        TextBox BookingNO = (TextBox)gvDetails.Rows[i].FindControl("BookingNO");
        TextBox ItemName = (TextBox)gvDetails.Rows[i].FindControl("ItemName");
        TextBox Size = (TextBox)gvDetails.Rows[i].FindControl("Size");
        TextBox Unit = (TextBox)gvDetails.Rows[i].FindControl("Unit");
        TextBox Price = (TextBox)gvDetails.Rows[i].FindControl("Price");
        //TextBox DueDate = (TextBox)gvDetails.Rows[i].FindControl("DueDate");
        TextBox PendingQty = (TextBox)gvDetails.Rows[i].FindControl("PendingQty");
        BookingNO.Text = Session["BookingNO1"].ToString();
        ItemName.Text = dt.Rows[i]["ItemName"].ToString();
        Size.Text = dt.Rows[i]["Size"].ToString();
        Unit.Text = dt.Rows[i]["Unit"].ToString();
        Price.Text = dt.Rows[i]["Price"].ToString();
        //DueDate.Text = dt.Rows[i]["DueDate"].ToString();
        PendingQty.Text = dt.Rows[i]["PendingQty"].ToString();

    }

}
</code>```

Title: GridView text field data posting issue

Body:
I am Not getting text field values into grid view. Only row increases but I do not get the text.

This is the code that I have for the purpose.

    DataTable dt1 = new DataTable();
    bool flag = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gridVIEWData();
            Gridview1.DataSource = dt1;
            Gridview1.DataBind();
        }
    }
    protected void gobtn_Click(object sender, EventArgs e)
    {

        if (Session["dtInSession"] != null)
        dt1 = (DataTable)Session["dtInSession"];

        DataRow dr = dt1.NewRow();
        dr["Product"] = DropDownList1.SelectedItem;
        dr["Size"] = DropDownList2.SelectedItem;
        dr["Case"] = casetxt.Text;
        dr["Weight"] = TextBox1.Text;
        dr["Price"] = TextBox2.Text;
        dt1.Rows.Add(dr);

        Session["dtInSession"] = dt1;
        Gridview1.DataSource = dt1;
        Gridview1.DataBind();
    }

    private void gridVIEWData()
    {
        dt1.Columns.Add("Product", typeof(string));
        dt1.Columns.Add("Size", typeof(string));
        dt1.Columns.Add("Case", typeof(string));
        dt1.Columns.Add("Weight", typeof(string));
        dt1.Columns.Add("Price", typeof(string));
        Session["dtInSession"] = dt1;
    }

Please Can any one help me