问:
How to perform mathematical operation on Roman numerals
How to perform mathematical operation on Roman numerals like addition,subtraction, multiplication and division in asp.net c#</p>

答:
Step 1: Convert your roman number to numerical number.

The following is the example for converting from roman to number.

```<code>private enum RomanDigit
{
    I = 1,
    V = 5,
    X = 10,
    L = 50,
    C = 100,
    D = 500,
    M = 1000
}

public static int RomanToNumbers(string roman)
{
    roman = roman.ToUpper().Trim();
    if (roman == "N") return 0;

    int ptr = 0;
    ArrayList values = new ArrayList();
    int maxDigit = 1000;
    while (ptr < roman.Length)
    {
        char numeral = roman[ptr];
        int digit = (int)Enum.Parse(typeof(RomanDigit), numeral.ToString());

        int nextDigit = 0;
        if (ptr < roman.Length - 1)
        {
            char nextNumeral = roman[ptr + 1];
            nextDigit = (int)Enum.Parse(typeof(RomanDigit), nextNumeral.ToString());

            if (nextDigit > digit)
            {
                maxDigit = digit - 1;
                digit = nextDigit - digit;
                ptr++;
            }
        }

        values.Add(digit);
        ptr++;
    }

    int total = 0;
    foreach (int digit in values)
        total += digit;

    return total;
}
</code>```

Step 2: Now use the following piece of code to get the value from the above method.

```<code>string data1 = "CDXIX";
string data2 = "CCXXII";
int value1 = RomanToNumbers(data1); //returns 419
int value2 = RomanToNumbers(data2); //returns 222
</code>```

Step 3: Now Perform your operations like sum, subtract, multiply or division or etc.

```<code>int result = value1 + value2; //641
</code>```

Step 4: use the following method to convert from numeric to Roman

```<code>public static string ToRoman(int number)
{
    if ((number < 0) || (number > 3999)) throw new ArgumentOutOfRangeException("insert value betwheen 1 and 3999");
    if (number < 1) return string.Empty;
    if (number >= 1000) return "M" + ToRoman(number - 1000);
    if (number >= 900) return "CM" + ToRoman(number - 900); //EDIT: i've typed 400 instead 900
    if (number >= 500) return "D" + ToRoman(number - 500);
    if (number >= 400) return "CD" + ToRoman(number - 400);
    if (number >= 100) return "C" + ToRoman(number - 100);
    if (number >= 90) return "XC" + ToRoman(number - 90);
    if (number >= 50) return "L" + ToRoman(number - 50);
    if (number >= 40) return "XL" + ToRoman(number - 40);
    if (number >= 10) return "X" + ToRoman(number - 10);
    if (number >= 9) return "IX" + ToRoman(number - 9);
    if (number >= 5) return "V" + ToRoman(number - 5);
    if (number >= 4) return "IV" + ToRoman(number - 4);
    if (number >= 1) return "I" + ToRoman(number - 1);
    throw new ArgumentOutOfRangeException("something bad happened");
}
</code>```

Step 5: Now again convert from numeric to Roman for result

```<code>string output = ToRoman(result); //your output "DCXLI"
</code>```

Body:
Step 1: Convert your roman number to numerical number.

The following is the example for converting from roman to number.

private enum RomanDigit
{
    I = 1,
    V = 5,
    X = 10,
    L = 50,
    C = 100,
    D = 500,
    M = 1000
}

public static int RomanToNumbers(string roman)
{
    roman = roman.ToUpper().Trim();
    if (roman == "N") return 0;

    int ptr = 0;
    ArrayList values = new ArrayList();
    int maxDigit = 1000;
    while (ptr < roman.Length)
    {
        char numeral = roman[ptr];
        int digit = (int)Enum.Parse(typeof(RomanDigit), numeral.ToString());

        int nextDigit = 0;
        if (ptr < roman.Length - 1)
        {
            char nextNumeral = roman[ptr + 1];
            nextDigit = (int)Enum.Parse(typeof(RomanDigit), nextNumeral.ToString());

            if (nextDigit > digit)
            {
                maxDigit = digit - 1;
                digit = nextDigit - digit;
                ptr++;
            }
        }

        values.Add(digit);
        ptr++;
    }

    int total = 0;
    foreach (int digit in values)
        total += digit;

    return total;
}

Step 2: Now use the following piece of code to get the value from the above method.

string data1 = "CDXIX";
string data2 = "CCXXII";
int value1 = RomanToNumbers(data1); //returns 419
int value2 = RomanToNumbers(data2); //returns 222

Step 3: Now Perform your operations like sum, subtract, multiply or division or etc.

int result = value1 + value2; //641

Step 4: use the following method to convert from numeric to Roman

public static string ToRoman(int number)
{
    if ((number < 0) || (number > 3999)) throw new ArgumentOutOfRangeException("insert value betwheen 1 and 3999");
    if (number < 1) return string.Empty;
    if (number >= 1000) return "M" + ToRoman(number - 1000);
    if (number >= 900) return "CM" + ToRoman(number - 900); //EDIT: i've typed 400 instead 900
    if (number >= 500) return "D" + ToRoman(number - 500);
    if (number >= 400) return "CD" + ToRoman(number - 400);
    if (number >= 100) return "C" + ToRoman(number - 100);
    if (number >= 90) return "XC" + ToRoman(number - 90);
    if (number >= 50) return "L" + ToRoman(number - 50);
    if (number >= 40) return "XL" + ToRoman(number - 40);
    if (number >= 10) return "X" + ToRoman(number - 10);
    if (number >= 9) return "IX" + ToRoman(number - 9);
    if (number >= 5) return "V" + ToRoman(number - 5);
    if (number >= 4) return "IV" + ToRoman(number - 4);
    if (number >= 1) return "I" + ToRoman(number - 1);
    throw new ArgumentOutOfRangeException("something bad happened");
}

Step 5: Now again convert from numeric to Roman for result

string output = ToRoman(result); //your output "DCXLI"


来源: stackexchange

问:
Umbraco - custom model causing problems?
In a vanilla Umbraco project, i am importing a vanilla MVC app.
I am currently beeing held up, by this error:

```<code>Cannot bind source type eParser.Model.MyModel to model type MyNamespace.Controllers.ViewModel`1[[eParser.Model.MyModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
</code>```

This is my code:

Local project

```<code>namespace MyNamespace.Controllers
{
    public class MyOutputController : RenderMvcController
    {
        private static Parser _parser;

        public MyOutputController()
        {
            _parser = new Parser(@"localfile.txt");
        }

        public override ActionResult Index(RenderModel model)
        {
        var settings = new RPSettings();
        var wsParser = _parser.GetwsParser();
            var result = wsParser.GetDataAsMyModel(settings);
        return View("MyView", result);
    }
     }

    public class ViewModel<TModel> : RenderModel
    {
        public ViewModel(RenderModel model) : base(model.Content, model.CurrentCulture) { }

        public TModel MyModel { get; set; }
    }
}
</code>```

External project

```<code>namespace eParser
{
    public class wsParser
    {
    public MyModel GetDataAsMyModel(RPSettings settings)
        {
            var model = new MyModel();
        return model;
    }
    }
}

namespace eParser.Model
{
    public class MyModel
    {
        public string Name { get; set; }
        public string Value1 { get; set; }
        public bool IsValid { get; set; }
    }
}
</code>```

Template

```<code>@using MyNamespace.Controllers
@using OtherNamespace.Models
@inherits Umbraco.Web.Mvc.UmbracoViewPage<ViewModel<MyModel>>
@{
    Layout = "/Views/Shared/_Layout.cshtml"; //Just <html> and very basic - no code
    var addModel = new AddListViewModel
    {
        MyType = MyType.Value1,
        MyModel = Model
    };
}

<h1>@Model.Name</h1>

namespace OtherNamespace.Models
{
    public class AddListViewModel
    {
        public string ValueName { get; set; }
        public MyType MyType { get; set; }
        public ViewModel<MyModel> MyModel { get; set; }
    }
}
</code>```

Any ideas what i could do to fix it?

答:
Your Index method is wrong - you are passing in your model to the view but you should be passing your view model instead.

It should be:

```<code>public override ActionResult Index(RenderModel model)
{
    var settings = new RPSettings();
    var wsParser = _parser.GetwsParser();
    var result = wsParser.GetDataAsMyModel(settings);

    var viewModel = new ViewModel<MyModel>(model);
    viewModel.MyModel = result;

    return View("MyView", viewModel );
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In a vanilla Umbraco project, i am importing a vanilla MVC app.
I am currently beeing held up, by this error:

Cannot bind source type eParser.Model.MyModel to model type MyNamespace.Controllers.ViewModel`1[[eParser.Model.MyModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].

This is my code:

Local project

namespace MyNamespace.Controllers
{
    public class MyOutputController : RenderMvcController
    {
        private static Parser _parser;

        public MyOutputController()
        {
            _parser = new Parser(@"localfile.txt");
        }

        public override ActionResult Index(RenderModel model)
        {
        var settings = new RPSettings();
        var wsParser = _parser.GetwsParser();
            var result = wsParser.GetDataAsMyModel(settings);
        return View("MyView", result);
    }
     }

    public class ViewModel<TModel> : RenderModel
    {
        public ViewModel(RenderModel model) : base(model.Content, model.CurrentCulture) { }

        public TModel MyModel { get; set; }
    }
}

External project

namespace eParser
{
    public class wsParser
    {
    public MyModel GetDataAsMyModel(RPSettings settings)
        {
            var model = new MyModel();
        return model;
    }
    }
}

namespace eParser.Model
{
    public class MyModel
    {
        public string Name { get; set; }
        public string Value1 { get; set; }
        public bool IsValid { get; set; }
    }
}

Template

@using MyNamespace.Controllers
@using OtherNamespace.Models
@inherits Umbraco.Web.Mvc.UmbracoViewPage<ViewModel<MyModel>>
@{
    Layout = "/Views/Shared/_Layout.cshtml"; //Just  and very basic - no code
    var addModel = new AddListViewModel
    {
        MyType = MyType.Value1,
        MyModel = Model
    };
}

@Model.Name

namespace OtherNamespace.Models
{
    public class AddListViewModel
    {
        public string ValueName { get; set; }
        public MyType MyType { get; set; }
        public ViewModel<MyModel> MyModel { get; set; }
    }
}

Any ideas what i could do to fix it?

Body:
Your Index method is wrong - you are passing in your model to the view but you should be passing your view model instead.

It should be:

public override ActionResult Index(RenderModel model)
{
    var settings = new RPSettings();
    var wsParser = _parser.GetwsParser();
    var result = wsParser.GetDataAsMyModel(settings);

    var viewModel = new ViewModel<MyModel>(model);
    viewModel.MyModel = result;

    return View("MyView", viewModel );
}


问:
C++ How to determine if function has capability for being inlined and actually was?
I have a question about inline functions in C++. I know that similar questions have appeared many times on this. I hope that mine is a little bit different.

I know that when you specify some function to be inline it is just a "suggestion" to the compiler. So in case:

```<code>inline int func1()
{
    return 2;
}
</code>```

Some code later

```<code>cout << func1() << endl; // replaced by cout << 2 << endl;
</code>```

So there is no mystery there, but what about cases like this:

```<code>inline int func1()
{
    return 2;
}

inline int func2()
{
    return func1() * 2;
}

inline int func3()
{
    return func2() * func1() * 2;
}
</code>```

And so on...

Which of these functions have a chance to become inlined, is it benefitial and how to check what compiler actually did?

答:
Which of these functions have a chance to become inlined

Any and all functions have a chance to become inlined, if the tool(1) doing the inlining has access to the function's definition (= body) ...

is it benefitial

... and deems it beneficial to do so. Nowadays, it's the job of the optimiser to determine where inlining makes sense, and for 99.9% of programs, the best the programmer can do is stay out of the optimiser's way. The remaining few cases are programs like Facebook, where 0.3% of performance loss is a huge regression. In such cases, manual tweaking of optimisations (along with profiling, profiling, and profiling) is the way to go.

how to check what compiler actually did

By inspecting the generated assembly. Every compiler has a flag to make it output assembly in "human-readable" format instead of (or in addition to) object files in binary form.

(1) Normally, this tool is the compiler and inlining happens as part of the compilation step (turning source code into assembly/object files). That is also the only reason why you may be required to use the inline keyword to actually allow a compiler to inline: because the function's definition must be visible in the translation unit (= source file) being compiled, and quite often that means putting the function definition into a header file. Without inline, this would then lead to multiple-definition errors if the header file was included in more than one translation unit.

Note that compilation is not the only stage when inlining is possible. When you enable Whole-Program Optimisation (also known as Link-Time Code Generation), one more pass of optimisation happens at link time, once all object files are created. At this point, the inline keyword is totally irrelevant, since linking has access to all the function definitions (the binary wouldn't link successfully otherwise). This is therefore the way to get the most benefit from inlining without having to think about it at all when writing code. The downside is time: WPO takes time to run, and for large projcts, can prolong link times to unacceptable levels (I've personally experienced a somewhat pathological case where enabling WPO took a program's link time from 7 minutes to 46).

Body:
I have a question about inline functions in C++. I know that similar questions have appeared many times on this. I hope that mine is a little bit different.

I know that when you specify some function to be inline it is just a "suggestion" to the compiler. So in case:

inline int func1()
{
    return 2;
}

Some code later

cout << func1() << endl; // replaced by cout << 2 << endl;

So there is no mystery there, but what about cases like this:

inline int func1()
{
    return 2;
}

inline int func2()
{
    return func1() * 2;
}

inline int func3()
{
    return func2() * func1() * 2;
}

And so on...

Which of these functions have a chance to become inlined, is it benefitial and how to check what compiler actually did?


问:
DRY templates with jekyll
I have a product grid in my Jekyll site. I'd like the product grid to appear with different products in different places on my site, but I want to only store the HTML for the grid in one place.

I've looked into collections (and I'm using collections for something else in my project), but collections don't seem to be the right tool. The product grids aren't really semantically a "group" of anything.

Is there any other way I can avoid copying the product grid HTML into multiple places?

Note: I'm new to Jekyll.

答:
You should use an 'include' for this. This is the easiest way. I think that using a 'layout' with a 'collection' would be a more beautiful solution.

```<code>{% include productgrid.html %}
</code>```

Note that you should put the 'productgrid.html' file in an '_includes' directory.

More info can be found here: http://jekyllrb.com/docs/includes/
or in this walkthrough: http://jekyllcodex.org/getting-started/

Title: DRY templates with jekyll

Body:
You should use an 'include' for this. This is the easiest way. I think that using a 'layout' with a 'collection' would be a more beautiful solution.

{% include productgrid.html %}

Note that you should put the 'productgrid.html' file in an '_includes' directory.

More info can be found here: http://jekyllrb.com/docs/includes/
or in this walkthrough: http://jekyllcodex.org/getting-started/


问:
WPF efficient drawing in usercontrol
I have a performance issue drawing a usercontrol in WPF. Here is what I do.
Basically the application plays an audio file. The class playing the audio file sends information about its position every few times a second.

I have a Usercontrol that renders the position of the file. I do it like this:

```<code>    protected override void OnRender(DrawingContext drawingContext)
    {

        // lots of drawing happens here like drawingContext.DrawRectangle,
        // drawingContext.DrawLine ....

        base.OnRender(drawingContext);
    }
</code>```

Now I have another thread in the application that does some processing (basically reading audio data) and sends information to the usercontrol afew times every second via delegate. The second process declares a delegate like this:

```<code>    protected virtual void OnBytesPlayed(BytesPlayedEventArgs e)
    {

        if (playheadCallback != null)
            playheadCallback(fileStream.CurrentTime.TotalSeconds, fileStream.TotalTime.TotalSeconds);

    }
</code>```

the usercontrol registered to that event and redraws itself as such:

```<code>    public void PlayheadPositionUpdate(double currentFrame, double allFrames)
    {

        Application.Current.Dispatcher.BeginInvoke(
           DispatcherPriority.Background,
           new System.Action(() =>
           {
               this.InvalidateVisual();
           }));
    }
</code>```

This all works, however once I enable the callback and it draws the usercontrol a few times every second everything becomes sluggish and performance goes down. So I guess the way I handle the drawing or redrawing is not efficient. Can someone point me in the right direction how to redraw the usercontrol so it does not impact the playback performance or the overall performance of the application?

Please let me know if I need to explain more or provide more code. I wanted to keep it as simple as possible to outline the problem.

thank you.

Edit:

The code that calls NAudio is

```<code>            var inputStream = new AudioFileReader(filename);

            fileStream = inputStream;

            var aggregator = new SampleAggregator(inputStream);

            aggregator.NotificationCount = inputStream.WaveFormat.SampleRate;

            aggregator.BytesPLayed += (s, a) => OnBytesPlayed(a);

            playbackDevice.Init(aggregator);
</code>```

答:
You don't want to call InvalidateVisual() as this causes a very slow re-layout of the UI. However you also don't need to use DataBinding (though it is a good solution).

To make the method you are trying to use fast, create a DrawingGroup "backingStore" to hold your drawing commands. In your OnRender() method, output the DrawingGroup to the DrawingContext. Then you can update the backingStore whenever you like and your visuals will be updated. Move your existing rendering code to a different "Render()" method that just draws into the backingStore.

The code looks like this:

```<code>DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}
</code>```

Title: WPF efficient drawing in usercontrol

Body:
I have a performance issue drawing a usercontrol in WPF. Here is what I do.
Basically the application plays an audio file. The class playing the audio file sends information about its position every few times a second.

I have a Usercontrol that renders the position of the file. I do it like this:

    protected override void OnRender(DrawingContext drawingContext)
    {

        // lots of drawing happens here like drawingContext.DrawRectangle,
        // drawingContext.DrawLine ....

        base.OnRender(drawingContext);
    }

Now I have another thread in the application that does some processing (basically reading audio data) and sends information to the usercontrol afew times every second via delegate. The second process declares a delegate like this:

    protected virtual void OnBytesPlayed(BytesPlayedEventArgs e)
    {

        if (playheadCallback != null)
            playheadCallback(fileStream.CurrentTime.TotalSeconds, fileStream.TotalTime.TotalSeconds);

    }

the usercontrol registered to that event and redraws itself as such:

    public void PlayheadPositionUpdate(double currentFrame, double allFrames)
    {

        Application.Current.Dispatcher.BeginInvoke(
           DispatcherPriority.Background,
           new System.Action(() =>
           {
               this.InvalidateVisual();
           }));
    }

This all works, however once I enable the callback and it draws the usercontrol a few times every second everything becomes sluggish and performance goes down. So I guess the way I handle the drawing or redrawing is not efficient. Can someone point me in the right direction how to redraw the usercontrol so it does not impact the playback performance or the overall performance of the application?

Please let me know if I need to explain more or provide more code. I wanted to keep it as simple as possible to outline the problem.

thank you.

Edit:

The code that calls NAudio is

            var inputStream = new AudioFileReader(filename);

            fileStream = inputStream;

            var aggregator = new SampleAggregator(inputStream);

            aggregator.NotificationCount = inputStream.WaveFormat.SampleRate;

            aggregator.BytesPLayed += (s, a) => OnBytesPlayed(a);

            playbackDevice.Init(aggregator);

Body:
You don't want to call InvalidateVisual() as this causes a very slow re-layout of the UI. However you also don't need to use DataBinding (though it is a good solution).

To make the method you are trying to use fast, create a DrawingGroup "backingStore" to hold your drawing commands. In your OnRender() method, output the DrawingGroup to the DrawingContext. Then you can update the backingStore whenever you like and your visuals will be updated. Move your existing rendering code to a different "Render()" method that just draws into the backingStore.

The code looks like this:

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}


问:
Merging Two HashTable with removal of duplicates in java
I am having two Hashtables with <int,string> pair. Now they both have duplicate values in each of them, and I want to merge both the hashtables to give me distinct values. How can I do that!?

thanks
Edit #1 I am reading file contents from a directory. and storing those contents as tokens in two different hashtables. Now I need to merge them into a single hashtable which would give me distinct values of both the tables.

答:
I guess you mean duplicate keys, not duplicate values. Also, since Hashtable is a map implementation, I'll provide a generic map solution.

```<code>// assuming the maps are of type String / String
for(Map.Entry<String, String> entry : map1.entrySet()){
    if(map2.containsKey(entry.getKey()){
        map2.remove(entry.getKey());
    }else{
        map2.put(entry.getKey(), entry.getValue());
    }
}
</code>```

Now map2 is the merged version with all duplicates removed

But if you want a Map without duplicate values, that's pretty cumbersome to achieve. Maybe you should check out the BidiMap interface in apache commons / collections. It provides maps were both keys and values are unique.

Actually, here's a simple way to remove duplicate values:

```<code>Collection<String> values1 = map1.values();
Collection<String> values2 = map2.values();
Collection<String> values1Copy = new ArrayList<String>(values1);
Collection<String> values2Copy = new ArrayList<String>(values2);
while(values1.removeAll(values2Copy)){}
while(values2.removeAll(values1Copy)){}
</code>```

Now all duplicate values are removed from both maps. (This is assuming you want to delete the dupes entirely. If you want to keep one copy, use the values1 and values2 collections in the while loops and don't take copies.)

ContentLicense: CC BY-SA 2.5

Body:
I guess you mean duplicate keys, not duplicate values. Also, since Hashtable is a map implementation, I'll provide a generic map solution.

// assuming the maps are of type String / String
for(Map.Entry<String, String> entry : map1.entrySet()){
    if(map2.containsKey(entry.getKey()){
        map2.remove(entry.getKey());
    }else{
        map2.put(entry.getKey(), entry.getValue());
    }
}

Now map2 is the merged version with all duplicates removed

But if you want a Map without duplicate values, that's pretty cumbersome to achieve. Maybe you should check out the BidiMap interface in apache commons / collections. It provides maps were both keys and values are unique.

Actually, here's a simple way to remove duplicate values:

Collection<String> values1 = map1.values();
Collection<String> values2 = map2.values();
Collection<String> values1Copy = new ArrayList<String>(values1);
Collection<String> values2Copy = new ArrayList<String>(values2);
while(values1.removeAll(values2Copy)){}
while(values2.removeAll(values1Copy)){}

Now all duplicate values are removed from both maps. (This is assuming you want to delete the dupes entirely. If you want to keep one copy, use the values1 and values2 collections in the while loops and don't take copies.)


问:
Dependency injection and serialization Object in spring
I have an application that is configured with spring security.

Everything is working as well.

The UserDetailService is:

```<code>@Service(value = "userDetail")
public class UserDetailServiceImpl implements UserDetailsService, Serializable {
    private static final long serialVersionUID = 3487495895819392L;

    @Autowired
    private IUserDetailRepository iUserDetailRepository;

    @Autowired
    private IUserRoleRepository iUserRoleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = iUserDetailRepository.loadUserByUsername(username);
        List<UserRole> roles = iUserRoleRepository.getAllRoleByUserName(username);
        UserDetails u = new UserDetails() {

            @Override
            public boolean isEnabled() {
                // return user.getEnable();
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;
            }

            @Override
            public String getUsername() {
                // return user.getUsername();
                return "reyhane";
            }

            @Override
            public String getPassword() {
                // return user.getPassword();
                return "reyhane";
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ADMIN");
                authorities.add(authority);

                return authorities;

            }
        };
        return u;
    }

}
</code>```

After that I was forced to config spring session over this configuration for saving the context of spring security into Redis.

There exists a problem in UserDetailService.

UserDetailService have two autowired filed as shown above are:

```<code>@Autowired
private IUserDetailRepository iUserDetailRepository;

@Autowired
private IUserRoleRepository iUserRoleRepository;
</code>```

This two autowired field are for getting User and User's roles information from DB.

It is interesting here that when I comment this two autowired like this:

```<code>//@Autowired
private IUserDetailRepository iUserDetailRepository;

//@Autowired
private IUserRoleRepository iUserRoleRepository;
</code>```

and fill manually user and user's role.Spring session is working as well but when this two @Autowired exist in the class the below exception is raised:

Caused by:
  org.springframework.core.serializer.support.SerializationFailedException:
  Failed to serialize object using DefaultSerializer; nested exception
  is java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:68)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:35)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:90)
  ~[spring-data-redis-1.7.2.RELEASE.jar:na] ... 35 common frames omitted
  Caused by: java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
  ~[na:1.8.0_111] at
  java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
  ~[na:1.8.0_111]

Everybody know that what is happen?

I do not understand what is happen.

I do not know there is what key for searching in google

I want to know what is happen between spring session and spring security and how to solve it.

Thanks for your helping

答:
I solve my problem with this solution:</p>

```<code>private static IUserDetailRepository userDetailRepository;

private static IUserRoleRepository userRoleRepository;

    @Autowired
    public void setUserDetailRepository(IUserDetailRepository userDetailRepository) {
        UserDetailServiceImpl.userDetailRepository = userDetailRepository;
    }

   @Autowired
   public void setUserRoleRepository(IUserRoleRepository userRoleRepository) {
       UserDetailServiceImpl.userRoleRepository = userRoleRepository;
    }
</code>```

Body:
I have an application that is configured with spring security.

Everything is working as well.

The UserDetailService is:

@Service(value = "userDetail")
public class UserDetailServiceImpl implements UserDetailsService, Serializable {
    private static final long serialVersionUID = 3487495895819392L;

    @Autowired
    private IUserDetailRepository iUserDetailRepository;

    @Autowired
    private IUserRoleRepository iUserRoleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = iUserDetailRepository.loadUserByUsername(username);
        List<UserRole> roles = iUserRoleRepository.getAllRoleByUserName(username);
        UserDetails u = new UserDetails() {

            @Override
            public boolean isEnabled() {
                // return user.getEnable();
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;
            }

            @Override
            public String getUsername() {
                // return user.getUsername();
                return "reyhane";
            }

            @Override
            public String getPassword() {
                // return user.getPassword();
                return "reyhane";
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ADMIN");
                authorities.add(authority);

                return authorities;

            }
        };
        return u;
    }

}

After that I was forced to config spring session over this configuration for saving the context of spring security into Redis.

There exists a problem in UserDetailService.

UserDetailService have two autowired filed as shown above are:

@Autowired
private IUserDetailRepository iUserDetailRepository;

@Autowired
private IUserRoleRepository iUserRoleRepository;

This two autowired field are for getting User and User's roles information from DB.

It is interesting here that when I comment this two autowired like this:

//@Autowired
private IUserDetailRepository iUserDetailRepository;

//@Autowired
private IUserRoleRepository iUserRoleRepository;

and fill manually user and user's role.Spring session is working as well but when this two @Autowired exist in the class the below exception is raised:

Caused by:
  org.springframework.core.serializer.support.SerializationFailedException:
  Failed to serialize object using DefaultSerializer; nested exception
  is java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:68)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:35)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:90)
  ~[spring-data-redis-1.7.2.RELEASE.jar:na] ... 35 common frames omitted
  Caused by: java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
  ~[na:1.8.0_111] at
  java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
  ~[na:1.8.0_111]

Everybody know that what is happen?

I do not understand what is happen.

I do not know there is what key for searching in google

I want to know what is happen between spring session and spring security and how to solve it.

Thanks for your helping

Body:
I solve my problem with this solution:

private static IUserDetailRepository userDetailRepository;

private static IUserRoleRepository userRoleRepository;

    @Autowired
    public void setUserDetailRepository(IUserDetailRepository userDetailRepository) {
        UserDetailServiceImpl.userDetailRepository = userDetailRepository;
    }

   @Autowired
   public void setUserRoleRepository(IUserRoleRepository userRoleRepository) {
       UserDetailServiceImpl.userRoleRepository = userRoleRepository;
    }


问:
Jmeter how to send multiple default values under __P like ${__P(case_ids,'2211, 2222')}
On my use case I need to send multiple default values under __P like

```<code>${__P(case_ids,'2211, 2222, ....')}
</code>```

I Tried following cases but no luck:

```<code>${__P(case_ids,'2211, 2222')}
${__P(case_ids,"2211, 2222")}
${__P(case_ids,(2211, 2222))}
</code>```

Please suggest.

答:
${__P} function call is used for getting a property and not setting it.

You need to set the property using the function:

```<code>${__setProperty(case_ids,'2211, 2222, ....')}
</code>```

Body:
On my use case I need to send multiple default values under __P like

${__P(case_ids,'2211, 2222, ....')}

I Tried following cases but no luck:

${__P(case_ids,'2211, 2222')}
${__P(case_ids,"2211, 2222")}
${__P(case_ids,(2211, 2222))}

Please suggest.

Body:
${__P} function call is used for getting a property and not setting it.

You need to set the property using the function:

${__setProperty(case_ids,'2211, 2222, ....')}

ContentLicense: CC BY-SA 4.0


问:
In AngularJS, how do I add a $watch on the URL hash?
Using Angular, how can I add a watch that is fired when the hash is updated, either by my application, or when the browser updates the URL from either the URL bar or the back/forward buttons?</p>

答:
location.hash can be updated internally by angular or externally by the user or the browser (click link in bookmarks). If it is updated internally angular runs a $scope.$apply(). If an external event updates location.hash $watch does only fire UNTIL AFTER the next $scope.$apply(), e.g. a user pushes a button within your app.

If you wish to use a $watch, add an additional event listener to "hashchange" to call $apply, or add all functionality to the native DOM listener AND do not forget to call $apply(), as this is an external call.

```<code>window.addEventListener("hashchange", function(){ $scope.$apply(); }, false);
</code>```

OR ...

```<code>window.addEventListener("hashchange", function(){ me._locationHashChanged(); $scope.$apply(); }, false);
</code>```

Body:
location.hash can be updated internally by angular or externally by the user or the browser (click link in bookmarks). If it is updated internally angular runs a $scope.$apply(). If an external event updates location.hash $watch does only fire UNTIL AFTER the next $scope.$apply(), e.g. a user pushes a button within your app.

If you wish to use a $watch, add an additional event listener to "hashchange" to call $apply, or add all functionality to the native DOM listener AND do not forget to call $apply(), as this is an external call.

window.addEventListener("hashchange", function(){ $scope.$apply(); }, false);

OR ...

window.addEventListener("hashchange", function(){ me._locationHashChanged(); $scope.$apply(); }, false);


问:
How to test if a td is a child of a tr in jquery
I want to void treating the last tr's tds of a table while iteration through all td's in a table's columns:

```<code>for (i = 0; i < tableLength; i++) {
  $('#myTable>tbody>tr>td:nth-child(' + i + ')').each(function() {
      //stuf to do : if $(this)... not a child of $('#myTable tr:last')
    }
  }
</code>```

答:
You can check if the  is in the last
 using the following:

```<code>$(this).parent().is(':last-child')
</code>```

For example:

$('table tr td').each(function() {
 if( $(this).parent().is(':last-child') )
  {

  }
  else
  {
   $(this).css('background', 'red');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
  border: 1px solid #000;
  padding: 10px;
}</code>```

```

Body:
I want to void treating the last tr's tds of a table while iteration through all td's in a table's columns:

for (i = 0; i < tableLength; i++) {
  $('#myTable>tbody>tr>td:nth-child(' + i + ')').each(function() {
      //stuf to do : if $(this)... not a child of $('#myTable tr:last')
    }
  }

Body:
You can check if the <td> is in the last <tr> using the following:

$(this).parent().is(':last-child')

For example:

$('table tr td').each(function() {
 if( $(this).parent().is(':last-child') )
  {

  }
  else
  {
   $(this).css('background', 'red');
  }
});

td {
  border: 1px solid #000;
  padding: 10px;
}

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


问:
How can i get (handle) Uninstall event of Application in android?
i want to handle uninstall event of application in android like Google Play shown active user and if i remove app then it also increase in-active user count.</p>

答:
You can make use of the GCM/FCM to figure out the registration status.
If you try to send a message to an uninstalled device, it will fail with the response of "NotRegistered".

Take a look at this:
https://firebase.google.com/docs/cloud-messaging/server#response

Hope its not too late.


问:
Could not load the assembly 'App_Web_xmyvjx04'
I compiled my ASP.Net files and uploaded them to my server (godaddy host) but I got this Run time
Error:

```<code>Parser Error Message: Could not load the assembly 'App_Web_xmyvjx04'. Make
sure that it is compiled before accessing the page.

Line 1:  <%@ page language="C#" autoeventwireup="true" inherits="movies,
App_Web_xmyvjx04" %>
</code>```

I have the file App_Web_xmyvjx04.dll uploaded in my bin folder

答:
you need to specify namespace.classname in your inherits and make sure App_Web_xmyvjx04 assembly is inside your bin folder.

Example:

```<code><%@ page language="C#" autoeventwireup="true" inherits="App_Web_xmyvjx04.movies, App_Web_xmyvjx04" %>
</code>```

Body:
I compiled my ASP.Net files and uploaded them to my server (godaddy host) but I got this Run time
Error:

Parser Error Message: Could not load the assembly 'App_Web_xmyvjx04'. Make
sure that it is compiled before accessing the page.

Line 1:  <%@ page language="C#" autoeventwireup="true" inherits="movies,
App_Web_xmyvjx04" %>

I have the file App_Web_xmyvjx04.dll uploaded in my bin folder

Body:
you need to specify namespace.classname in your inherits and make sure App_Web_xmyvjx04 assembly is inside your bin folder.

Example:

<%@ page language="C#" autoeventwireup="true" inherits="App_Web_xmyvjx04.movies, App_Web_xmyvjx04" %>


问:
Delete php is not working
My database does not have unique id.

```<code>include('php_connect.php');

// check if the 'Userid' variable is set in URL, and check that it is valid
if (isset($_GET['ServerName']))
{
// get id value
    $userid = $_GET['ServerName'];
// delete the entry
    $strSQL = "DELETE from server WHERE ServerName = (?)";
    $params = array($userid);
    $stmt = sqlsrv_query( $conn, $strSQL, $params);
    if( $stmt ){
        sqlsrv_commit( $conn );
        echo "Record Deleted";
        }
    else
    {
        echo $params[0];
        echo "statement error.<br />";
        die( print_r( sqlsrv_errors(), true));
    }
    sqlsrv_close( $conn );
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
    echo "WTH Something happened to the ServerName!.<br />";
    echo "Better start over.<br />";
}

?>
</code>```

and the results is this:

```<code>WTH Something happened to the ServerName!
Better start over
</code>```

答:
Simple</p>

```<code> if(!$_GET['ServerName']){}
</code>```

Title: Delete php is not working

Body:
My database does not have unique id.

include('php_connect.php');

// check if the 'Userid' variable is set in URL, and check that it is valid
if (isset($_GET['ServerName']))
{
// get id value
    $userid = $_GET['ServerName'];
// delete the entry
    $strSQL = "DELETE from server WHERE ServerName = (?)";
    $params = array($userid);
    $stmt = sqlsrv_query( $conn, $strSQL, $params);
    if( $stmt ){
        sqlsrv_commit( $conn );
        echo "Record Deleted";
        }
    else
    {
        echo $params[0];
        echo "statement error.
";
        die( print_r( sqlsrv_errors(), true));
    }
    sqlsrv_close( $conn );
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
    echo "WTH Something happened to the ServerName!.
";
    echo "Better start over.
";
}

?>

and the results is this:

WTH Something happened to the ServerName!
Better start over

Body:
Simple

 if(!$_GET['ServerName']){}


问:
Compare list of JSONArray in ArrayList
I have an ArrayList containing a list of JSONArrays

```<code>staffArray = new ArrayList<JSONArray>();
</code>```

the JSONArray is in a form of this:

```<code>[
    {
      "id": "k40dn-dff02-mm1",
      "name": "staff1",
      "tel": "0123456789",
    },
    {
      "id": "ch2mq-pmw01-ps6",
      "name": "staff2",
      "tel": "9876543210",
    }
    ...
]
</code>```

And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.

So far I have tried this to extract the string:

```<code>for(int i = 0; i < staffArray.size(); i++){
    JSONArray jsonArray = new JSONArray();
    jsonArray = staffArray.get(i);
    for(int j = 0; j < jsonArray.length(); j ++){
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            String id = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
How about using group by to group the json arrays with same id something like this</p>

```<code>public static void groupById(List<JSONArray> staffArray) {
    Map<String, List<JSONArray>> jsonArraysById = staffArray.stream().collect(Collectors.groupingBy(jsonArray -> getIdFromJsonArray(jsonArray)));
    jsonArraysById.forEach((id, arrays) -> {
        System.out.println("Arrays with id " + id + " are " + arrays);
    });
}

public static String getIdFromJsonArray(JSONArray jsonArray) {
    String result = null;
    for (int j = 0; j < jsonArray.length(); j++) {
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            result = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return result;
}
</code>```

Title: Compare list of JSONArray in ArrayList

Body:
I have an ArrayList containing a list of JSONArrays

staffArray = new ArrayList<JSONArray>();

the JSONArray is in a form of this:

[
    {
      "id": "k40dn-dff02-mm1",
      "name": "staff1",
      "tel": "0123456789",
    },
    {
      "id": "ch2mq-pmw01-ps6",
      "name": "staff2",
      "tel": "9876543210",
    }
    ...
]

And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.

So far I have tried this to extract the string:

for(int i = 0; i < staffArray.size(); i++){
    JSONArray jsonArray = new JSONArray();
    jsonArray = staffArray.get(i);
    for(int j = 0; j < jsonArray.length(); j ++){
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            String id = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Body:
How about using group by to group the json arrays with same id something like this

public static void groupById(List<JSONArray> staffArray) {
    Map<String, List<JSONArray>> jsonArraysById = staffArray.stream().collect(Collectors.groupingBy(jsonArray -> getIdFromJsonArray(jsonArray)));
    jsonArraysById.forEach((id, arrays) -> {
        System.out.println("Arrays with id " + id + " are " + arrays);
    });
}

public static String getIdFromJsonArray(JSONArray jsonArray) {
    String result = null;
    for (int j = 0; j < jsonArray.length(); j++) {
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            result = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return result;
}


问:
How to draw a "speech bubble" on an iPhone?
I'm trying to get a "speech bubble" effect similar to the one in Mac OS X when you right click on something in the dock.  Here's what I have now:

I need to get the "triangle" part of the lower portion.  Is there any way I can draw something like that and get a border around it?  This will be for an iPhone app.

Thanks in advance!

EDIT:  Many thanks to Brad Larson, here's what it looks like now:

答:
See the triangle on the pop up menu in the image below, thats drawn with Core Graphics funcs and is completely scalable.

Done like this to do an equilateral triangle (old-school function names, sorry):

```<code>#define triH(v) (v * 0.866)

func(CGContextRef inContext, CGRect arrowRect, CustomPushButtonData* controlData) {
// Draw the triangle
float   arrowXstart, arrowYstart;
float   arrowXpos, arrowYpos, arrowHpos;

if (controlData->controlEnabled && controlData->controlActive) {

    CGContextSetRGBFillColor(inContext, 0., 0., 0., 1.);

} else {

    CGContextSetRGBFillColor(inContext, 0., 0., 0., 0.5);

}

arrowHpos = triH(arrowRect.size.height);

// Point C

CGContextBeginPath(inContext);

arrowXstart = arrowXpos = (arrowRect.origin.x + ((float)(arrowRect.size.width / 2.) - (arrowSize / 2.)));

arrowYstart = arrowYpos = (arrowRect.origin.y + (float)((arrowRect.size.height / 2.) - (float)(arrowHpos / 2.)));

CGContextMoveToPoint(inContext, arrowXpos, arrowYpos);

// Point A

arrowXpos += arrowSize;

CGContextAddLineToPoint(inContext, arrowXpos, arrowYpos);

// Point B

arrowYpos += arrowHpos;

arrowXpos -= (float)(arrowSize / 2.0);

CGContextAddLineToPoint(inContext, arrowXpos, arrowYpos);

// Point C
CGContextAddLineToPoint(inContext, arrowXstart, arrowYstart);

CGContextClosePath(inContext);

CGContextFillPath(inContext);
</code>```

}

Note that the triH(x) func is an optimized formula for calculating the height of an equitlateral triangle e.g. h = 1/2 * sqrt(3) * x . Since 1/2 * sqrt(3) never changes, I optimized it into that define.

Body:
See the triangle on the pop up menu in the image below, thats drawn with Core Graphics funcs and is completely scalable.

Done like this to do an equilateral triangle (old-school function names, sorry):

#define triH(v) (v * 0.866)

func(CGContextRef inContext, CGRect arrowRect, CustomPushButtonData* controlData) {
// Draw the triangle
float   arrowXstart, arrowYstart;
float   arrowXpos, arrowYpos, arrowHpos;

if (controlData->controlEnabled && controlData->controlActive) {

    CGContextSetRGBFillColor(inContext, 0., 0., 0., 1.);

} else {

    CGContextSetRGBFillColor(inContext, 0., 0., 0., 0.5);

}

arrowHpos = triH(arrowRect.size.height);

// Point C

CGContextBeginPath(inContext);

arrowXstart = arrowXpos = (arrowRect.origin.x + ((float)(arrowRect.size.width / 2.) - (arrowSize / 2.)));

arrowYstart = arrowYpos = (arrowRect.origin.y + (float)((arrowRect.size.height / 2.) - (float)(arrowHpos / 2.)));

CGContextMoveToPoint(inContext, arrowXpos, arrowYpos);

// Point A

arrowXpos += arrowSize;

CGContextAddLineToPoint(inContext, arrowXpos, arrowYpos);

// Point B

arrowYpos += arrowHpos;

arrowXpos -= (float)(arrowSize / 2.0);

CGContextAddLineToPoint(inContext, arrowXpos, arrowYpos);

// Point C
CGContextAddLineToPoint(inContext, arrowXstart, arrowYstart);

CGContextClosePath(inContext);

CGContextFillPath(inContext);

}

Note that the triH(x) func is an optimized formula for calculating the height of an equitlateral triangle e.g. h = 1/2 * sqrt(3) * x . Since 1/2 * sqrt(3) never changes, I optimized it into that define.


问:
Generics and Inheritance corner case
I have following code and it is not behaving as i am thinking. I have put the comments inline , that what is happening and what is expected.

```<code>class C<T> {
    void m(T arg) {
    }
}

interface I {
    void m(Class arg);
}

class D extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: error -- abstract method not overridden

abstract class E extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: no error, but no bridge method
</code>```

Can some one please help me understand this behavior.

答:
I expect following discussion in jdk8.

In the your code:

```<code>class D extends C<Class<String>> implements I {
</code>```

}

should implement the interface I like this:

```<code>class D extends C<Class<String>> implements I {

    @Override
    public void m(Class arg) {

    }
}
</code>```

Let's see why should implement the method in the interface I.According the JLS8.4.8.1:

```<code>An instance method mC declared in or inherited by class C, overrides from C another
method mI declared in an interface I, iff all of the following are true:
• I is a superinterface of C.
• mI is an abstract or default method.
• The signature of mC is a subsignature (§8.4.2) of the signature of mI.
</code>```

In the above code,the mC is void m(Class<String> arg) in Class D,the mI is void m(Class arg)

And see the specification of subsignature:

```<code>And the `JLS8.4.2` explain the subsignature between two method:

The signature of a method m1 is a subsignature of the signature of a method m2 if
either:
• m2 has the same signature as m1, or
• the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
</code>```

According to above specification ,the void m(Class<String> arg is not subsignature of void m(Class arg),but the void m(Class arg) is subsignature of void m(Class<String> arg.So the Class D should implement the interface I explicitly.

See following code to explain it:

```<code>class C {
    public void m(Class arg) {
    }
}

interface I<T> {
    void m(T arg);
}

class D extends C implements I<Class<String>> {

}
</code>```

it will compile ok.

The second,Why there is not method conflicting,Because of the JLS8.4.8 explain the inheritance of class:

```<code>A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:
• m is a member of the direct superclass of C.
• m is public, protected, or declared with package access in the same package as C.
• No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m.
</code>```

According to above specification,the method void m(T arg) with Class<String> parameter of T be translated to void m(Class<String> arg).And the converted method will be erasured to void m(Class arg),this method will be existed in class D,so the Class D don't inherit the method void m(T arg) in class C.

Title: Generics and Inheritance corner case

Body:
I have following code and it is not behaving as i am thinking. I have put the comments inline , that what is happening and what is expected.

class C<T> {
    void m(T arg) {
    }
}

interface I {
    void m(Class arg);
}

class D extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: error -- abstract method not overridden

abstract class E extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: no error, but no bridge method

Can some one please help me understand this behavior.

Body:
I expect following discussion in jdk8.

In the your code:

class D extends C<Class<String>> implements I {

}

should implement the interface I like this:

class D extends C<Class<String>> implements I {

    @Override
    public void m(Class arg) {

    }
}

Let's see why should implement the method in the interface I.According the JLS8.4.8.1:

An instance method mC declared in or inherited by class C, overrides from C another
method mI declared in an interface I, iff all of the following are true:
• I is a superinterface of C.
• mI is an abstract or default method.
• The signature of mC is a subsignature (§8.4.2) of the signature of mI.

In the above code,the mC is void m(Class<String> arg) in Class D,the mI is void m(Class arg)

And see the specification of subsignature:

And the `JLS8.4.2` explain the subsignature between two method:

The signature of a method m1 is a subsignature of the signature of a method m2 if
either:
• m2 has the same signature as m1, or
• the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

According to above specification ,the void m(Class<String> arg is not subsignature of void m(Class arg),but the void m(Class arg) is subsignature of void m(Class<String> arg.So the Class D should implement the interface I explicitly.

See following code to explain it:

class C {
    public void m(Class arg) {
    }
}

interface I<T> {
    void m(T arg);
}

class D extends C implements I<Class<String>> {

}

it will compile ok.

The second,Why there is not method conflicting,Because of the JLS8.4.8 explain the inheritance of class:

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:
• m is a member of the direct superclass of C.
• m is public, protected, or declared with package access in the same package as C.
• No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m.

According to above specification,the method void m(T arg) with Class<String> parameter of T be translated to void m(Class<String> arg).And the converted method will be erasured to void m(Class arg),this method will be existed in class D,so the Class D don't inherit the method void m(T arg) in class C.


问:
How to loop tooptip additional data in chart.js
Here i have a graph which contains x-axis data and y-axis data which are com from db table. and now i am facing a problem is that, wherever i trying to append this 3rd data in afterbody callback function in tooltip. it will shows entire data in each and every tool tip.

But i want to append these data in each tool tip respectively.

like:

on 1st tool tip margin 12%

on 2nd tool tip margin 5%

on 3rd tool tip margin 25% and so on.

Here is a screen shot from current graph with tool tip data

And here is my code

```<code>    $(document).ready(function(){
    $.ajax({
        url: "<?php base_url();?>/charts/getsome",
        method: "GET",
        success: function(data) {
            console.log(data);
            var data = JSON.parse(data);
            var month = [];
            var customers = [];
            var margin = [];

            for(var i in data) {
                month.push("Customer in " + data[i].apply_month);
                customers.push(data[i].no_customers);
                margin.push(data[i].margin);
            }
            var chartdata = {
                labels: month,
                datasets : [
                    {
                        label: 'monthly customers for Year 2016',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: customers,
                        fill: false
                    }

                ]

            };

            var frame = $("#mycanvas");

            var barGraph = new Chart(frame, {
                type: 'line',
                data: chartdata,
                options: {
                          responsive: true,
                          tooltips: {
                             callbacks: {
                                afterBody: function(t, d) {
                                   return 'margin  '+margin;
                                }
                             }
                          }
                       }
            });
        },
        error: function(data) {
            console.log(data);
        }
    });
});
</code>```

Now i just want to showing these margin percentage data separately for each tool tip. Please suggest me, where i am going wrong? Thanks in Advance :)

答:
Replace your tooltip's afterBody callback function ...

ꜰʀᴏᴍ ᴛʜɪꜱ

```<code>tooltips: {
   callbacks: {
      afterBody: function(t, d) {
         return 'margin  ' + margin;
      }
   }
}
</code>```

ᴛᴏ ᴛʜɪꜱ

```<code>tooltips: {
   callbacks: {
      afterBody: function(t, d) {
         return 'margin ' + margin[t[0].index];
      }
   }
}
</code>```

Body:
Here i have a graph which contains x-axis data and y-axis data which are com from db table. and now i am facing a problem is that, wherever i trying to append this 3rd data in afterbody callback function in tooltip. it will shows entire data in each and every tool tip.

But i want to append these data in each tool tip respectively.

like:

on 1st tool tip margin 12%

on 2nd tool tip margin 5%

on 3rd tool tip margin 25% and so on.

Here is a screen shot from current graph with tool tip data

And here is my code

    $(document).ready(function(){
    $.ajax({
        url: "<?php base_url();?>/charts/getsome",
        method: "GET",
        success: function(data) {
            console.log(data);
            var data = JSON.parse(data);
            var month = [];
            var customers = [];
            var margin = [];

            for(var i in data) {
                month.push("Customer in " + data[i].apply_month);
                customers.push(data[i].no_customers);
                margin.push(data[i].margin);
            }
            var chartdata = {
                labels: month,
                datasets : [
                    {
                        label: 'monthly customers for Year 2016',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: customers,
                        fill: false
                    }

                ]

            };

            var frame = $("#mycanvas");

            var barGraph = new Chart(frame, {
                type: 'line',
                data: chartdata,
                options: {
                          responsive: true,
                          tooltips: {
                             callbacks: {
                                afterBody: function(t, d) {
                                   return 'margin  '+margin;
                                }
                             }
                          }
                       }
            });
        },
        error: function(data) {
            console.log(data);
        }
    });
});

Now i just want to showing these margin percentage data separately for each tool tip. Please suggest me, where i am going wrong? Thanks in Advance :)

Body:
Replace your tooltip's afterBody callback function ...

ꜰʀᴏᴍ ᴛʜɪꜱ

tooltips: {
   callbacks: {
      afterBody: function(t, d) {
         return 'margin  ' + margin;
      }
   }
}

ᴛᴏ ᴛʜɪꜱ

tooltips: {
   callbacks: {
      afterBody: function(t, d) {
         return 'margin ' + margin[t[0].index];
      }
   }
}


问:
ld: 2 duplicate symbols for architecture armv7 Splunk MINT SDK Xcode 8.2
After adding Splunk MINT SDK into existing project, I'm experiencing a linker duplicates now:

```<code>duplicate symbol _OBJC_CLASS_$_SSMemoryInfo in:
    /Users/Mac05/Library/Developer/Xcode/DerivedData/../armv7/SSMemoryInfo.o
    ../SplunkMint.framework/SplunkMint(SSMemoryInfo.o)
duplicate symbol _OBJC_METACLASS_$_SSMemoryInfo in:
    /Users/Mac05/Library/Developer/Xcode/DerivedData/../Objects-normal/armv7/SSMemoryInfo.o
    /Volumes/Data HD/../SplunkMint.framework/SplunkMint(SSMemoryInfo.o)
ld: 2 duplicate symbols for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Here I'm using Facebook, Google Maps, Google Login and Google Places SDK's too.
Please help me with this error.

this the SKD's developer guide site : Splunk MINT SDK for iOS Developer Guide

答:
Add each of the remaining required frameworks and libraries as
  follows. Under Link Binary With Libraries, click the + button, click
  Add Other, select one of the following, then click Add:

```<code>SystemConfiguration.framework
CoreTelephony.framework
CoreLocation.framework
WebKit.framework
libz.dylib
</code>```

Body:
After adding Splunk MINT SDK into existing project, I'm experiencing a linker duplicates now:

duplicate symbol _OBJC_CLASS_$_SSMemoryInfo in:
    /Users/Mac05/Library/Developer/Xcode/DerivedData/../armv7/SSMemoryInfo.o
    ../SplunkMint.framework/SplunkMint(SSMemoryInfo.o)
duplicate symbol _OBJC_METACLASS_$_SSMemoryInfo in:
    /Users/Mac05/Library/Developer/Xcode/DerivedData/../Objects-normal/armv7/SSMemoryInfo.o
    /Volumes/Data HD/../SplunkMint.framework/SplunkMint(SSMemoryInfo.o)
ld: 2 duplicate symbols for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here I'm using Facebook, Google Maps, Google Login and Google Places SDK's too.
Please help me with this error.

this the SKD's developer guide site : Splunk MINT SDK for iOS Developer Guide

Body:
Add each of the remaining required frameworks and libraries as
  follows. Under Link Binary With Libraries, click the + button, click
  Add Other, select one of the following, then click Add:

SystemConfiguration.framework
CoreTelephony.framework
CoreLocation.framework
WebKit.framework
libz.dylib


问:
Execute external program from Linux/Delphi 10.2 console application
How can I execute an external program from a Linux console application created in Delphi 10.2 Tokyo?

What I want to do is execute a shell command with parameters like

```<code>/home/test/qrencode -o /tmp/abc.png '08154711'
</code>```

I do not need the output of the program but it should be executed synchronously.

It is easy in Windows environments but as 64 bit Linux support in Delphi (after  Kylix) is quite new, I could not find any hints on the Web by now.

Any tip helping me to solve that is very appreciated.

Thanks in advance!

答:
Davids hint pointed me to an example that helped creating the solution. The most tricky part was finding out how to convert a Delphi string to a MarshaledAString as the example used a const string as argument for popen. I tested on RHEL 7.3, runs like a charm.</p>

```<code>uses
  ...
  System.SysUtils,
  Posix.Base,
  Posix.Fcntl,
  ...;

type
  TStreamHandle = pointer;

function popen(const command: MarshaledAString; const _type: MarshaledAString): TStreamHandle; cdecl;
      external libc name _PU + 'popen';
function pclose(filehandle: TStreamHandle): int32; cdecl; external libc name _PU + 'pclose';
function fgets(buffer: pointer; size: int32; Stream: TStreamHandle): pointer; cdecl; external libc name _PU + 'fgets';

function runCommand(const acommand: MarshaledAString): String;
// run a linux shell command and return output
// Adapted from http://chapmanworld.com/2017/04/06/calling-linux-commands-from-delphi/
var
  handle: TStreamHandle;
  data: array [0 .. 511] of uint8;

  function bufferToString(buffer: pointer; maxSize: uint32): string;
  var
    cursor: ^uint8;
    endOfBuffer: nativeuint;
  begin
    if not assigned(buffer) then
      exit;
    cursor := buffer;
    endOfBuffer := nativeuint(cursor) + maxSize;
    while (nativeuint(cursor) < endOfBuffer) and (cursor^ <> 0) do
    begin
      result := result + chr(cursor^);
      cursor := pointer(succ(nativeuint(cursor)));
    end;
  end;

begin
  result := '';
  handle := popen(acommand, 'r');
  try
    while fgets(@data[0], sizeof(data), handle) <> nil do
    begin
      result := result + bufferToString(@data[0], sizeof(data));
    end;
  finally
    pclose(handle);
  end;
end;

function createQRCode(id, fn: string): string;
// Create qr-code using qrencode package
begin
  deletefile(fn);
  if fileExists(fn) then
    raise Exception.create('Old file not deleted!');
  // I am targeting rhel for now, so I know the path for sure
  result := runCommand(MarshaledAString(UTF8STring('/usr/bin/qrencode -o ' + fn + ' ''' + id + '''')));
  if not fileExists(fn) then
    raise Exception.create('New file not created!');
end;

function testqr: String;
// Test QR Code creation with error handling
// QREncode does not output anything but who knows ;-)
begin
  try
    result := createQRCode('08154711', '/tmp/myqrcode.png');
  except
    on e: Exception do
    begin
      result := 'Error: ' + e.message;
    end;
  end;
end;
</code>```

Body:
How can I execute an external program from a Linux console application created in Delphi 10.2 Tokyo?

What I want to do is execute a shell command with parameters like

/home/test/qrencode -o /tmp/abc.png '08154711'

I do not need the output of the program but it should be executed synchronously.

It is easy in Windows environments but as 64 bit Linux support in Delphi (after  Kylix) is quite new, I could not find any hints on the Web by now.

Any tip helping me to solve that is very appreciated.

Thanks in advance!

Body:
Davids hint pointed me to an example that helped creating the solution. The most tricky part was finding out how to convert a Delphi string to a MarshaledAString as the example used a const string as argument for popen. I tested on RHEL 7.3, runs like a charm.

uses
  ...
  System.SysUtils,
  Posix.Base,
  Posix.Fcntl,
  ...;

type
  TStreamHandle = pointer;

function popen(const command: MarshaledAString; const _type: MarshaledAString): TStreamHandle; cdecl;
      external libc name _PU + 'popen';
function pclose(filehandle: TStreamHandle): int32; cdecl; external libc name _PU + 'pclose';
function fgets(buffer: pointer; size: int32; Stream: TStreamHandle): pointer; cdecl; external libc name _PU + 'fgets';

function runCommand(const acommand: MarshaledAString): String;
// run a linux shell command and return output
// Adapted from http://chapmanworld.com/2017/04/06/calling-linux-commands-from-delphi/
var
  handle: TStreamHandle;
  data: array [0 .. 511] of uint8;

  function bufferToString(buffer: pointer; maxSize: uint32): string;
  var
    cursor: ^uint8;
    endOfBuffer: nativeuint;
  begin
    if not assigned(buffer) then
      exit;
    cursor := buffer;
    endOfBuffer := nativeuint(cursor) + maxSize;
    while (nativeuint(cursor) < endOfBuffer) and (cursor^ <> 0) do
    begin
      result := result + chr(cursor^);
      cursor := pointer(succ(nativeuint(cursor)));
    end;
  end;

begin
  result := '';
  handle := popen(acommand, 'r');
  try
    while fgets(@data[0], sizeof(data), handle) <> nil do
    begin
      result := result + bufferToString(@data[0], sizeof(data));
    end;
  finally
    pclose(handle);
  end;
end;

function createQRCode(id, fn: string): string;
// Create qr-code using qrencode package
begin
  deletefile(fn);
  if fileExists(fn) then
    raise Exception.create('Old file not deleted!');
  // I am targeting rhel for now, so I know the path for sure
  result := runCommand(MarshaledAString(UTF8STring('/usr/bin/qrencode -o ' + fn + ' ''' + id + '''')));
  if not fileExists(fn) then
    raise Exception.create('New file not created!');
end;

function testqr: String;
// Test QR Code creation with error handling
// QREncode does not output anything but who knows ;-)
begin
  try
    result := createQRCode('08154711', '/tmp/myqrcode.png');
  except
    on e: Exception do
    begin
      result := 'Error: ' + e.message;
    end;
  end;
end;


问:
Need advice before I develop a bad habit
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

```<code>//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}
</code>```

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

```<code>@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            IDSubcategory
        </th>
        <th>
            IDCity
        </th>
        <th>
            IDPerson
        </th>
        <th>
            Title
        </th>
        <th>
            TextBody
        </th>
        <th>
            ContactNumber
        </th>
        <th>
            AskingPrice
        </th>
        <th>
            AddressDirection
        </th>
        <th>
            LatestUpdateDate
        </th>
        <th>
            VisitCount
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
        <td>
            @item.IDSubcategory
        </td>
        <td>
            @item.IDCity
        </td>
        <td>
            @item.IDPerson
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @item.TextBody
        </td>
        <td>
            @item.ContactNumber
        </td>
        <td>
            @String.Format("{0:F}", item.AskingPrice)
        </td>
        <td>
            @item.AddressDirection
        </td>
        <td>
            @String.Format("{0:g}", item.LatestUpdateDate)
        </td>
        <td>
            @item.VisitCount
        </td>
    </tr>
}

</table>
</code>```

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.

答:
I'd modify this to:

```<code>public ActionResult Index(string categoryName)
{

    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions=auctionRepo.FindAllAuctions();

    if (!string.IsNullOrEmpty(categoryName))
    {
        auctions = auctions.Where(c => c.Subcategory.Category.Name == categoryName);
    }

    return View(auctions);
}
</code>```

Your route might then look like:

```<code>    context.MapRoute(
        "auction_defalt",
        "Auction/{categoryName}",
        new { controller="Auction", action = "Index", categoryName = UrlParameter.Optional }
</code>```

Since the actions are so similar, I don't see a reason to separate them.

OwnerDisplayName: delete

LastEditorDisplayName: delete

Body:
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            IDSubcategory

            IDCity

            IDPerson

            Title

            TextBody

            ContactNumber

            AskingPrice

            AddressDirection

            LatestUpdateDate

            VisitCount

@foreach (var item in Model) {

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

            @item.IDSubcategory

            @item.IDCity

            @item.IDPerson

            @item.Title

            @item.TextBody

            @item.ContactNumber

            @String.Format("{0:F}", item.AskingPrice)

            @item.AddressDirection

            @String.Format("{0:g}", item.LatestUpdateDate)

            @item.VisitCount

}

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.

Body:
I'd modify this to:

public ActionResult Index(string categoryName)
{

    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions=auctionRepo.FindAllAuctions();

    if (!string.IsNullOrEmpty(categoryName))
    {
        auctions = auctions.Where(c => c.Subcategory.Category.Name == categoryName);
    }

    return View(auctions);
}

Your route might then look like:

    context.MapRoute(
        "auction_defalt",
        "Auction/{categoryName}",
        new { controller="Auction", action = "Index", categoryName = UrlParameter.Optional }

Since the actions are so similar, I don't see a reason to separate them.


问:
Laravel 5.4: custom Middleware not working in route
I created the following Middleware to check user session

```<code><?php

namespace App\Http\Middleware;

use Closure;

class Checkusersession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->session()->has('admin_name')) {
            // user value cannot be found in session
            return redirect('adminlogin');
        }

        return $next($request);
    }
}
</code>```

this is my route:

```<code> Route::get('webadmin',['middleware' => 'usersession','Admin_controller@index']);
</code>```

this is my kernel.php

```<code> protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'usersession' => \App\Http\Middleware\Checkusersession::class,
];
</code>```

this is my controller method that creates session:

```<code>public function auth_admin(Request $request)
{
    $admin_emai = $request->input('admin_email');
    $admin_password = $request->input('admin_password');

    $checklogin = DB::table('admin_login')
        ->select('admin_id','admin_email','admin_name')
        ->where([
            'admin_email' => $admin_email,
            'admin_password' => $admin_password
        ])->first();

    if (count($checklogin) > 0) {
        $request->session()->put('admin_id',$checklogin->admin_id);
        $request->session()->put('admin_name',$checklogin->admin_name);
        $request->session()->put('admin_email',$checklogin->admin_email);

        return redirect()->action('Admin_controller@webadmin');
    } else {
        return redirect()->action('Admin_controller@admin_login_page')->with('status','Incorrect Email ID or Password');
    }
}
</code>```

I want the Middleware to check if the session (admin_name) exists or not. If not, redirect the user to the login page. but it is not working. if I access the webadmin (dashboard) directly from url, it gives me access even if the session is not set. Please help.

答:
Your route is wrong, you should write it as (in L5.4):

```<code>Route::get('webadmin', 'Admin_controller@index')->middleware('usersession');
</code>```

Or even:

```<code>Route::group(['middleware' => 'auth'], function(){
    Route::get('webadmin', 'Admin_controller@index');
});
</code>```

In L5.3 (as you have tagged the question), and in L5.4 I guess you could also write:

```<code>Route::get('webadmin',['middleware' => 'usersession', 'uses => 'Admin_controller@index']);
</code>```

Also, have you tried just to do a dd(request()); or similar in your middleware-handle function to see that it is actually fired?

Body:
I created the following Middleware to check user session

<?php

namespace App\Http\Middleware;

use Closure;

class Checkusersession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->session()->has('admin_name')) {
            // user value cannot be found in session
            return redirect('adminlogin');
        }

        return $next($request);
    }
}

this is my route:

 Route::get('webadmin',['middleware' => 'usersession','Admin_controller@index']);

this is my kernel.php

 protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'usersession' => \App\Http\Middleware\Checkusersession::class,
];

this is my controller method that creates session:

public function auth_admin(Request $request)
{
    $admin_emai = $request->input('admin_email');
    $admin_password = $request->input('admin_password');

    $checklogin = DB::table('admin_login')
        ->select('admin_id','admin_email','admin_name')
        ->where([
            'admin_email' => $admin_email,
            'admin_password' => $admin_password
        ])->first();

    if (count($checklogin) > 0) {
        $request->session()->put('admin_id',$checklogin->admin_id);
        $request->session()->put('admin_name',$checklogin->admin_name);
        $request->session()->put('admin_email',$checklogin->admin_email);

        return redirect()->action('Admin_controller@webadmin');
    } else {
        return redirect()->action('Admin_controller@admin_login_page')->with('status','Incorrect Email ID or Password');
    }
}

I want the Middleware to check if the session (admin_name) exists or not. If not, redirect the user to the login page. but it is not working. if I access the webadmin (dashboard) directly from url, it gives me access even if the session is not set. Please help.

Body:
Your route is wrong, you should write it as (in L5.4):

Route::get('webadmin', 'Admin_controller@index')->middleware('usersession');

Or even:

Route::group(['middleware' => 'auth'], function(){
    Route::get('webadmin', 'Admin_controller@index');
});

In L5.3 (as you have tagged the question), and in L5.4 I guess you could also write:

Route::get('webadmin',['middleware' => 'usersession', 'uses => 'Admin_controller@index']);

Also, have you tried just to do a dd(request()); or similar in your middleware-handle function to see that it is actually fired?


问:
Re-select and upload the same file
You cannot re-select and upload the same file except in Firefox, which mistakenly allows you to do so:

```<code><input type="file" id="fileChooser">
document.getElementById('fileChooser').onchange = function () {
    alert('Uploaded!');
};
</code>```

Here's my approach to resolve the issue. I wonder if there's a neater way to achieve it.

```<code><input type="file" id="fileChooser">
var fileChooser = document.getElementById('fileChooser');
fileChooser.onclick = function () {
    this.value = '';
};
fileChooser.onchange = function () {
    if (this.value) {
        alert('Uploaded!');
    }
};
</code>```

On JSFiddle: http://jsfiddle.net/scMF6/2/

Explanation:

You cannot re-select the same file twice in a row, i.e. you select and upload foo.txt on your desktop, for example, and then click the file chooser again, file select dialog appears and you try to select the same file again -- the browser simply does nothing and no alert box appears.

答:
Thanks for idea!
If some one use GWT, then you can use this code)</p>

```<code>     ...//some code :)
     Event.setEventListener(btn, new EventListener() {
           @Override
           public void onBrowserEvent(Event event) {
           //work with IE11+ and other modern browsers
           nativeClearFile(fileUpload.getElement());
           //throw event click
           InputElement.as(fileUpload.getElement()).click();
           }
          });
    Event.sinkEvents(btn, Event.ONCLICK);
    ...//continue code :)

    private native void nativeClearFile(Element element) /*-{
        element.value = '';
    }-*/;
</code>```

Title: Re-select and upload the same file

Body:
You cannot re-select and upload the same file except in Firefox, which mistakenly allows you to do so:

<input type="file" id="fileChooser">
document.getElementById('fileChooser').onchange = function () {
    alert('Uploaded!');
};

Here's my approach to resolve the issue. I wonder if there's a neater way to achieve it.

<input type="file" id="fileChooser">
var fileChooser = document.getElementById('fileChooser');
fileChooser.onclick = function () {
    this.value = '';
};
fileChooser.onchange = function () {
    if (this.value) {
        alert('Uploaded!');
    }
};

On JSFiddle: http://jsfiddle.net/scMF6/2/

Explanation:

You cannot re-select the same file twice in a row, i.e. you select and upload foo.txt on your desktop, for example, and then click the file chooser again, file select dialog appears and you try to select the same file again -- the browser simply does nothing and no alert box appears.

Body:
Thanks for idea!
If some one use GWT, then you can use this code)

     ...//some code :)
     Event.setEventListener(btn, new EventListener() {
           @Override
           public void onBrowserEvent(Event event) {
           //work with IE11+ and other modern browsers
           nativeClearFile(fileUpload.getElement());
           //throw event click
           InputElement.as(fileUpload.getElement()).click();
           }
          });
    Event.sinkEvents(btn, Event.ONCLICK);
    ...//continue code :)

    private native void nativeClearFile(Element element) /*-{
        element.value = '';
    }-*/;


问:
Boolean variable becomes command-line option
Is there a more succinct way to do this with bash?

```<code>if [[ ${BOOL} == true ]]; then
    OPTION="--option"
else
    OPTION=
fi

command ${OPTION}
</code>```

BOOL is a string value guaranteed to be either: true or false

If true there should be an option.
If false there should be no option.

答:
You can use something like this:</p>

```<code>OPTION=[[ ${BOOL} == true ]] && "--option"
command ${OPTION}
</code>```

Body:
Is there a more succinct way to do this with bash?

if [[ ${BOOL} == true ]]; then
    OPTION="--option"
else
    OPTION=
fi

command ${OPTION}

BOOL is a string value guaranteed to be either: true or false

If true there should be an option.
If false there should be no option.

Body:
You can use something like this:

OPTION=[[ ${BOOL} == true ]] && "--option"
command ${OPTION}


问:
change default db in cakephp3
In a controller I want to change the default database so i can access the new db (db2) from anywhere in the website. The db2 database has the same models but just different data. My code just accesses the other database but doesnt set the new default database to db2 which can be accessed anywhere in the website. I didnt get the answer from the below posts.

This is my controller :

$connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured
$results = $connection->execute('SELECT * FROM tutors')->fetchAll('assoc');
//this works but doesnt set the default database to db2 everywhere
```

<p><strong>This is my app.php :</strong></p>

<pre class="lang-php prettyprint-override"><code>'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',

        //'port' => 'non_standard_port_number',
        'username' => 'root',
        'password' => '',
        'database' => 'aptutori_test',
        'encoding' => 'utf8',
        'timezone' => '+11:00',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,

        'quoteIdentifiers' => false,

        'url' => env('DATABASE_URL', null),
    ],

    'db2' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',

        //'port' => 'non_standard_port_number',
        'username' => 'root',
        'password' => '',
        'database' => 'aptutori_testbak',
        'encoding' => 'utf8',
        'timezone' => '+11:00',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,

        'quoteIdentifiers' => false,

        'url' => env('DATABASE_URL', null),
    ],
</code>```

Dynamically change database connection in cakephp 3

http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database

答:
Use ConnectionManager::alias():

http://api.cakephp.org/3.0/class-Cake.Datasource.ConnectionManager.html#_alias

Fore example this will make all tables that require the default connection to use db2:

```<code>ConnectionManager::alias('db2', 'default');
</code>```

Title: change default db in cakephp3

Body:
In a controller I want to change the default database so i can access the new db (db2) from anywhere in the website. The db2 database has the same models but just different data. My code just accesses the other database but doesnt set the new default database to db2 which can be accessed anywhere in the website. I didnt get the answer from the below posts.

This is my controller :

$connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured
$results = $connection->execute('SELECT * FROM tutors')->fetchAll('assoc');
//this works but doesnt set the default database to db2 everywhere

This is my app.php :

'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',

        //'port' => 'non_standard_port_number',
        'username' => 'root',
        'password' => '',
        'database' => 'aptutori_test',
        'encoding' => 'utf8',
        'timezone' => '+11:00',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,

        'quoteIdentifiers' => false,

        'url' => env('DATABASE_URL', null),
    ],

    'db2' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',

        //'port' => 'non_standard_port_number',
        'username' => 'root',
        'password' => '',
        'database' => 'aptutori_testbak',
        'encoding' => 'utf8',
        'timezone' => '+11:00',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,

        'quoteIdentifiers' => false,

        'url' => env('DATABASE_URL', null),
    ],

Dynamically change database connection in cakephp 3

http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database

Body:
Use ConnectionManager::alias():

http://api.cakephp.org/3.0/class-Cake.Datasource.ConnectionManager.html#_alias

Fore example this will make all tables that require the default connection to use db2:

ConnectionManager::alias('db2', 'default');


问:
Console Application as continuous Azure webjob does not convert Time.ToUniversalTime() in UTC
I have a simple console application running as continuous webjob in Azure, Locally when I debug it gives proper output time in UTC when I convert time using
    new DateTime(Time).ToUniversalTime()
but when I run it in webjob it still gives local time instead of universal time.

Console.WriteLine(MyData.Time.ToUniversalTime() + " "+ DateTime.Now.ToUniversalTime());

at 3:43 PM PST

Kudu console (webjob): 6/7/2017 3:38:46 PM 6/7/2017 10:43:52 PM

on local Console: 6/7/2017 10:38:46 PM 6/7/2017 10:43:52 PM

答:
Tried this Console.WriteLine(new DateTime(2017, 05, 23, 8, 00, 00, 0).ToUniversalTime() + " "+ DateTime.Now.ToUniversalTime()); Even this does not give expected result on Kudu Console, on Kudu Console: 5/23/2017 8:00:00 AM 6/7/2017 11:04:23 PM on Local Console: 5/23/2017 3:00:00 PM 6/7/2017 11:04:23 PM

The differences between your local and Azure Web App instance is that the default time zone in Azure Web App instances is UTC. According the result of your test, the time zone on your local is UTC+07:00. If you create a new instance of DateTime by year/month/day/hour/month/minute, it will use the default time zone of your system.

It is not recommended to save a datetime to a string with this format 'year/month/day/hour/month/minute'. It will lose the time zone information.  If your code runs on a machine with different time zone, it will cause some issues.

If you did need to store the datetime information in a string, you could store the datetime information with a time zone symbol(ex. 2017, 05, 23, 8, 00, 00, 00 UTC+07:00). To get the datetime back from the string, we need to add the offset hours.

```<code>var dateTime = new DateTime(2017, 05, 23, 8, 00, 00, 0, DateTimeKind.Utc).AddHours(7);
</code>```

Or you could convert datetime to GMC time before save it. After that, you could create a new instance of DateTime with a DateTimeKind parameter.

```<code>var dateTime = new DateTime(2017, 05, 23, 8, 00, 00, 0, DateTimeKind.Utc);
</code>```

Body:
Tried this Console.WriteLine(new DateTime(2017, 05, 23, 8, 00, 00, 0).ToUniversalTime() + " "+ DateTime.Now.ToUniversalTime()); Even this does not give expected result on Kudu Console, on Kudu Console: 5/23/2017 8:00:00 AM 6/7/2017 11:04:23 PM on Local Console: 5/23/2017 3:00:00 PM 6/7/2017 11:04:23 PM

The differences between your local and Azure Web App instance is that the default time zone in Azure Web App instances is UTC. According the result of your test, the time zone on your local is UTC+07:00. If you create a new instance of DateTime by year/month/day/hour/month/minute, it will use the default time zone of your system.

It is not recommended to save a datetime to a string with this format 'year/month/day/hour/month/minute'. It will lose the time zone information.  If your code runs on a machine with different time zone, it will cause some issues.

If you did need to store the datetime information in a string, you could store the datetime information with a time zone symbol(ex. 2017, 05, 23, 8, 00, 00, 00 UTC+07:00). To get the datetime back from the string, we need to add the offset hours.

var dateTime = new DateTime(2017, 05, 23, 8, 00, 00, 0, DateTimeKind.Utc).AddHours(7);

Or you could convert datetime to GMC time before save it. After that, you could create a new instance of DateTime with a DateTimeKind parameter.

var dateTime = new DateTime(2017, 05, 23, 8, 00, 00, 0, DateTimeKind.Utc);


问:
How can i update two slice with same silde in nrrd loader
I am new to Javascript and NRRD Loader, in nrrd loader we can change the index value of a slice using the slider

sliceY = volume.extractSlice('y', Math.floor(volume.RASDimensions[1]/2));
scene3.add(sliceY.mesh);

gui.add(sliceY, 'index', 0, volume.RASDimensions[1], 1).name('indexY').onChange(function () {
  sliceY.repaint.call(sliceY);
});
```

<p>Consider I need update value of slicesX at same time with the same slider</p>

<pre class="lang-js prettyprint-override"><code>sliceX = volume.extractSlice('x', Math.floor(volume.RASDimensions[1]/2));
</code>```

答:
I used slider.js Javascript  which helped me to move the two slices using the same slider</p>

```<code>$( function() {
                  $( "#sliderx" ).slider({
                    min: 0,
                    max: volumeslicex,
                    step: 1,

                    stop: function( event, ui ) {
                        // planexy.material.color.setHex( 0x8d8d8d );
                        // preset = "NULL";
                    },

                    slide: function( event, ui ) {

                      indexX=ui.value;
                      scene1.remove( sliceX.mesh );
                      scene.remove( sliceX1.mesh );
                      sliceChange();

                    }
                  });
                } );
                    function sliceChange(){
                    //alert(indexX);
                    sliceX = volume.extractSlice('x',Math.floor(indexX));
                    sliceX1 = volume.extractSlice('x',Math.floor(indexX));
                    scene1.add( sliceX.mesh );
                    scene.add( sliceX1.mesh );
                    };
</code>```

Body:
I am new to Javascript and NRRD Loader, in nrrd loader we can change the index value of a slice using the slider

sliceY = volume.extractSlice('y', Math.floor(volume.RASDimensions[1]/2));
scene3.add(sliceY.mesh);

gui.add(sliceY, 'index', 0, volume.RASDimensions[1], 1).name('indexY').onChange(function () {
  sliceY.repaint.call(sliceY);
});

Consider I need update value of slicesX at same time with the same slider

sliceX = volume.extractSlice('x', Math.floor(volume.RASDimensions[1]/2));

Body:
I used slider.js Javascript  which helped me to move the two slices using the same slider

$( function() {
                  $( "#sliderx" ).slider({
                    min: 0,
                    max: volumeslicex,
                    step: 1,

                    stop: function( event, ui ) {
                        // planexy.material.color.setHex( 0x8d8d8d );
                        // preset = "NULL";
                    },

                    slide: function( event, ui ) {

                      indexX=ui.value;
                      scene1.remove( sliceX.mesh );
                      scene.remove( sliceX1.mesh );
                      sliceChange();

                    }
                  });
                } );
                    function sliceChange(){
                    //alert(indexX);
                    sliceX = volume.extractSlice('x',Math.floor(indexX));
                    sliceX1 = volume.extractSlice('x',Math.floor(indexX));
                    scene1.add( sliceX.mesh );
                    scene.add( sliceX1.mesh );
                    };