Does destiny affect the type of loot you get in Kingdoms of Amalur?

Question: Does destiny change the loot you get?  If you take sorcery destiny will that make it so most items you get in the game world are weapons/armors mages use, or if you choose finesse destiny would it make it so that you mostly get finesse weapons/armors?
I am playing as pure warrior at the moment and most items I find in chests or dead bodies are warrior weapons (Greatswords,Longswords,Hammers) and warrior armors.  I do get items for other "classes" but not as much/often as warrior items.
Comment: My experience suggests no relation whatsoever - as purely sorcery, I've found more great set might and finesse items than I can shake a stick at (and only two set sorcery items). I sell/salvage all of it, but I definitely find more non-sorcery than sorcery.
Answer: No, not from my experience.  The loot drops appear to be random, and not impacted by your choice of skills or destiny.  I have no points in Might, yet I find heavy armor, swords, and hammers with alarming regularity.
I ran a test with my "current" destiny, which is Finesse/Sorcery, and before filling my inventory I found:

9 Sorcery items
11 Might items
14 Finesse items

(along with other assorted junk)
I then changed my Destiny to the default level 1 Might destiny, and went forth and looted again, and I came away with:

7 Sorcery items
10 Might items
8 Finesse items

If destiny played a significant role in determining loot drops, I'd expect to see a much larger bias towards Sorcery/Finesse in the first category, and Might in the second.  As it was, I found roughly similar amounts of items from each category, regardless of my destiny.  This is not an exhaustive test, and probably a much larger sample size could be taken, but I think this is at least somewhat representative of a random loot drop system.
Do note that even if you have a weapon or piece of armor that you can't use due to your skill choices, you can still break it down at a blacksmith workbench to recover components you can use to build armor or weapons for your chosen skill tree.  Not all components will be reusable in other items, but more often than not you'll find something you can use.
Also, since you can respec at any time, if you find something overpowered that's not for your chosen class, you can stick it in your stash in case you decide to re-roll later.
Comment: @ChrisHateZ, I gathered some empirical data and added it to my answer.  I don't see a statistically significant difference in the type of loot I find depending on my destiny over a sample size of about 60 "attribute point dependent" items.  You can feel free to run a larger sample size if you so desire, I'd be interested to see the results.
Comment: @ChrisHateZ, or I could just be ridiculously unlucky :)  That's kind of the problem with a potentially random sequence - you can't really tell whether or not what you're getting is truly random without a gigantic sample size.
Comment: I just made a new character and I'm playing as a rogue now,and i have to say i keep getting rogue weapons and armors non-stop and almost nothing else,just like i was getting warrior items most of the time when i was playing warrior.This makes me doubt in your answer,because from my experience it seems that destiny really does affect the loot you get.
Comment: I guess i am just ridiculously lucky because i tend to get just the gear for the class i need on both warrior and rogue.I might do a test by making more characters later and having them use different destiny.I also have a friend who mostly gets items for his class on both of his characters (he haves mage and rogue) so that is interesting as we both seem to get same results,which really makes me wonder are we both just lucky or what.I think the only way of finding out the truth would be to ask game developers thought.
Answer: i dont believe this is the case, on my char that has never been specced into anything else then finesse (and only finese destiny cards) i keep finding lots of epic might weapons and lots of those magic boomerang things, while i have only found 1 epic feablade's (@ low level)
Comment: Ouch,you're really not lucky then.I made new character like 2 days ago (playing him as pure finesse) and most of the purple and gold items i got so far were for finesse and only few of them for might/sorcery.I guess it's not destiny that changes the loot after all,it's just my awesome luck.


How to log django performance statistics on production server?

Question: I'm looking for something that will get me the same info as I got via Django debug Toolbar, but in form of log file rather than template overlay. It must be is safe to run  in production environment. I'm most concerned about cpu time and number/time of database query's.
What would you recommend?
Answer: If your focus is indeed lower down on the stack (e.g. queries, CPU load, memory) and you don't Django specific stats, then munin is a good candidate.


Detect Returning User in a Rails3 + Devise application

Question: I'm looking for a solution, to reach the desired behaviour.
Running a Rails3 application where authentication is handle by Devise. I want to detect any user coming back to the site while already signed in (with the remember_me cookie).
My aim is to redirect him to a specific page (as I already do it on after_sign_in_path_for).
My very problem is not to detect if a user is signed_in?, but to be sure he wasn't navigating on the site just tow minutes before (I prefer to avoid strategy based an time...)
Any guess ?
Comment: Not at all clear to me what you are wanting here.  You want to detect if a user has been signed in recently, but don't want to do it based on time?  This doesn't make sense ...
Comment: Sorry if I was unclear, I wanted to detect if a user signed in based on the remember_me cookie is returning to the site. But I found a good solution based on the rails session cookie (see the edit of my question). thx anyway
Answer: My own answer, to my question...
I posted the question too quickly.
The solution is quite simple, Rails create a session cookie after each request, we just need to check if it exists or not :
def user_returning?
  user_signed_in? && session[:session_id].blank?
end

I was mixing Devise session wich can subsiste between browser closings, and session cookie which are destroyed after each browser closing.
user_returning? allow me to know if a user is coming back to the site, while he is already signed in...


Upconverting older consoles' output for HDTVs

Question: Is it possible?  I still like retro gaming on my PSX/PS2 when I have time, but all TVs are HD now and the AVI looks like a mess, and even output from the 480p component cables look really grainy and not as smooth as they used to.  Is there such thing as a device out there which will smooth out the quality and make it look at least as good on an HDTV as it did on the old tube TVs of the past?
Comment: To the downvoters: We encourage users to leave a comment when downvoting so that the OP knows how to improve their question. When down votes are left without comments and the reasons for doing so are unclear, you'll often see users (like myself) wanting to know the reason why.
Comment: Video game console emulators in the PC have [image scaling](https://en.wikipedia.org/wiki/Image_scaling) features that work like you described. I'm just not sure if there are hardware or software that you could use to make it work with your PS2 and HDTV.
Comment: +1.  Great question, inspite of the downvote.  And, yes, there certainly is hardware for this.  It just depends on the desired effect.  See my answer.
Answer: There are some modern TVs that will emulate certain features of tube TVs, and there are other ways of upconverting. Playing your older games on a (compatible) PS3, can naturally upconvert them to a higher resolution, the (compatible) PS3 has various settings to make playing the older games work in various ways.
Comment: Good to know that some TVs have this feature, though when you try to ask about it at any local retail place they just look at me like I'm the dumbest person on earth for suggesting such a thing.  I do play Playstation 1 games on my PS3, but it would be nice to enjoy my ps2/gamecube/n64 games with this same upconversion.  My PS3 is not one of the backwards compatible models so I can't play PS2 that way.  I hope the technology is more common too.  Do you know of any specific modern TVs that will emulate a tube TV to accomplish what I am looking for?
Comment: I didn't know about that (never owned a PS3.)  Is it some form of built-in pixel-level filtering?  Awesome!
Answer: At the center of my heart I am an avid retro-gamer.  About 6 months ago I decided that I wanted to work on a game that had a real "8-bit" feel to it and I wanted it to look more than being just a blocky-looking game.  It had to feel like you were playing on an old, gaming system and playing on an CRT television.
In short, what you want to see are the effects of the scanlines that show up on your television.  I'll spare all of the technical details but the bottom line is that old, analog televisions display information on old TV screens in a much different manner than current Plasmas, LCD, LEDs and anything else that will ever come along.
Not to worry, though!  There is hardware out there (called a scan converter) that takes these old channels, converts them to digital and then applies appropriate filters to the HDMI output so that it looks and feels a much like ye olde skool, CRT output of yore.
I really want one of these devices but they are pretty intense.  You might be able to find a cheap box for under $100 but the really top-notch converters can cost more than $500.
Scanlines Demistified is the original source that I found when looking for a converter.  I've not looked much further than this source because, all though I want a converter for all of my systems, I need to save up to get one of the nicer $300+ units.
Comment: If and when you do decide to take the plunge, I'd love to speak further with you about this.  I don't understand the details enough to be sure of what I am getting but based on what you've said, 300 dollars seems completely reasonable if it really does restore the viability of playing these older consoles on newer TVs.
Comment: @Kyle. It really depends on what you want.  If you want to play Super Mario Bros. 3 or Final Fantasy III (US), so that it looks and feels like it originally did, then this is the way to go.  That, or just by an old boxy TV.  Do you spend $3-400 on an expensive converter or just keep an old 21" around.  I, personally, have kept  a 23" in my spare bedroom for this very reason.  In fact, my wife has begged me to toss "that piece of junk".  Lol... but I just can't do it since you can't get the same affect on an HDTV without expensive equipment.
Answer: Not possible since those games weren't made to take advantage of HDTVs. Although God of War II can go up to 720i. If you have an old tube TV or can get one. It will be the only way to play the games. I've been thinking of finding an old tube TV to play N64 and Wii games on.
Comment: He's looking for something that will blur the pixels, not something that will make it true 1080p.
Comment: No, it's possible. Some TVs have it built in.
Comment: Knowing that it's not impossible doesn't mean I know of an inline device or HD receiver model that can do it. Logic, it do not work that way.
Comment: @SevenSidedDie My bad. Still not possible.
Comment: Post the answer, son.
Comment: My bad. I meant no disrespect.
Comment: If you find one please let me know!  Thanks Seven.


How to get events of type by reflection ignoring events on parent interfaces

Question: I have the following code
Type type = ...
var events=type.GetEvents(
    BindingFlags.DeclaredOnly
    | BindingFlags.Instance
    | BindingFlags.Public).ToList();

However this is also returning me events declared on
parent interfaces. For example
Both
UIElement
ContentElement

implement
IInputElement

which defines the event
//
// Summary:
//     Occurs when the mouse pointer moves while the mouse pointer is over the element.
event MouseEventHandler PreviewMouseMove;

but the above call to GetEvents with all the binding flags set as above
returns the event for the interface as well as the two concrete classes.
How can I filter out events that are defined on parent interfaces from
GetEvents?
Note that I am generating extensions methods for each event like so
public static
IObservable<EventPattern<MouseButtonEventArgs>>
PreviewMouseLeftButtonDownObserver(this IInputElement This){
        return Observable
               .FromEventPattern
               <MouseButtonEventHandler, MouseButtonEventArgs>
               ( h => This.PreviewMouseLeftButtonDown += h
               , h => This.PreviewMouseLeftButtonDown -= h);
}

so I only did the root definition of the event not derived virtual or interface implementations.
Comment: What type is returned as you execute `someObject.GetType()`? If it is a concrete class all the events are going to be returned, as they are explicitly implemented. Try to infer the interface you'd like to get and call `GetType()` on the `interface`, not the concrete class.
Comment: Is `type` an interface, or is it a class/struct which implements some interfaces?
Comment: I'm processing all the types in an assembly and for each type extracting the events for code generation purposes. I only want the events declared explicitly on each type or interface not inherited. I'm generating f# style event observables for the whole WPF library bit I end up with redundant code if I generate for both the interface and the concrete class.
Comment: FYI the complete T4 template is here https://gist.github.com/bradphelan/5343651
Answer: In the example:
interface IFace
{
    event EventHandler A;
}

class Base
{
    public virtual event EventHandler B;

    public event EventHandler C;
}

class YourType : Base, IFace
{
    public event EventHandler A;          // implements interface

    public override event EventHandler B; // overrides base class implementation

    public event EventHandler D;          // new event
}

which event do you want to see if you use reflection on typeof(YourType)?
ANSWER:
You can use something like:
events.Where(x =>
  x.GetAddMethod().GetBaseDefinition().DeclaringType == type
  && !x.GetAddMethod().IsFinal)
  );

where type is like in your question. The first criterion makes sure it is not an event defined on a parent type. The second criterion makes sure it's not an interface implementation. You might not need the second criterion, depending on your exact setup.
EDIT to ANSWER
events.Where(x =>{
   var addMethod = x.GetAddMethod();
   var basetype = addMethod.GetBaseDefinition().DeclaringType;
   return basetype == type && (!addMethod.IsFinal || basetype.IsInterface);
})

This addition ensures that I get the interfaces as well.
ALTERNATIVE APPROACH:
To definitely determine if a member implements some interface or not, one can use this:
var interfaceImplementingMethods = new HashSet<MethodInfo>(type.GetInterfaces()
  .SelectMany(i => type.GetInterfaceMap(i).TargetMethods));
var result = events.Where(x => !interfaceImplementingMethods
  .Contains(x.GetAddMethod()));

It should work even if the implementing member is declared virtual (or abstract). This must be combined with GetBaseDefinition() if you want to exclude also inherited members, of course.
Comment: Only D is required as I wish only to generate extension methods via t4 for the parent classes implementation.
Comment: See the edit I made to the question with an example of the type of code I'm generating.
Comment: @bradgonesurfing My example `YourType` contains four events, `A`, `B`, `C`, and `D`. I believe the `DeclaredOnly` binding flag only excludes `C`. The other events have implementations in `YourType`.
Comment: Yes that is correct. Just using BindingFlags.DeclaredOnly is not enough. The question is how to achieve what I need?
Comment: @bradgonesurfing Thanks for editing my answer. There's probably still an issue when a clss implements an event from an interface and uses the `virtual` (or `abstract`) keyword on the event.
Comment: probably rare enough that I can skip it for code gen purposes. I've also skipped generic events as well.
Answer: You could try to filter out the events of the interface using linq, like this...
Type type = typeof (Bar);
Type interfaceType = typeof (IFoo);
var interfaceEvents = interfaceType.GetEvents(BindingFlags.DeclaredOnly
                                              | BindingFlags.Instance
                                              | BindingFlags.Public);

var events = type.GetEvents(BindingFlags.DeclaredOnly
                            | BindingFlags.Instance
                            | BindingFlags.Public);

events = events.Where(e => interfaceEvents.FirstOrDefault(
                ie => ie.Name == e.Name &&
                ie.EventHandlerType == e.EventHandlerType) == null).ToArray();

Edit:
Events from base classes should not be included in the result from GetEvents method. Here is a method that removes the events of all interfaces the type implements.
Edit 2:
This method will also remove overridden base class events:
public IEnumerable<EventInfo> GetEventsEx(Type type)
{
    var baseEvents = new List<EventInfo>();

    // Adds Events of interfaces to baseEvents
    foreach (var interfaceType in type.GetInterfaces())
    {
        baseEvents.AddRange(interfaceType.GetEvents(
            BindingFlags.DeclaredOnly
            | BindingFlags.Instance
            | BindingFlags.Public));
    }

    // Adds Events of base classes to baseEvents
    var baseType = type.BaseType;
    while (baseType != typeof (object))
    {
        baseEvents.AddRange(baseType.GetEvents(
            BindingFlags.DeclaredOnly
            | BindingFlags.Instance
            | BindingFlags.Public));
        baseType = baseType.BaseType;
    }

    // Get events for type
    var events = type.GetEvents(
        BindingFlags.DeclaredOnly
        | BindingFlags.Instance
        | BindingFlags.Public);

    // Remove baseEvents and return
    return events.Where(e => baseEvents.FirstOrDefault(
            ie => ie.Name == e.Name &&
            ie.EventHandlerType == e.EventHandlerType) == null);
}

Edit 3:
New method with the BindingFlags.DeclaredOnly flags removed, this will probably work a little better:
public IEnumerable<EventInfo> GetEventsEx(Type type)
{
    var baseEvents = new List<EventInfo>();

    // Adds Events of interfaces to baseEvents
    foreach (var interfaceType in type.GetInterfaces())
    {
        baseEvents.AddRange(interfaceType.GetEvents(
            BindingFlags.Instance
            | BindingFlags.Public));
    }

    // Adds Events of base classes to baseEvents
    var baseType = type.BaseType;
    if (baseType != null && baseType != typeof (object))
    {
        baseEvents.AddRange(baseType.GetEvents(
            BindingFlags.Instance
            | BindingFlags.Public));
    }

    // Get events for type
    var events = type.GetEvents(
        BindingFlags.DeclaredOnly
        | BindingFlags.Instance
        | BindingFlags.Public);

    // Remove baseEvents and return
    return events.Where(e => baseEvents.FirstOrDefault(
            ie => ie.Name == e.Name &&
            ie.EventHandlerType == e.EventHandlerType) == null);
}

Comment: This is a start. But instead of a single interface I want to ignore any events declared on parent classes or interfaces of Bar.
Comment: @bradgonesurfing, I have update my answer. To reflect on your input.
Comment: Cool. I think that you should remove the ``BindingFlags.DeclaredOnly`` from the ``Adds Events of base classes to baseEvents`` otherwise you would need to modify the code to be recursive and note that interfaces can implement other interfaces so you might want to drop the ``BindingFlags.DeclaredOnly`` in the first loop as well.
Comment: It is easier to check `GetBaseDefinition`. See my edited answer.
Comment: @bradgonesurfing, Thanks, the base classes loop is recursive but your right I removed `BindingFlags.DeclaredOnly` and created a new method.
Comment: @JensGranlund good work. However I've just looked at the other answer that Jeppe made and it's pretty short and sweet and if it works is the one I'll go for. Thanks for the work however :)
Comment: @bradgonesurfing, I like his answer better too.


Delete data from destination tables before running copy data activity

Question: I am trying to create a pipeline that moves data between some Oracle databases. I have successfully created and tested the copy data activities. My problem is I want to empty the destination tables before the "copy" runs and I can't see a way to do that (right now it appends data to the tables).
At first I tried using the Stored Procedure activity, but that only supports SQL Server-related sources. None of the other activities offered by data factory work for this use case. Even a generic "execute SQL" activity could work for me, but nothing like that appears to be available.
EDIT: I have posted an answer below, but it's not ideal. Please post an answer if you think you have a better solution!
Answer: I use "TRUNCATE TABLE xxx" in pre-copy script. (Truncate is faster than Delete)
Also, to your point, there is no "Execute SQL task", but as a hack, we can use a "Lookup" activity to execute ad-hoc scripts. Link to one of my previous answers on the same : https://stackoverflow.com/a/59422740/2993606
Comment: This works, thank you. I would still rather have a generic "Execute SQL" activity, but that's up to Microsoft.
Comment: Thanks, this could be promising. I'll try this tomorrow and if it works for my use case I'll upvote you and give you the bounty.
Answer: I have found a slightly hacky solution. There is a configuration in the Sink part of the Copy Data activity called Pre-copy script. The documentation says to use it for manipulating the incoming data so I thought it would only work on the incoming data, but it's actually SQL that's executed on the target database (seemingly in a transaction, which is committed)
So basically, this works:

I'm not a huge fan of this solution, because it's hard to configure the flow. I would have preferred a separate activity so I could prepare success/failure options, while with this, the whole "Copy Data" activity will fail. Please post an answer if you have a better idea!
Answer: I have always used a Stored Procedure to clear table data as part of my pipelines. I do this because I usually have a specific where clause for the data [that typically lines up with a table partition] rather than truncating the entire table.
As an alternative to the Copy activity, you can use a Data Flow (ADFDF) activity. ADFDF Sink settings show you can truncate the table:

This screenshot is for a SQLDW Sink, so I don't know if the ADFDF Sink for Oracle permits this or not.
Comment: It does not. I mention this in my question, "Stored Procedure" activity is not supported for Oracle Database linked service.
Comment: Sorry if my post was not clear - my screen shot was NOT for stored procedure, or Copy activity, but for using a Data Flow activity. Post edited for clarity.
Comment: The answer of @SouravA works for my use case. But I'll take a look at this too, thanks for your effort.
Comment: No problem - I would have suggested the same as he did, but you had said the pre-script was not ideal so I wanted to give you an alternative :-)
Comment: My problem with the "Pre copy script" was that it was not a separate activity, and I wanted to check its success/failuler separately. For example, if the "pre copy" failed, that would make the whole "Copy Data" activity fail, and I didn't want that. Using the "Lookup" is I suppose equally hacky, but at least I can handle its failure separately.


How to control Div properties through JavaScript

Question: I have to work with a web design application that uses absolute positioning, I need to create a way in which the font size for say the paragraph can be increased for accessibility purposes. I can figure this bit out, but the part I am lost at is trying to understand how to change the properties (height, padding, margins) of the Divs so the text fits and the Divs do not overlap each other. I can set height to auto, but I can't figure out how to prevent the two Div from maintain space between each other, and how I could apply this to other objects like images.
Any help would be great.
Edit: I have added a screenshot below with two basic div both the same except the bottom one has a top-margin of 15% applied, which works for large fonts but breakdown for smaller fonts.
Comment: I haven't attached code as I haven;t written any because I don't understand the logic, it's that logic that I am asking about.
Comment: @Prashant but if the width of the first div is 500px setting the margin-left of the second div (assuming they are side by side) will make the margin-left 500px and the gap between the two large?
Comment: @prashant i tried using % but that didn't work when you reduce the size of the font the gap is too large, as % relates to the width of the containing Div rather than the two divs (i.e. the page width of 980px)
Comment: @prashant The whole point is to be able to change the font size programmatically and maintain the layout in an absolute position environment.
Comment: Hey you can remove position:absolute; because this is the one that is the cause of overlapping then you can use width:auto; & now you can give margin-top to second div to maintain them on a fixed distance..
Answer: If you place every element inside div tags, they will be considered as block-tags, and should not overlap each other. Then you can use javascript to change their attributes.
If you encounter some problem, maybe you could post it here with some screen, and some HTML/CSS code so we can help you more precisely.
Answer: Set the height of the divs to auto in CSS. You can then access the divs' height and position with .offsetHeight and .offsetTop respectively, and adjust their positions every time you change the font size. Something like:
function adjust () {
    var divs = document.getElementsByTagName("div");
    for (var i = 1; i < divs.length; i++)
        divs[i].style.top = divs[i - 1].offsetHeight + divs[i - 1].offsetTop + "px";
}

http://jsfiddle.net/megapop/judyc/3/


Dynamically create javascript object

Question: I have below code in which i need to create a dynamic object
let response = {};
const process = (key, value) => {
if (key == FieldMapping[key]) {
    response = {
        ...response,
        key : value
    }
    console.log(key + " : " + value);
}
}

In the above code, i want to pass key as property of new object and value as value and keep all the previous added property and its value but it's not persisting the previously added property. Also FieldMapping[key] : value is giving compilation error .What's wrong here?
Comment: `response = { ...response, [key]: value}`
Comment: What is `FieldMapping` here and what values have you passed when calling the `process` function?
Comment: var new_obj={}; new_obj[key]=value
Comment: @connexo That is syntax error, isn't it?
Answer: You current code will keep creating/overwriting a key property. What you instead want is a property with the name of the string contained in key. You achieve this using the bracket property notation:
response = { ...response, [key]: value}

See it work:

const key = 'foo', value = 'bar';
let response = { baz: true };
response = { ...response, [key]: value };
console.log(response);
Answer: You should use response object:
response = {...response}

response[key] = value

FieldMapping[key] : value should be FieldMapping[key] = value

Dynamically create javascript object


typed `apt-get update` now showing a long list of EDAC errors. Is there anything wrong?

Question: I typed apt-get update and then I saw a long list of
EDAC i7Core: Lost 127 memory errors
Please help me understand what has happened.
I am using ubuntu server edition 12.04 LTS
UPDATE:
I followed Gilles answer. I got the following when I do a dmesg
[113893.215234] EDAC MC0: CE error on CPU#0Channel#1_DIMM#0 (channel:1 slot:0 page:0x0 offset:0x0 grain:8 syndrome:0x0)
[113893.215237] EDAC MC0: CE error on CPU#0Channel#1_DIMM#0 (channel:1 slot:0 page:0x0 offset:0x0 grain:8 syndrome:0x0)
[113893.215240] EDAC MC0: CE error on CPU#0Channel#1_DIMM#0 (channel:1 slot:0 page:0x0 offset:0x0 grain:8 syndrome:0x0)
[113893.215243] EDAC MC0: CE error on CPU#0Channel#1_DIMM#0 (channel:1 slot:0 page:0x0 offset:0x0 grain:8 syndrome:0x0)
[113893.215246] EDAC MC0: CE error on CPU#0Channel#1_DIMM#0 (channel:1 slot:0 page:0x0 offset:0x0 grain:8 syndrome:0x0)
[113893.215248] EDAC MC0: CE error on CPU#0Channel#1_DIMM#0 (channel:1 slot:0 page:0x0 offset:0x0 grain:8 syndrome:0x0)
[113893.215251] EDAC MC0: CE error on CPU#0Channel#1_DIMM#0 (channel:1 slot:0 page:0x0 offset:0x0 grain:8 syndrome:0x0)

Answer: EDAC is the kernel component that watches for memory errors. You get a message about lost memory errors when so many errors occurred in a short interval that the kernel was unable to log them all.
A memory error is a bad thing. Check your kernel logs (/var/log/kern.log) for messages like this:
EDAC MC0: CE page 0x283, offset 0xce0, grain 8, syndrome 0x6ec3, row 0, channel 1 "DIMM_B1": amd76x_edac

CE indicates an error that was corrected. If your RAM has error correction, it's ok to have a corrected error now and then. But when you get to the point where memory errors get lost due to their number, it's high time to replace your RAM. The message indicates which RAM module (DIMM) is faulty.
If you see UE instead of CE, it means that an error was detected but not corrected. You may have corrupt data.
If your RAM and CPU don't support error correction, then the first sign you'll get that your RAM is defective is when you realize that your data is corrupted.
This is completely unrelated to apt-get update, that's just the command you happened to be executing when the errors happened.
Replace your RAM yesterday.
Comment: @kimsia Most CPUs aren't able to report memory corruption to the OS, hence usually you need to run memtest to diagnose potential memory corruption. Since your CPU has been able to report the errors to Linux, you don't need to run memtest. CE are corrected errors, but when you have that many corrected errors, there's a probability that some errors are going uncorrected. Replace the RAM module on channel 1 slot 0.
Comment: the kern.log is now 500Mb large. It is slow to open. From the first few lines, it appears to be CE errors. I was advised by people in the #ubuntu-server channel to do a memtest. What is the easiest way to do memtest? Googling shows I need a CD-rom or flash drive. I have never done it before. Advice?
Comment: @kimsia You don't need a CD, Ubuntu installs memtest on your system. [Make sure that your Grub menu can appear](http://askubuntu.com/questions/71867/grub-menu-doesnt-appear-when-pressing-shift), then press and hold `Shift` while booting. When the Grub menu appears, select memtest.
Comment: I have never done this before, so I was hoping for a simple screen walkthrough. I googled youtube but most of them seem to be for windows. Does it apply to ubuntu server? http://www.youtube.com/results?search_query=memtest86+ubuntu
Comment: I have updated my question with the latest from my dmesg. I guess it is time to replace the RAM yes? Or do I still bother with the memtest?
Comment: Got it, @Gilles. I am going to mark your answer as correct. You are fantastic!


How do I resize elements in the graphical version of XML?

Question: This is going to seem like such a stupid question but I am trying to resize an image I added to the graphical layout of my XML file. I can drag it around but it won't let me resize it.
What am I missing?
Thanks
Comment: I personally suggest avoid using the designer, it will make your layout display differently on different phone sizes, always use xml to manually write your layout to be sure what exactly is happening, eclipse designer is not the best
Comment: Thanks, I'm still new to eclipse and thought it was odd I couldn't resize. Will keep this in mind
Comment: you can switch to the xml of your layout and can set android:layout_width and android:layout_height to your likings
Answer: If you are unable to resize in graphical layout then you can resize in XML file.
You can use Height, Width and Weight parameters to resize..
Remove Wrap_content kind or words and provide values like 50dip
hope this helps.
Comment: yeah this one is prefered


How can i change x in print("",end=x) at end of loop?

Question: I have a bit of code that looks like this:
for num in [1,2,3,4,5]:
    print(num, end=",")
x="I want this on a new line"
print(x)

The output is this:
1,2,3,4,5,I want this on new line

How can get x onto a new line without a comma in the most pythonic way?
Answer: Don't use print one-by-one if you can; just join and print all your values at once, which avoids the trailing comma and adds one and only one desired newline:
print(','.join(map(str, [1,2,3,4,5])))  # map to str needed because join requires strs

or similarly, unpack all the arguments as sequential arguments to a single print with a sep argument, without tweaking end:
print(*[1,2,3,4,5], sep=',')  # No conversion needed, print stringifies anything

Answer: Here's one alternative :
x = ','
for num in [1,2,3,4,5]:
    if num == 5 :
        x = '\nI want this on a new line'
    print(num, end= x)

Comment: Rather than test every time, if you needed the individual `print`s, I'd be inclined to loop over all but the last element (e.g. `for num in allnums[:-1]: print(num, end=',')`), then print the last value outside the loop `if allnums: print(allnum[-1])`, then print the unrelated data. Avoids a test per loop where the result of the test is always known in advance.


How to give my mailid in my code itself for sending mail

Question: This is my code and i need to send mail!! Everything is working fine but i need my mailid to be given by default in the "to" field itself..instead getting from the user? Iam new to android plz help!!
      package com.example.newactivity;
      import android.app.Activity;
      import android.content.Intent;
      import android.os.Bundle;

       public class Revert extends Activity {
     String anu;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    String message = "Our Valuable Feedback";

    Intent emailintent = new Intent(android.content.Intent.ACTION_SEND);
    emailintent.putExtra(android.content.Intent.EXTRA_EMAIL,
            "firstname.lastname@example.com");

    emailintent.putExtra(android.content.Intent.EXTRA_SUBJECT, "i hate u");
    emailintent.setType("plain/text");
    emailintent.putExtra(android.content.Intent.EXTRA_SUBJECT, message);
    startActivity(emailintent);
}

}
Comment: what do you mean by this statement .... my mailid to be given by default in the "to" field itself ??
Comment: I dont want the user to enter his mail id! i need the user to send it to me only!!
Answer: This is the way to add recipient mail in the intent to send mail
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"email@example.com"});

body of mail
i.putExtra(Intent.EXTRA_TEXT   , "body of email");

Comment: Fine!! similarly can u tel me how to add contents in the body plz?
Comment: welcome.. remove your mail_id in the question ..just make it as  dummy mail id .. don't share your personal id's like this :)
Comment: Instead of {"email@example.com"} im supposed to give my mail id ?
Comment: just give your mail id instead of "firstname.lastname@example.com" in code. it will send mail to that mail


Syntax for Stored Procedure Parameter

Question: I have a value which I am trying to add as a parameter to a stored procedure.
The value of this parameter could either be a STRING of "1" or "NULL"
If it's NULL then I want to add the parameter of DBNull.Value
If it's "1" I want to add the parameter of 1 (int)
I have tried numerous combinations of syntax but cannot get it right.
This is what I have:
cmd.Parameters.Add(new SqlParameter("@LinkClickedId", (insertValuesSplit[12] == "NULL") ? Convert.ToInt16(insertValuesSplit[12]) : DBNull.Value));

But I have a syntax error of

Type of conditional expression cannot be determined because there is no implicit conversion between 'short' and 'System.DBNull'
  Can anyone suggest what the syntax should be please?
Comment: Have you ever read the documentation of [`?:` operator](https://msdn.microsoft.com/en-us/library/ty67wk28.aspx)? It says: _Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other._
Comment: By the way, I think you should invert the values assigned to the true/false conditions
Answer: Try casting it to an object:
(object) Convert.ToInt16(insertValuesSplit[12])

The problem is that there is no common type that your ternary operator can discern between Convert.ToInt16(insertValuesSplit[12]) and DBNull.Value, but if you cast your value to an object, then it works because there is an implicit conversion between DBNull.Value and object.
Answer: (insertValuesSplit[12] == "NULL") ? Convert.ToInt16(insertValuesSplit[12]) : DBNull.Value)

Short-hand if-statements have to return the same type.
Convert.ToInt16(insertValuesSplit[12]) returns a short
DBNull.Value returns an Object
Answer: The ternary operator is an expression, and as such it has a type. The compiler tries to determine this type but fails because your true-case is a short but your false-case a DBNull.
You have to explicitly cast one of them to object to make it work, e.g.
(object) Convert.ToInt16(insertValuesSplit[12]).
Answer: The true and false sub-expressions of your conditional operator have types DbNull and Int16.
You probably need to cast the results to the only common base type: object.
PS. I think you have the condition reversed: if "NULL" you want DBNUll and not the parse.

Syntax for Stored Procedure Parameter


Web API 2 OData = $format not working: the request is always ignored

Question: I have a Web API OData project and everything is working great. I'm now trying to return xml instead of JSON using the $format parameter, as opposed to specifying a header request, and it is not working. I've tried these approaches:
http://localhost:3845/api/Customer?$format=application/xml
http://localhost:3845/api/Customer?$format=xml
http://localhost:3845/api/Customer?$format=application/xml;odata.metadata=full

All without success. This article says that it is possible: https://blogs.msdn.microsoft.com/webdev/2014/03/13/getting-started-with-asp-net-web-api-2-2-for-odata-v4-0/
I have updated all of my NuGet packages, but it seems that the request is always ignored, and instead I get JSON every time.
Answer: Since the ATOM format (XML) is only a technical committee specification instead of an OASIS standard for the OData V4 protocol, the ATOM format is disabled in the ODataLib from the version 6.3.0.
The correct way to ask the OData V4 service to respond in XML is as follows:
GET http://localhost:3845/api/Customer?$format=application/atom+xml

or set the header Accept to application/atom+xml. But due to the reason mentioned above, it doesn't work for Web API OData V4.
Answer: To support $format=xml and $format=json, add the following configuration:
config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");


Selection Issue

Question: So I have this QVD where records seize to update incrementally, the last record is dated 25/04/2022. However, I enable to generate new dates to calculate the interest accrued with the expression; RANGESUM(BELOW(SUM(DailyInterest),0,NOOFROWS())) + SUM(Interest).
My challenge is whenever  I select any subsequent date, the amount defaults to 5,263.25, that's the initial amount as of 25/04/2022.
Table without any date selection
Table with 27/04/2022 selection
Apparently, in the above scenario, the amount should read 5,409.45 and not 5,263.25.
Help me out here, please!
Table with Daily Interest column
Comment: Tough formula to guess out. Could you add a `sum(DailyInterest)` column in your test cases so we can understand better what's going on?
Comment: @GeorgeMenoutis as requested please refer to this https://i.stack.imgur.com/h6lTy.jpg
Answer: Disclaimer, there is guesswork in this answer, it might not work.
Your formula of rangesum + below (x,x,noofrows()) access the data table and sums all(noofrows) rows with date less or equal than the dimension value.
There is no set analysis in your formula; That means, when you make a selection, the other dates' data are removed from the calculation. Obviously 5263.25 (or maybe 5263.25-73.10) is an initial value, maybe sum(Interest).
One solution would be to make a set analysis that would make DailyInterest ignore your selections:
RANGESUM(BELOW(SUM({1}DailyInterest),0,NOOFROWS())) + SUM(Interest).
That might cause your chart to re-show dates you don't need. In this case, you have the generic problem of "I want to see less rows, but not actually select less data". You can solve this by using "Hide zeroes" and using IFs on every measure to make sure they are equal to zero/null for the dimension values you don't want.
You could of course calculate the accrued in your data model, which would be simpler.
Comment: I have been at this since and exploring your suggestion. But eventually, the expression distorts the result and even more I  can't do away with the zero anomaly.. sigh

Selection Issue


Dihedral Group of Order 12 in Cycle Notation

Question:
I want to check that this cycle notation is correct for the Dihedral Group of order $12$. I found this graph in Wikipedia. I did not find the cycle notation. May you please tell me if my cycle notation is correct?
Here is my solution: I will name the vertices $1,2,3,4,5,6$ in the clockwise direction.
1) Rotation 0 degrees
$(1)(2)(3)(4)(5)(6)$
2) Rotation 60 degrees (clockwise direction)
$(123456)$
3) Rotation 120 degrees
$(135)(246)$
4) Rotation 180 degrees
$(14)(25)(36)$
5) Rotation 240 degrees
$(153)(264)$
6) Rotation 300 degrees
$(165432)$
7) Flip 2-5
$(2)(5)(13)(46)$
8) Flip 1-4
$(1)(4)(26)(35)$
9) Flip 3-6
$(3)(6)(15)(24)$
10) Flip A
$(12)(36)(45)$
11) Flip B
$(14)(23)(56)$
12) Flip C
$(16)(25)(34)$
Comment: @hellotinfish The 1-cycle notation is important for the Polya's enumeration theorem and the Cauchy-Frobenius-Burnside theorem
Comment: Whatever you're asking, you should delete all the 1-cycles. They can be omitted.
Answer: There is a computationally easier way to do this, and you do not even need to revisit the geometric intepretation of $\operatorname{Dih}(6)$. Let $\phi:\operatorname{Dih}(6)\times\{1,2,3,4,5,6\}\rightarrow\{1,2,3,4,5,6\}$ be the group action of the dihedral group of a regular hexagon on the six vertices. Let $\varphi:\operatorname{Dih}(6)\rightarrow\operatorname{Sym}(6)$ be the permutation representation afforded by the action. Then write $\varphi(r)=(123456)$ and $\varphi(s)=(13)(46)$. Then since $\varphi$ is a homomorphism, and $\operatorname{Dih}(6)=\{1,r,r^2,\dots,s,sr,sr^2\dots\}$ is generated by $r$ and $s$, you can compute the cycle representation of each element of $\operatorname{Dih}(6)$, e.g. $\varphi(sr^2)=\varphi(s)\varphi(r)^2=(13)(46)(123456)^2=\dots$ (check it yourself :D).
P.S. Hmm... it seems that your answer is correct, but you should check it again using the group action approach anyway.
Comment: The 1-cycle notation is important for the Polya's enumeration theorem and the Cauchy-Frobenius-Burnside theorem.
Comment: Thank you so much for your help! Very interesting!


ZF2 router configuration for handling multiple subdomains

Question: I'm working on a zf2 project and i need to configure some of my modules to work on different subdomains following scenario:

I have different Modules like API, Backend (Admin), Application (Core
module), Blog etc..
I have multiple vhosts which points to same
application/public directory like api.foobar.com, admin.foobar.com
I'm using unique controller keys/aliases in each module like this:

...
'controllers' => array(
    'invokables' => array(
        'home-controller'     => 'Application\Controller\IndexController',
    ),
),

So, i want to change my application's behaviour based on domain (hostname/routeMatch), if hostname looks like api.foobar.com my default controller should derived form a restful controller, if it's a generic homepage request my auth-backed admin controller should not invoke, if it's a mobile site, change home controller to mobile-controller, utilize different layout etc...
Non-working configuration (application/config/module.config.php):
return array(
    'router' => array(
        'routes' => array(
           'home' => array(
                'type' => 'hostname',
                'options' => array(
                    'route' => 'www.foobar.com',
                    'defaults' => array(
                        '__NAMESPACE__' => 'Application\Controller',
                        'controller' => 'home-controller',
                        'action' => 'index'
                    )
                )
            ),
            'api' => array(
                'type' => 'hostname',
                'options' => array(
                    'route' => 'api.foobar.com',
                    'constraints' => array(
                        'subdomain' => 'api',
                    ),
                    'defaults' => array(
                        '__NAMESPACE__' => 'Api\Controller',
                        'controller' => 'api-controller',
                        'action' => 'index'
                    )
                )
            ),
            'admin' => array(
                'type' => 'hostname',
                'options' => array(
                    'route' => 'admin.foobar.com',
                    'constraints' => array(
                        'subdomain' => 'admin',
                    ),
                    'defaults' => array(
                        '__NAMESPACE__' => 'Admin\Controller',
                        'controller' => 'admin-controller',
                        'action' => 'index'
                    )
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'default' => array(
                        'type' => 'Segment',
                        'options' => array(
                            'route' => '/[:controller[/:action]]',
                            'constraints' => array(
                                '__NAMESPACE__' => 'Admin\Controller',
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action' => '[a-zA-Z][a-zA-Z0-9_-]*'
                            ),
                            'defaults' => array()
                        )
                    )
                )
            )
        )
    )
);

Interesting thing is, currently with this configuration i'm getting a 404 page not found error both api.foobar.com, www.foobar.com and admin.foobar.com on my devlepment environment and dump of routes like following:
object(Zend\Mvc\Router\PriorityList)[214]
  protected 'routes' =>
    array (size=3)
      'home' =>
        array (size=3)
          'route' =>
            object(Zend\Mvc\Router\Http\Hostname)[216]
              ...
          'priority' => int 0
          'serial' => int 0
      'admin' =>
        array (size=3)
          'route' =>
            object(Zend\Mvc\Router\Http\Part)[218]
              ...
          'priority' => int 0
          'serial' => int 1
              ...
          'priority' => int 0
          'serial' => int 2
  protected 'serial' => int 3
  protected 'count' => int 3
  protected 'sorted' => boolean false

I got this dump in Application Module > Module.php > onBootstrap($e) method simply:
  $routes = $e->getApplication()->getServiceManager->get('router')->getRoutes();

Questions:

What is wrong with this configration?
why my top-level admin route listing as a Zend\Mvc\Router\Http\Part?
Should i separate route definitions to every module's own module.config.php file for this scenario?
Answer: ---What is wrong with this configuration
it works well in my test, you can refer to the code at the bottom.
So I suggest you should check:

make sure the controller/action files exist
make sure the vhosts has been configured in apache/nginx/, whatever http host you are using.

---why my top-level admin route listing as a Zend\Mvc\Router\Http\Part?
actully, your 'admin' route has child routes configured, zf2 will treat it as 'part' route, please refer to the Zend\Mvc\Router\Http\Part example
---Should I separate route definitions to every module's own module.config.php file for this scenario?
No, actually you can put all module routes in one module's config file if you like.
Here is my code:
return array
(
    'router' => array(
        'routes' => array(
                /*
            'home' => array(
                'type' => 'Zend\Mvc\Router\Http\Literal',
                'options' => array(
                    'route'    => '/',
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                        'action'     => 'index',
                    ),
                ),
            ),
            */
            'home1' => array(
                    'type' => 'hostname',
                    'options' => array(
                            'route' => 'zfskeleton.com',
                            'defaults' => array(
                                    '__NAMESPACE__' => 'Application\Controller',
                                    'controller' => 'Index',
                                    'action' => 'index'
                            )
                    )
            ),
            'home' => array(
                    'type' => 'hostname',
                    'options' => array(
                            'route' => 'www.zfskeleton.com',
                            'defaults' => array(
                                    '__NAMESPACE__' => 'Application\Controller',
                                    'controller' => 'Index',
                                    'action' => 'index'
                            )
                    )
            ),
            'api' => array(
                    'type' => 'hostname',
                    'options' => array(
                            'route' => 'api.zfskeleton.com',
                            'constraints' => array(
                                    'subdomain' => 'api',
                            ),
                            'defaults' => array(
                                    '__NAMESPACE__' => 'Album\Controller',
                                    'controller' => 'Album',
                                    'action' => 'api'
                            )
                    )
            ),
            'admin' => array(
                    'type' => 'hostname',
                    'options' => array(
                            'route' => 'admin.zfskeleton.com',
                            'constraints' => array(
                                    'subdomain' => 'admin',
                            ),
                            'defaults' => array(
                                    '__NAMESPACE__' => 'Album\Controller',
                                    'controller' => 'Album',
                                    'action' => 'admin'
                            )
                    ),
                    'may_terminate' => true,
                    'child_routes' => array(
                            'default' => array(
                                    'type' => 'Segment',
                                    'options' => array(
                                            'route' => '/[:controller[/:action]]',
                                            'constraints' => array(
                                                    '__NAMESPACE__' => 'Admin\Controller',
                                                    'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*'
                                            ),
                                            'defaults' => array()
                                    )
                            )
                    )
            ),
            // The following is a route to simplify getting started creating
            // new controllers and actions without needing to create a new
            // module. Simply drop new controllers in, and you can access them
            // using the path /application/:controller/:action
            'application' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/application',
                    'defaults' => array(
                        '__NAMESPACE__' => 'Application\Controller',
                        'controller'    => 'Index',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),


Sending Mail - Yii 2.0

Question: I'm trying to send mail, but getting error like.

Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: yii\web\Application::mail

After changing Yii::$app->mail->compose() to Yii::$app->mailer->compose()
I got this error

Invalid Parameter – yii\base\InvalidParamException
Invalid path alias:@backend/mail

I'm not getting where i'm doing mistake.
I'm using yii-app-basic.
config/console.php
...
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
        ],
    ],
...

config/web.php
...
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@backend/mail',
            'useFileTransport' => true,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'localhost',
                'username' => 'root',
                'password' => '',
                'port' => '8080',
                'encryption' => 'tls',
            ],
        ],
    ],
...

SiteController.php
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;

class SiteController extends Controller
{
    public function actionRegister()
    {
        Yii::$app->mail->compose()
                ->setFrom('email@example.com')
                ->setTo('email@example.com')
                ->setSubject('This is a test mail')
                ->send();
    }
}

Error Screenshot

I'm new to Yii. I don't have much idea. If this is a silly question,please forgive me.
Taking help from Mailing- Yii 2.0. But, not getting much idea.
Please help me to send email
Comment: @InsaneSkull. I edited my question. Now, register.php page content is available.
Comment: From what I remember, ```backend``` in yii refers to a different config than the web config
Answer: Use mailer component.
Yii::$app->mailer->compose()

In your config you write components that will be avalible on Yii::$app application.
Example:
In config:
'components' => [
    'myComponent' => ['class' => '\common\MyClass']
]

In controller:
Yii::$app->myComponent->foo();

Comment: Got Error Like
Invalid Parameter – yii\base\InvalidParamException
Invalid path alias: @backend/mail
Comment: You should write correct path to mail views in param `'viewPath' => '@backend/mail',`
Comment: where to edit Mr @Onedev. Both config.php and web.php have param.
And, what path to give
Comment: Yeah. Got it. just changed 'viewPath' => '@backend/mail', to 'viewPath' => '@app/mail',
Answer: You are using the basic template. Path '@backend/mail' is only for advanced template. The correct path is @app/mail (or whatever path where you are storing your email templates).
Answer: well it's an old question but if you still using yii if you want to send a mail with no effort use dektrium it's an abandoned project but it provides many features user management email login etc

Sending Mail - Yii 2.0


Bootstrap responsive columns order based on alphabetical content

Question: Let's say I have 4 columns like this

A   D   G   J
B   E   H   K
C   F   I   L

I just can't get my head around the markup that's needed to let it flow like this:

A   G
B   H
C   I
D   J
E   K
F   L

Instead of

A   D
B   E
C   F
G   J
H   K
I   L

Any information regarding this issue would be much appreciated!
Comment: I don't think you will be able to achieve this with bootstrap. Why not put the Letters in their correct order: A B C D /linebreak E F G H...
Comment: Are you asking to change the columns on a different viewport?
Comment: Yes, Sorry!
Basically what I want is that when viewing it on a large screen, all 4 are next to each other
When on a tablet, you get 2 columns and on a phone, all of them are underneath each other, respecting the sorting (alphabetically)
Answer: You should be able to do this with:

A
B
C

G
H
I

D
E
F

J
K
L

I find designing from the smallest size first make this easy.
bootply example
Comment: I think this should be accepted as the correct answer, as it is the most elegant and straightforward answer.
Comment: Anonymous coward downvoter care to grow a pair and comment?
Answer: You can try something like this. Note - this is 2 columns at less than 768px and 4 at 768px and up.
Demo here

A

B

C

D

E

F

G

H

I

J

K

L

Answer: Assuming you are using bootstrap 3. I have achieved the effect I think you are after by nesting columns:

A
 B
 C

D
 E
 F

G
 H
 I

J
 K
 L

Demo


Auth::check() in view always returns false

Question: I am trying to display some content in a partial only to logged in users. The content is never displayed. Here is the bit of code:
  @if(Auth::check())

         Edit

  @endif

The page that contains the partial is available to everyone; I only want to hide this one bit of content.
Can anyone point me in the right direction?
Additional info
This is part of a CMS system I am attempting to write. So, the controller is called via a service provider (RouteServiceProvider). I am pulling the routes based on a pages model. Here is the pertinent method:
  public function map(Router $router)
  {
    $this->mapWebRoutes($router);

    foreach (Page::all() as $page) {
        $router->get($page->uri, ['middleware' => 'web', 'as' => $page->name, function () use ($page, $router) {
            return $this->app->call('App\Http\Controllers\PageController@show', [
                'page' => $page,
                'parameters' => $router->current()->parameters()
            ]);
        }]);
    }
  }

Comment: Did you try auth()->check() instead of Auth::check()?
Comment: are you sure this controller is passed through `auth` middleware?
Comment: @MinaAbadir no. You may be onto my problem. How do I do that and still allow guests?
Comment: @RogerCreasy you are correct, I meant middleware `web`
Comment: Thanks. I tried adding the web middleware in my `RouteServiceProvider`. It still doesn't work..
Comment: @RogerCreasy can you post your routes file and the method from which this view is initiated
Comment: @jaysingkar I added my routeprovider. Should I call the web middleware in teh controller instead?
Comment: @RogerCreasy no, its look good, BTW where are you using `auth` middleware ?
Comment: Please double check your spelling of files and in your question - `RouteSrevicePRovider` is an obvious typo in your question wording. But assuming you aren't replicating typos in your actual code is a bad place to start in debugging.
Comment: Auth middleware is used on the backend. I need someone logged into the backend to see some links on the front-end
Comment: @Jonathan thanks. Good thought...I have a lazy pinky on the shift key :)
Comment: `Auth::check()` should be all you need. Did you actually load the laravel library with `php artisan make:auth` ?
Comment: @Jonathan not sure. How could I confirm?
Comment: The first step to using the auth library with laravel is to generate the required files with `php artisan make:auth`. If you haven't done this step, it might explain why you don't have `Auth` available to your view
Comment: I am using authentication on the backend, and it is working. Is it possible that the session is just not available on my frontend for some reason?
Comment: What resource did you read that lead you to defining your routes in `RouteServiceProvider`? I can understand that this may be your CMS approach to defining routes - but I'd like to see the info myself so I can cut it apart
Comment: It was on a TutsPlus how-to. So, it is paid content. I am only just beginning to understand how it functions. It is done this way so users can define pages. I am OK with taking it apart and define routes the usual Laravel way, if that is what would worjk best.
Answer: I found the solution
public function map(Router $router)
{
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    Route::group(['middleware' => 'web'], function ($router) {

    if (! app()->runningInConsole()) {
        foreach (ProductCategory::all() as $category) {
            $router->get($category->uri, ['as' => $category->name, function () use ($category, $router) {
                return $this->app->call(
                    'App\Http\Controllers\PageController@show', [
                    'category' => $category,
                    'parameters' => $router->current()->parameters()
                ]);
            }]);
        }
    }

    });

}

Comment: explain the solution a little more, so the OP can learn from it and not just copy-paste it.


Spring deserializes a LocalDate in a @RequestBody differently from one in a @RequestParam - why, and can they be the same?

Question: QUESTION: Spring appears to use different deserialization methods for LocalDate depending on whether it appears in a @RequestBody or a request @ReqestParam - is this correct, and if so, is there a way to configure them to be the same throughout an application?
BACKGROUND: In my @RestController, I have two methods - one GET, and one POST. The GET expects a request parameter ("date") that is of type LocalDate; the POST expects a JSON object in which one key ("date") is of type LocalDate. Their signatures are similar to the following:
@RequestMapping(value = "/entity", method = RequestMethod.GET)
public EntityResponse get(
       Principal principal,
       @RequestParam(name = "date", required = false) LocalDate date)

@RequestMapping(value = "/entity", method = RequestMethod.POST)
public EntityResponse post(
       Principal principal,
       @RequestBody EntityPost entityPost)

public class EntityPost {
       public LocalDate date;
}

I've configured my ObjectMapper as follows:
@Bean
public ObjectMapper objectMapper() {

   ObjectMapper objectMapper = new ObjectMapper();
   objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
   objectMapper.registerModule(new JavaTimeModule());
   objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

   return objectMapper;
}

Which ensures the system accepts LocalDate in the format yyyy-MM-dd and deserializes it as expected - at least when it is part of a @RequestBody. Thus if the following is the request body for the POST
{
"date": 2017-01-01
}

The system deserializes the request body into an EntityPost as expected.
However, that configuration does not apply to the deserialization of the @RequestParam. As a result, this fails:
// fail!
/entity?date=2017-01-01

Instead, the system appears to expect the format MM/dd/yy. As a result, this succeeds:
// success!
/entity?date=01/01/17

I know I can change this on a parameter-by-parameter basis using the @DateTimeFormat annotation. I know that if I change the signature of the GET method as follows, it will accept the first format:
@RequestMapping(value = "/entity", method = RequestMethod.GET)
public EntityResponse get(
       Principal principal,
       @RequestParam(name = "date", required = false) @DateTimeFormat(iso=DateTimeFormat.ISO.DATE) LocalDate date)

However, I would prefer if I didn't have to include an annotation for every usage of LocalDate. Is there any way to set this globally, so that the system deserializes every @RequestParam of type LocalDate in the same way?
For reference:
I'm using Spring 4.3.2.RELEASE
I'm using Jackson 2.6.5
Comment: The body gets parsed by Jackson the param does not, that's why it is different. Usually you can just register a custom converter with the ConversionService which does the conversion you want it to do. - Also the link from @Andreas seems to be what you want.
Comment: I believe you need to define a global `@ControllerAdvice`. See [Setting default DateTimeFormat Annotation in Spring](http://stackoverflow.com/q/40644368/5221149)
Comment: Are you using spring boot?
Comment: *"What system ...?"* Spring Framework. `@RequestParam` processing is all Spring.
Comment: It is part of `spring-web-XXX.jar`. So I guess you could call that the "Web" subsystem. It is mainly documented in the "[Web MVC framework](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html)" chapter of the "[Spring Framework Reference Documentation](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/index.html)" guide, so perhaps the "Web MVC" subsystem is the answer you're looking for.
Comment: No, not using spring boot.
Comment: What system is used to deserialize the request params?
Comment: Add `@DateTimeFormat(pattern="yyyy-MM-dd")` to your `@RequestParam` annotated argument. Else configure the formatter/converter to (also) accept that date format.
Comment: @Andreas - what part of the Spring Framework, I mean. Any component in particular?
Comment: @Andreas - I should say, I now understand that I need to configure WebDataBinder, but beyond that, is there any more information on the Spring Framework subsystem that handles deserialization of request parameters?
Comment: @Andreas - That gives me what I need to know. Thanks!
Answer: Per @Andreas in comments, the Spring Framework uses Jackson to deserialize @RequestBody but Spring itself deserializes @RequestParam. This is the source of the difference between the two.
This answer shows how to use @ControllerAdvice and @InitBinder to customize the deserialization of @RequestParam. The code I ultimately used follows:
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.Format;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.function.Function;

@ControllerAdvice
public class ControllerAdviceInitBinder {

    private static class Editor<T> extends PropertyEditorSupport {

        private final Function<String, T> parser;
        private final Format format;

        public Editor(Function<String, T> parser, Format format) {

            this.parser = parser;
            this.format = format;
        }

        public void setAsText(String text) {

            setValue(this.parser.apply(text));
        }

        public String getAsText() {

            return format.format((T) getValue());
        }
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {

        webDataBinder.registerCustomEditor(
                Instant.class,
                new Editor<>(
                        Instant::parse,
                        DateTimeFormatter.ISO_INSTANT.toFormat()));

        webDataBinder.registerCustomEditor(
                LocalDate.class,
                new Editor<>(
                        text -> LocalDate.parse(text, DateTimeFormatter.ISO_LOCAL_DATE),
                        DateTimeFormatter.ISO_LOCAL_DATE.toFormat()));

        webDataBinder.registerCustomEditor(
                LocalDateTime.class,
                new Editor<>(
                        text -> LocalDateTime.parse(text, DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                        DateTimeFormatter.ISO_LOCAL_DATE_TIME.toFormat()));

        webDataBinder.registerCustomEditor(
                LocalTime.class,
                new Editor<>(
                        text -> LocalTime.parse(text, DateTimeFormatter.ISO_LOCAL_TIME),
                        DateTimeFormatter.ISO_LOCAL_TIME.toFormat()));

        webDataBinder.registerCustomEditor(
                OffsetDateTime.class,
                new Editor<>(
                        text -> OffsetDateTime.parse(text, DateTimeFormatter.ISO_OFFSET_DATE_TIME),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME.toFormat()));

        webDataBinder.registerCustomEditor(
                OffsetTime.class,
                new Editor<>(
                        text -> OffsetTime.parse(text, DateTimeFormatter.ISO_OFFSET_TIME),
                        DateTimeFormatter.ISO_OFFSET_TIME.toFormat()));

        webDataBinder.registerCustomEditor(
                ZonedDateTime.class,
                new Editor<>(
                        text -> ZonedDateTime.parse(text, DateTimeFormatter.ISO_ZONED_DATE_TIME),
                        DateTimeFormatter.ISO_ZONED_DATE_TIME.toFormat()));
    }
}

Comment: This solution does not work with `@RequestParam(required = false)` Optional date`. For a solution that can also deal with these, see this answer: https://stackoverflow.com/a/45453492/5391954
Answer: Create a Formatter for LocalDate:
public class LocalDateFormatter implements Formatter<LocalDate> {

    @Override
    public LocalDate parse(String text, Locale locale) throws ParseException {
        return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
    }

    @Override
    public String print(LocalDate object, Locale locale) {
        return DateTimeFormatter.ISO_DATE.format(object);
    }
}

Spring 5+:
Register the formatter:
Implement WebMvcConfigurer in your @Configuration and override addFormatters:
@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatter(new LocalDateFormatter());
}

Spring Boot: Define a @Primary @Bean to override the default formatter:
@Bean
@Primary
public Formatter<LocalDate> localDateFormatter() {
    return new LocalDateFormatter();
}

Comment: The Spring 5+ solution worked fine for me in Spring Boot (2.1.9) environment but I could not get the "Spring Boot" option to work. Still, this is by far the easiest solution that I found after hours of testing different variations and configurations.
Comment: It should work, as it is provided by [auto configuration](https://docs.spring.io/spring-boot/docs/2.1.9.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration).
Answer: for springboot 2.1.6
 @Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> {
        DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        builder.serializerByType(LocalDate.class, new LocalDateSerializer(localDateFormatter));
        builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(localDateFormatter));

        DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(localDateTimeFormatter));
        builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(localDateTimeFormatter));
    };
}


Use of getline to parse and store variables

Question: I'm writing a simple sandbox text-based game in c++ and have just got around to save files. Having looked at a few of the questions on this site and others I opted to do my own rather that use the boost libraries etc.
My save code works fine however, my load code isn't working like I want!
int loadGame(string filename){
string delim=":";
string readline;

ifstream filestream;
filestream.open(filename.c_str());

while(getline(filestream,readline)){
    cout << readline << endl;
    stringstream linestream(readline);
string         data;
getline(linestream, data, ':');
linestream >> playername >> location[0] >> location[1] >> hitpoints >> coins >> axes >> swords >> food >> maps;
}
return 0;
}

It currently loops, as you would expect but then stores only the last 'maps' variable to playername.
I understand that the while(getline(filestream,readline)){ is the cause of the problem but as a newbie I can't see how to work around this without adding in a loop with lots of ifs that does an
(pseudo code)
while(n<10){
if n=1{ linestream >> playername}
if n=2{linestream >> location[0]...

which seems to me to be very drawn out and inefficient.
A sample save might look like this:
playername:John
location[0]:400
location[1]:840
hitpoints:100
coins:35
axes:0
swords:0
food:0
maps:3

I know this is probably badly worded but I'd appreciate any help on this problem. Thanks in advance.
ps any other tips on the code posted here would be great :)
Answer: In the loadGame function you are checking unknown "arg" to string "null", not NULL.
Comment: I've removed the unrelated code you mentioned the variable 'arg' was from a separate function. Also, null was a potential input for that variable so wasn't as incorrect as it looked!
Comment: In that case checkout following one:  http://stackoverflow.com/questions/17971593/c-getline-and-file-eof
Answer: If you're beginning with C++, there are a couple of tips I could give you.
First of all, don't bother with parsing. There are far more interesting things to do with your time. Choose an easier input format, like
playername John Doe
hitpoints 300

Notice that I'm using a white space to separate the value from the key. Now you can simply do something like:
std::string key, value;
while (<more input>)
{
    input_file >> key;
    std::getline(input_file, value);

    if (key == "playername")
        // whatever...
    else if (key == "maps")
        // stuff...
}

Comment: Thanks a lot. I've just played around with it and it seems to be working now. And thanks for saving me from the clutches of parsing :L


How to change timezone with Offset when Deserializing DateTime using JSON.NET in Azure APIM?

Question: I'm using Azure APIM policy expression to aggregate multiple responses. In that one of the JSON response contains multiple dateTime fields. all of them are in UTC TZ. I want to deserialize all of the date fields to specific Timezone(in my case SGT +08:00) from +00:00
Input:
{
    "Header": {
        "UserID": "xxxxxx",
        "MessageID": "xxxxxx",
        "CorrelationID": "xxxx",
        "DateTime": "2018-02-12T15:31:18+00:00",
        "ReqID": "xxx"
    },
    "ResultSet": {
        "Tier": {
            "CardSuffix": "91",
            "RetentionDeadline": "2022-02-27T16:00:00+00:00",
            "PointsRequireToQualify": "xxxxx",
            "QualifyingDeadline": "2022-02-27T16:00:00+00:00",
            "SignupDate": "2020-08-07",
            "IssuedDate": "2021-06-15",
            "JoiningDateTime": "2010-03-31T10:10:00+00:00",
            "RequireToUpgradeInYear": "288886",
            "YearlyUpgradeDeadline": "2022-02-27T16:00:00+00:00",
            "CurrentCardDesc": "xxxxxxxx",
            "NextCardDesc": "xxxxxxxxx",
            "CurrentTierPoints": "0",
            "UpdatedDateTime": "2023-01-09T17:43:54.844+00:00",
            "LastRefreshedDateTime": "2022-02-10T07:45:13+00:00"
        }
    }
}

Expected Output:
{
    "Header": {
        "UserID": "xxxxxx",
        "MessageID": "xxxxxx",
        "CorrelationID": "xxxx",
        "DateTime": "2018-02-12T15:31:18+08:00",
        "ReqID": "xxx"
    },
    "ResultSet": {
        "Tier": {
            "CardSuffix": "91",
            "RetentionDeadline": "2022-02-28T0:00:00+08:00",
            "PointsRequireToQualify": "xxxxx",
            "QualifyingDeadline": "2022-02-28T0:00:00+08:00",
            "SignupDate": "2020-08-07",
            "IssuedDate": "2021-06-15",
            "JoiningDateTime": "2010-03-31T10:10:00+08:00",
            "RequireToUpgradeInYear": "288886",
            "YearlyUpgradeDeadline": "2022-02-28T0:00:00+08:00",
            "CurrentCardDesc": "xxxxxxxx",
            "NextCardDesc": "xxxxxxxxx",
            "CurrentTierPoints": "0",
            "UpdatedDateTime": "2023-01-10T22:08:08+08:00",
            "LastRefreshedDateTime": "2022-02-10T15:45:13+08:00"
        }
    }
}

I have tried and achieved the expected output by using ConvertTimeBySystemTimeZoneId(DateTimeOffset, String) Method, But real Problem is I don't want to add each individual Property name  to change the time zone with Offset. I need generic efficient solution that deserialize DateTime fields to Specific TimeZone with the format .ToString("yyyy-MM-ddTH:mm::sszzz")
Here's my fiddle: sample
If you see my above sample, I have parse the input as JObject and converts to required format for the first property alone
obj["ResultSet"]["Tier"]["RetentionDeadline"] which changed from "RetentionDeadline": "2022-02-27T16:00:00+00:00", to "RetentionDeadline": "2022-02-28T0:00:00+08:00",
Problem with this solution:
If any new DateField is added in the backend response, I need to revisit my policy expression again and do this manual conversion. So I want generic one time conversion for all dateTime fields.
Please note that I'm writing this inside policy expression; so I can't reuse the functionality by using any c# extensions or helper methods.
Answer: You can do this by looping over the children of the JSON object:
var obj = context.Request.Body.AsJObject(true, new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None } );
foreach (JProperty x in (JToken)obj["ResultSet"]["Tier"])
{}

DateParseHandling is used for the date format does not change.
A very simple Regex is used to recognize dates 2022-02-27T:
^[0-9]{4}-[0-9]{2}-[0-9]{2}T
Complete policy:
<policies>
    <inbound>
        <base />
        <return-response>
            <set-status code="200" reason="OK" />
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>@{
                var obj = context.Request.Body.AsJObject(true, new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None } );

                var pattern = @"^[0-9]{4}-[0-9]{2}-[0-9]{2}T";
                var regex = new Regex(pattern);

                foreach (JProperty x in (JToken)obj["ResultSet"]["Tier"])
                {
                    string name = x.Name;
                    JToken tokenValue = x.Value;

                    if(regex.IsMatch(tokenValue.ToString()))
                    {
                        obj["ResultSet"]["Tier"][name] = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(new DateTimeOffset(Convert.ToDateTime(obj["ResultSet"]["Tier"][name])), "Singapore Standard Time").ToString("yyyy-MM-ddTH:mm::sszzz");
                    }
                }

                return obj.ToString();
            }</set-body>
        </return-response>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Result:
Comment: Thank you very much, Marcus! I simply added a few empty string checks in addition to the RegEx approach for DateTime conversion. It was successful.
Answer: Update: My backend has been sending proper TimeZone data.
If your response has a Proper DateTime field with TimeZone and you want to keep the original value in TimeZone, this DateParseHandling = DateParseHandling.None can be used.
Below is an example Snippet.
https://dotnetfiddle.net/AlPJmk
This could be useful to someone.


DjangoCMS Plugin to list out specific staff from apphook model

Question: I am new to DjangoCMS. So please bear with me if the question is too trivial.
I have made an app hook for adding staff for a website with
model.py
from django.db import models
from filer.fields.image import FilerImageField
from djangocms_text_ckeditor.fields import HTMLField
from django.urls import reverse
from cms.models.fields import PlaceholderField

# Create your models here.

class Designations(models.Model):
    class Meta:
        app_label = 'voxstaff'
        verbose_name_plural = 'designations'
    desingation = models.CharField(
        blank=False,
        help_text="Please provide a label for the Designation",
        unique=True,
        max_length=100
    )

    def __str__(self):
        return self.desingation

class Staffs(models.Model):

    class Meta:
        app_label = 'voxstaff'

    full_name = models.CharField(
        blank=False,
        unique=True,
        help_text="Please enter the full name of the staff",
        max_length=100
    )

    slug = models.SlugField(
        blank=False,
        default='',
        help_text='Provide a unique slug for this staff member',
        max_length=100,
    )

    desingation = models.ForeignKey(
        Designations,
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )

    photo = FilerImageField(
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
    )
    staff_intro = HTMLField(blank=True)

    bio = PlaceholderField("staff_bio")

    is_featured = models.BooleanField()

    def get_absolute_url(self):
        return reverse("voxstaff:staffs_detail", kwargs={"slug": self.slug})

    def __str__(self):
        return self.full_name

class LinkTypes(models.Model):
    link_type = models.CharField(max_length=100)

    def __str__(self):
        return self.link_type

class Links(models.Model):
    staff = models.ForeignKey(Staffs,on_delete=models.CASCADE)
    link_type = models.ForeignKey(LinkTypes,on_delete=models.SET_NULL,null=True,blank=True)
    link_url = models.CharField(max_length=200)

    def __str__(self):
        return self.link_type.link_type

And cms_apps.py as below
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _

from .menu import StaffSubMenu

@apphook_pool.register
class StaffApp(CMSApp):
    name = _('VOXStaff')
    # urls = ['voxstaff.urls', ]
    app_name = 'voxstaff'
    menus = [StaffSubMenu, ]
    def get_urls(self, page=None, language=None, **kwargs):
        return ["voxstaff.urls"]

Now I need to Plugin that displays the staffs in the Home page. These staff should be with is_featured as Yes int the Staffs model.
How to proceed for the same. Please help, I am stuck.
Answer: I could meet my requirement by below post
django cms plugin that display model with specific value checked
This question can be closed.


Does exhaustaffect Karthus damage while he is undead?

Question: So let's say you are playing with Exhaust and you kill Karthus while he is Exhausted. Will his damage be reduced by Exhaust in his passive if you killed him while exhaust was active?
Comment: I dont think so because he technically dies and then comes back for a brief period. I have no evidence supporting it, but I am certain that exhaust's effects only last up until death.
Comment: Since Karthus is untargetable in the afterlife, you can't exhaust him.
Comment: I understand that what i just mean is if you get the exhaust and kill him 1 second after for the 1.5 s left on exhaust is the damage modifier still in effect
Comment: @slow_excellence: oh yeah that makes sense.
Comment: No. Karthus is untargettable and is instantly free from any CC when his passive skill is active.
Answer: No.  When Karthus dies and his passive is activated, all CC is removed and he is untargetable for the duration of the effect.
"Upon dying, Karthus enters a spirit form and becomes invulnerable and untargetable, allowing him to continue casting spells at no cost for 7 seconds."
-From the League of Legends Wiki.
http://leagueoflegends.wikia.com/wiki/Karthus


Truncated result when using Paramiko invoke_shell

Question: I am using Paramiko invoke_shell to pull results of the top command from a remote system. But I am getting truncated lines when looking at the results.
Code as follows :
channel = token.invoke_shell()

channel.send ('terminal length 0\n')
time.sleep(1)
resp = channel.recv(9999)
output = resp.decode('ascii')

channel.send('top -n 1\n')
time.sleep(1)
resp = channel.recv(9999)
output = resp.decode('ascii')
result = (''.join(output))

return (result)

The result is as follows (note cn_node+ is not the complete name, it is longer):
    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  28639 root      20   0   17.0g  38912  28336 S 111.1   0.1   1101:49 cn-node+
  29889 root      20   0 3379668  16532  13428 S  94.4   0.1 991:39.71 Flare

If directly ssh'ed into the system and running the command, the result is :
    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  28639 root      20   0   17.0g  38912  28336 S 116.7   0.1   1186:17 cn-node-cnfp
  29889 root      20   0 3379668  16796  13428 S  94.4   0.1   1067:53 Flare

Wondering how to get the whole line and not the truncated line (get cn-node-cnfp instead of cn-node+).
Thanks!
Answer: Set width parameter of SSHClient.invoke_shell to more than the default value of 80:
channel = token.invoke_shell(width=160)

Though better is probably to use COLUMN environment variable.
See Linux: How to not limit output from top based on screen width

In any case, you in general should not use SSHClient.invoke_shell for automating command execution. Use `SSHClient.exec_command. See What is the difference between exec_command and send with invoke_shell() on Paramiko?


Prove that $0 \leq ab^2-ba^2 \leq \frac{1}{4}$ with $0 \leq a \leq b \leq 1$.

Question:
Let $a$ and $b$ be real numbers such that $0 \leq a \leq b \leq 1$. Prove that $0 \leq ab^2-ba^2 \leq \dfrac{1}{4}$.

Attempt
We can see that $ab^2-ba^2 = ab(b-a)$, so it is obvious that it is greater than or equal to $0$. But how do I show it is also less than or equal to $\dfrac{1}{4}$?
Comment: Try having$1/2$ as the defining line, you get 3 cases, either both are less than one half, both greater than one half, or only one is greater and only one is less that (or equal in all cases) and prove each one.
Answer: Hint: write $b=a+c$. Then $ab(b-a)=ac(a+c)$. Now apply AM-GM inequality to $a,c$ and recall $a+c=b\leq 1$.
Elaboration on AM-GM part: $\sqrt{ac}\leq\frac{a+c}{2}\leq\frac{1}{2}$ so $ac\leq\frac{1}{4}$.
Comment: Can you elaborate on the AM-GM part?
Comment: Here you go. ${}$
Answer: First proof
The part $0 \leq ab^2-ba^2$ is equivalent with $$0 \leq ab(b-a)$$ which is true because $b \geq a \geq 0$ .
For the other part use $b^2 \leq b \leq 1 $ and $a^2 \leq a$ as follows :
$$ab^2-ba^2 \leq ab-ba^2=b(a-a^2) \leq a-a^2 \leq \frac{1}{4}$$ the last part being equivalent with $\left (a-\frac{1}{2} \right )^2 \geq 0$ .
Second proof
Denote $f(a,b)=ab^2-ba^2=ab(b-a)$ . Now notice that if $d>0$ then :
$$f(a+d,b+d)=(a+d)(b+d)(b-a) \geq ab(b-a)=f(a,b)$$
In this way we can increase $b$ to $1$ by choosing $d=1-b$ (this technique is usually called smoothing ). So it suffices to prove that :
$f(a+d,1) \leq \frac{1}{4}$ which is as in the previous proof equivalent with $$\left (a+d -\frac{1}{2} \right )^2 \geq 0$$
Comment: if $b<1$ then $b^2<b$
Comment: @Leox Thanks , I wrote it backwards but used it right .
Answer: There are more generic ways of solving such problems.
Since $f(a,b) = ab^2 - ba^2$ is continuous and differentiable, and the domain $0 \le a \le b \le 1$ is a compact simplex, it attains its max and min at one of the following points:

A point where $0 < a < b < 1$ and $\nabla f (a,b) = 0$, i.e. $f_x(a,b) = f_y(a,b) = 0$
A point where $a = 0$, $0 < b < 1$, and $f_y(a,b) = 0$
A point where $0 < a < 1$, $b = 1$, and $f_x(a,b) = 0$
A point where $0 < a = b < 1$, and $f_x(a,b) + f_y(a,b) = 0$
A point where $a = b = 0$ or $a = b = 1$.

Calculate that $f_x(a,b) = b^2 - 2ab$, $f_y(a,b) = 2ab - a^2$.
There are no points of type (1).
Type (2) points are anything on the line, and here $a = 0$ so $f(a,b) = 0$.
Type (3) points satisfy $b = 1$, so $1 - 2a = 0$, so $a = \frac12$, and here $f(a,b) = \frac12 - \frac14 = \frac14$. Type (4) points all have $f(a,b) = 0$.
Finally, the two type (5) points are $f(0,0) = 0$ and $f(1,1) = 0$.
Thus the minimum of $f$ is $0$ and the maximum is $\frac14$, on this domain.


Pokémon Go crashes when I try to login

Question: So I mistakenly uninstalled Pokémon Go and I reinstalled it and when I logged in using google, the game crashes. I am using an Samsung Galaxy S6. What am I doing wrong? It says: unfortunately Pokémon Go has stopped when I choose an account. I really want to get back to my account but it just won't work. I've tried re downloading the game but that does nothing. Help!
Comment: Could you run the game before you un-installed it?
Comment: @Fezodge III yes I could.
Comment: @DylanBlack did ya try reinstalling it or the OS?
Comment: In all seriousness; have you tried entirely restarting your phone? As in powering it down, rebooting it, and attempting to login again?
Comment: Does the app actually crash or do you just get a message that you cannot login? Have you tried logging in from a friends phone on PoGo? That should normally work, and maybe if you logout on that phone it might solve it? If not then perhaps your account was banned/ temporary blocked?
Comment: Can you post a crashlog?
Comment: Have you tried clearing the app data/caches? Is your device modded (rooted/whatever)?
Answer: Don't worry about your account; all your data is stored server side and will be restored. I personally swapped to a new phone and could keep playing from where I left off just fine.
Firstly, make sure you've completely rebooted your phone to clear out any active apps and try launching Pokémon GO with no other apps running just to make sure this isn't an issue about having too little memory available.
If that doesn't work here's what you can do to completely reset every bit of data for Pokémon GO which should hopefully make it able to launch again (I doubt what you have is a hardware issue since the S6 is a very high-spec phone which shouldn't have any issues rendering the game).
The following instructions should work for any phone running Android 6 Marshmallow.

Open the settings app.
Tap the menu item called 'Apps' or 'Applications' (This name can differ between devices; ex. the Nexus 5X says 'Apps' and the Samsung Galaxy S6 says 'Applications').
Specifically for the Samsung Galaxy S6: Tap the item called 'Application Manager' to show your installed apps instead of the default Samsung ones.
Find the item named Pokémon GO in the list and tap it.
You should see the app name and icon at the top and a list below. Tap 'Force Stop' at the top.
Now tap storage from the list below.
You should see two buttons, 'Clear Data' and 'Clear Cache'. Tap 'Clear Data' ('Clear Data' should also clear the cache).
Tap back once to return to the menu where you can see the 'Uninstall' button and tap it.
Pokémon GO should be completely uninstalled with all of its data removed too. Go to the Google Play store and download it again.
Attempt to login using your preferred account, it should launch.

What this process is attempting to do is clear every single bit of data related to Pokémon GO from your phone since sometimes an app uninstall won't completely remove it.
If this doesn't work, please comment.
Comment: Okay; so it's not an issue with the app install. You haven't used any extensions/cheats for the app, have you? Not trying to judge, but it's relevant.
Comment: Not on another S6, just any phone at all.
Comment: Can you post a picture of what you see where you get stuck on the instructions? Also, one of my family members has an S6 and I might be able to see if the interface is that different once they are back in a few hours... I didn't think Samsung would have altered this from the way default Android works.
Comment: This didn't work. I did exactly what you said but I still can't log in. Thanks anyway. :)
Comment: No. I have not used any cheats, hacks, etc. Unless PokeVision counts.
Comment: I don't think Pokevision got people banned. Is it possible for you to test it on another phone to determine if this is just your account having issues like @Mr. Meeseeks suggested?
Comment: no, I am the only one in my immediate family/friends with an S6. My dad has an S7 which is the closest to what I use.
Comment: not at the current moment, but I can later. Thanks for all your help! I need to get back to my CP 750 Pigeotto. :P
Comment: Ah; I think I found where the instructions differ for the Samsung S6. I'll add them in case it helps anyone else in the future.
Comment: Still can't log in D:
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/44166/discussion-between-venoda-and-dylan-black).
Comment: @DylanBlack just try to log in to your account from just any other phone (from a friend/family). If that works than the issue should be with your phone. That will at least narrow down where to look to solve this.
Answer: Without a crashlog or backtrace it will be impossible to know what could be causing the crash.  Even with the logs it might be difficult for an end-user to identify the cause of the crash, as the log may need to be symbolicated, etc.
I would open a ticket with Niantic by reporting an issue signing in.  There is also a report a bug form, but I feel that this is specifically a log in issue, so the first link would be your best bet.
Answer: A simple solution to this is - Log out and again Log in to the game.
But since you're already logged in and the game simply crashes on starting, here's something you can try:

Uninstall the current Pokemon GO App from your phone.
Download the latest version from the Play Store and install it.
Run it. Log in using the Google Account.

I too once faced this problem and following the above steps solved it for me. Good luck!
Answer: Since there is no log of any sort. I would suggest clearing cache of google play services. because google play services is the app that deals with logging in to a google+ account in the game.
If this does not open then try Venoda's solution if you haven't already tried. I think after clearing cache of both app will resolve this issue.

Pokémon Go crashes when I try to login


Unclear why (first order) satisfiability undecidable and not semi-decidable.

Question: Hoping this will just be a terminology question, otherwise I have a bigger problem of harboring a misunderstanding re: decidability.
We know that (first order) satisfiability (for the general case of an arbitrary closed formula) is undecidable, and not even semi-decidable, by the following argument:
Validity is semi-decidable, by deciding it in terms of unsatisfiability, which is semi-decidable by the result that closed formulae in Skolem form are unsatisfiable if and only if they have a finite "segment" that is unsatisfiable.
If satisfiability were semi-decidable, then satisfiability and its complement, unsatisfiability would both be semi-decidable, so satisfiability would be decidable, in which case validity would be decidable, contradicting the negative answer to the Entscheidungsproblem of (general first order) validity.
Correct so far, even if not very rigorous?
My question then: We say satisfiability is not semi-decidable, even though its complement (unsatisfiability) is semi-decidable. So one must see 'semi-decidable' as a property of the specific decision problem, i.e. keep apart "x is satisfiable" and "x is not satisfiable", and not incorrectly think of satisfiability as semi-decidable because: "one half of the entire question is decidable, so the entire problem of satisfiability is semi-decidable."
Answer: I'm not totally sure what you're asking, but let me take a stab at it:
Your sentence

One must see 'semi-decidable' as a property of the specific decision problem, i.e. keep apart "x is satisfiable" and "x is not satisfiable"

is absolutely correct. There are many senses in which two decision problems can be "equivalent," and the point is that semidecidability (or more commonly, computable or recursive enumerability) does not always respect these notions. For instance, every c.e. set is Turing equivalent to a co-c.e. set, but obviously no c.e. set is also co-c.e. unless it is computable. This is essentially the example you give of unsatisfiability for first-order formulas.
Comment: Thanks. I was trying to describe what is confusing to me in the last paragraph: a formula being satisfiable is not semi-decidable, a formula not being satisfiable is semi-decidable. I suppose I want to say then "satisfiability (in general) is semi-decidable because "one half of it" is decidable", but that would be wrong. Correct?
Comment: No, that's not correct: satisfiability is not semi-decidable. **Un**satisfiability is semi-decidable. These two statements are *not the same*.
Comment: @RobArthan of course you're right, that's part of my point; although satisfiability is "the same as" unsatisfiability with respect to Turing equivalence, it's not the same with respect to many-one equivalence, and this is the relevant notion of equivalence for c.e.-ness.
Comment: That's what I wanted to have confirmed. Sorry for the awkward phrasing. Will mark as accepted. Thanks!
Comment: Indeed but Turing equivalence is obviously far to crude to be relevant here, because it is based on oracles that give yes/no answers to membership tests. Many-one reduction gives the right notion of equivalence to be used in this context. See https://en.wikipedia.org/wiki/Many-one_reduction.


BigBlueButton audio and video permission denied

Question: I am using BBB in my Laravel web application for online audio/video calls and conferencing, previously it was working fine but now it is showing audio/video permission denied or not allowed, although I allowed mic and video in chrome but didn't work out.

Note: it is without any error running on IE browser.
Comment: Where you able to solve it?
Answer: If you are running Windows 10 just go to Settings -> search Microphone privacy settings. There you have 3 chapters:

Allow access to the microphone on this device
Allow apps to access your microphone.
Allow desktop apps to access your microphone.

You can allow all of them or try some combination which works just to not allow permissions for apps you are not using. Cheers!