return monodimensional-array from multidimensional

Question: I have a multidimensional array:
$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
              1=>array('text'=>'text2','desc'=>'blablabla'),
              2=>array('text'=>'blablabla','desc'=>'blablabla'));

Is there a function to return a monodimensional array based on the $text values?
Example:
monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');

Maybe a built-in function?
Comment: you want to turn all values of a particular sub-key in the array? Change your 'blablabla' to something more unique, because it's not clear which of the 4 blablabla's you want returned.
Answer: This will return array with first values in inner arrays:
$ar = array_map('array_shift', $array);

For last values this will do:
$ar = array_map('array_pop', $array);

If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):
$ar = array_map(function($a) {
    return $a[(key you want to return)];
}, $array);

Comment: First two examples are also PHP4 stuff ;)
Answer: Do it like this:
function GetItOut($multiarray, $FindKey)
{
   $result = array();
   foreach($multiarray as $MultiKey => $array)
        $result[$MultiKey] = $array[$FindKey];

   return $result;
}

$Result = GetItOut($multiarray, 'text');
print_r($Result);

Answer: Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.
The foreach loop would look something like:
function monoarray($myArray) {
    $output = array();

    foreach($myArray as $key=>$value) {
        if( $key == 'text' ) {
            $output[] = $value;
        }
    }

    return $output;
}

Answer: If the order of your keys never changes (i.e.: text is always the first one), you can use:
$new_array = array_map('current', $array);

Otherwise, you can use:
$new_array = array_map(function($val) {
    return $val['text'];
}, $array);

Or:
$new_array = array();
foreach ($array as $val) {
    $new_array[] = $val['text'];
}

Answer: Try this:
function monoarray($array)
{
    $result = array();

    if (is_array($array) === true)
    {
        foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
        {
            $result[] = $value;
        }
    }

    return $result;
}

Answer: With PHP, you only have to use the function print_r();
So --> print_r($array);
Hope that will help you :D


How do I remove XML elements without removing content from the elements' tail?

Question: I'm trying to delete nodes in an xml file. I've managed to get that far but when the script runs it appears to take the attributes belonging to the parent element which come after with it.
Here is the code:
for i, pid in enumerate(root.findall(".//p")):
   for cont in pid.findall('membercontribution'):
          for col in cont.findall('col'):
                 cont.remove(col)

tree.write('fofo.xml')

this:

<member>The Minister for Overseas Development (Mr. Neil Marten)
</member><membercontribution>: a policy
<col>16</col>
foobar barforb </membercontribution>

becomes this:

<member>The Minister for Overseas Development (Mr. Neil Marten)
</member><membercontribution>: a policy </membercontribution>

How do I code this so that I get to keep the "foobar barforb" part that comes after?
Answer: What unintentionally gets removed here is not attributes, but the contents of an element's tail.
The tail property is a peculiarity of the ElementTree API. It is text immediately following an element's end tag and before any other tag. When you remove an element (in this case col), you also remove its tail.
The clearest explanation that I have found is this: http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html.

To get the wanted output, you need to keep a reference to the tail of the removed col element and append it to the text of the parent element. A complete example:
from xml.etree import ElementTree as ET

XML = """
<root>

<member>The Minister for Overseas Development (Mr. Neil Marten)
</member><membercontribution>: a policy
<col>16</col>
foobar barforb </membercontribution>

</root>
"""

root = ET.fromstring(XML)

for pid in root.findall(".//p"):
    for cont in pid.findall('membercontribution'):
        for col in cont.findall('col'):
            col_tail = col.tail.strip()          # Get the tail of "col"
            cont.remove(col)                     # Remove "col"
            cont.text = cont.text.strip() + " "  # Replace trailing whitespace with single space
            cont.text = cont.text + col_tail     # Add the tail to "membercontribution"

print ET.tostring(root)

Output:
<root>

<member>The Minister for Overseas Development (Mr. Neil Marten)
</member><membercontribution>: a policy foobar barforb</membercontribution>

</root>

Comment: Thanks for this. Is there any way to remove the line break that appears between "policy" and "foobar"?


Django -- Custom filter or SQL raw

Question: I have an application with a model which has three tables implementing the toxi tagging model.
One table for jobs, one table for skills and one table to map them, in the form of jobid -- skillid.
Due to the number of mappings if I use the following:
{% for job in jobs %}

{{ job.job_title }}

                        {% for skill in skillmaps %}
                        {% if job.id == skill.job_id.id %}
                                #{{ skill.skill_id|title }}
                        {% endif %}
                        {% endfor %}
{% endwith %}

It just simply uses all the processor and takes a very long time, in the order of 30 minutes.
If I query the DB for all the skillids in the mapping table where jobid = "nnn", the query is really fast.
I was wondering what would be the best approach, as I would like something like this:
{% for job in jobs %}

{{ job.job_title }}

  {{ print all skills for job.job_id}}
{% endwith %}

I've tried with custom filters, but I can't get the code above to work, as it seems I have to filter a value from a for skillmaps foor lop, which it's just the same problem.
Is it possible to define a class with a raw query and pass a variable from the for loop in the template?
Or what would be the best approach?
The model:
class Job(models.Model):
    job_title = models.CharField(max_length=200)
    job_identifier = models.CharField(max_length=140)
    job_site = models.URLField(max_length=200)
    job_url = models.URLField(max_length=400)
    job_salary = models.PositiveIntegerField(default=0, blank=True, null=True)
    def __unicode__(self):
        return self.job_title[:200]

class Skill(models.Model):
    skill_name = models.CharField(max_length=200)
    def __unicode__(self):
        return self.skill_name[:200]

class SkillMap(models.Model):
        job_id = models.ForeignKey(Job)
        skill_id = models.ForeignKey(Skill)
        def get_skills_mod(self, *args):
                return SkillMap.objects.filter(job_id = args)

Thanks,
Isaac
Comment: could you maybe add the actual code of models instead of describing them by words?
Answer: This is not very clean solution, but you can fetch all SkillMap at once in your view, create a dictionary with job_id as a key and then inject them into Job :p
from collections import defaultdict

def my_view(request):
    skills = SkillMap.objects.all()
    skills_dict = defaultdict(list)
    for x in skills:
        skills_dict[x.job_id].append(x)

    jobs = Job.objects.all()
    for job in jobs:
        job.injected_skills = skills_dict.get(job.id, [])

    template_context = {
        'jobs': jobs,
    }

template:
{% for job in jobs %}

{{ job.job_title }}

    {% for skill in job.injected_skills %}
         {{ skill }}
    {% endfor %}
{% endwith %}

Comment: Thanks, I'll try that tomorrow. If it's fast enough it's ok for me. I can try to make it better later.
Comment: I've just tried it and I'm getting the following error: "Job matching query does not exist." from line skills_dict[x.job_id].append(x). The dictionary is fully constructed. Any idea of why wouldn't it find the job_id from the table?
Comment: I dont know what data you have in your DB, but that error message is quite obvious, I think. Try to use `x.job_id_id` instead
Comment: Thanks! I'm getting to the template now, had to modify the last bit for template context but it's working now :-D

Django -- Custom filter or SQL raw


Ada Get_Line not waiting to get Response

Question: I have this strange problem in a program I have been working on. If I attempt to use get_line in Ada to solicit a response from the use after already doing a previous Q&A, the program does not wait for the response. I have put together a little demo program that replicates the issue. I can not use an unbounded string in my situation. I have instructions to use a bound string.
WITH Ada.Text_IO; USE Ada.Text_IO;

PROCEDURE StrPractice IS
   Name : String (1 .. 5);
   NextName : String (1 .. 10);
   Len  : Natural;

BEGIN
   Put("Enter first name? "); --5 digit terry
   Get(Name);
   new_line;
   Put_line("First Name: " & name);
   New_Line;

   Put("Enter next name:");
   Get_Line(NextName, Len);
   new_line(2);
   Put_Line("Next name: " & NextName(1..Len));
END StrPractice;

I am not sure what is causing this problem. I thought perhaps the buffer needed clearing, so I crated a character variable c and used get(c), but that did not correct my issue. I did a search here, but did not see the same situation. Any help would be appreciated.
Comment: You undoubtely are hitting Enter after you enter the `Name`, but `Get` does not consume the end-of-line.  So it's still there in the buffer when you call `Get_Line` later.  Try adding a call to `Skip_Line` to consume the end-of-line.
Comment: Bless you! Yep, That corrected the issue. I figured it was grabbing my enter, but for the life of me, could not figure out how to deal with it. Thank you very much!
Comment: OK, then I'll post it as an answer.
Answer: The problem is that when you enter the Name, you have to enter a newline before the program can see your input.  However, Get does not consume the newline; thus, when Get_Line is called, it sees the newline still in the input buffer and treats that as the end of the input line.  You can consume the newline by using Skip_Line:
Put("Enter first name? "); --5 digit terry
Get(Name);
Skip_Line;
new_line;
Put_line("First Name: " & name);
New_Line;


Close popup div if element loses focus

Question: I have the following scenario: On a label's mouseover event, I display a div. The div must stay open in order to make selections within the div. On the label's mouseout event, the div must dissappear. The problem is that when my cursor moves from the label to the div, the label's mouseout event is fired, which closes the div before I can get there. I have a global boolean variable called canClose which I set to true or false depending on the case in which it must be closed or kept open. I have removed the functionality to close the div on the label's mouseout event for this purpose.
Below is some example code.
EDIT
I have found a workaround to my problem, event though Alex has also supplied a workable solution.
I added a mouseleave event on the label as well, with a setTimeout function which will execute in 1.5 seconds. This time will give the user enough time to hover over the open div, which will set canClose to false again.
$("#label").live("mouseover", function () {
        FRAMEWORK.RenderPopupCalendar();
    });

$("#label").live("mouseout", function () {
        setTimeout(function(){
            if(canClose){
                FRAMEWORK.RemovePopupCalendar();
            }
        },1500);
    });

    this.RenderPopupCalendar = function () {
        FRAMEWORK.RenderCalendarEvents();
        }
    };

    this.RenderCalendarEvents = function () {
        $(".popupCalendar").mouseenter(function () {
            canClose = false;
        });

        $(".popupCalendar").mouseleave(function () {
            canClose = true;
            FRAMEWORK.RemovePopupCalendar();
        });
    }

    this.RemovePopupCalendar = function () {
        if (canClose) {
            if ($(".popupCalendar").is(":visible")) {
                $(".popupCalendar").remove();
            }
        }
    };

Any help please?
Comment: Do the mouseleave on the popped ''
Comment: Alex, I have already implemented a mouseleave on my div. That works fine. What happens is when i hover over the label, the div appears correctly, but when I move out of the label (to anywhere on the page without moving over the div), I need the div to close as well.
Comment: Not sure if I understood your question .. I have a question though . Why cant you show on mouseover label and hideon mouseout div itself? ,
Answer: I would wrap the  and
 in a containing
 then do all you mouse/hide events on that.
Check out this fiddle example - http://jsfiddle.net/6MMW6/1
Comment: position the 'dre' `div` absolutely also. Then give it a height. - http://jsfiddle.net/6MMW6/8/
Comment: Thanks Alex, I will have a look at your suggestion.
Comment: Your suggestion would work in some cases, except that in my case the div container (your "dre" div) is wrapped within another div. When you hover over the label, it will stretch the "dre" container to the height of the popup div. Which will result in the parent container also stretched.
Comment: I have updated your fiddle to illustrate what is happening: http://jsfiddle.net/6MMW6/6/
Comment: This might work, I'll check it out. Thanks Alex. How do I mark a comment as answered?
Answer: Give your popupCalendar an explicit ID instead of a class selector, e.g.

Reference it with #popupCalendar instead of .popupCalendar.
Now, remove() is quite drastic as it will completely remove the div from the DOM. If you wish to display the calendar again you should just .hide() it.
But your logic seems a bit overly complex, why not just .show() it on mouseenter and .hide() on mouseout events ?
Comment: Thanks Endy. To which element must I attach mouseenter & mouseout events? Remember, I need to show the div on the label's mouseenter, and hide the div again on mouseout (if i have not moved over the div yet). If I have moved over the div, the div needs to stay visible.
Comment: Bind the mouseenter to the label and mouseleave to the div. That way the div gets hidden when the mouse exits the div for the first time.
Comment: No luck yet Endy. The div still stays visible if I leave the label without moving over the div.
Answer: This will close the entire tab page if the tab page loses focus.
How ever if you target it, it can work for  something within the page too, just change the target codes.
JavaScript:

HTML:

Close popup div if element loses focus


Can gang power go lower than 4%?

Question: In Spiderman 3 for the PS2, there are gangs that control parts of the city, and each gang controls a certain percentage of the city. When you do the "crime patrols", this percentage goes down and some power is returned to the police. I did crime patrols on every spot I could find for the "Dragon Tails" gang, but when I got them down to two spots and 4% power, I couldn't do the patrols any more.
At first I was able to go up to the informant, but hitting triangle would just do nothing. But next time I played the game the informants disappeared and were not at the spots that the two dots showed on the map.
Is this just a glitch or is 4% the lowest you can force a gang's power to go? If it is the lowest, does that mean that they will still attack other territories and try to increase their power, meaning I can never fully eliminate them?
Answer: I've been playing the game for a while longer now, and it turns out I needed the Dragon Tails gang for the next mission. Once the mission was over, I was able to do more crime patrols for their gang, and once I took out their last spot I got the message "Gang Defeated", and received A LOT of exp. Now their gang is at 0% and probably won't be ever coming back.

Can gang power go lower than 4%?


Docker trust: how to sign image without pushing it to repository

Question: We run private docker registry, and I am trying to use notary to add image signing. I have notary set up, and Docker client can sign images as it pushes to the registry.
My problem is that we do not push to the same registry name we are pulling from. We use Nexus for hosting our docker images, and this is an artifact of the Nexus way of running private registry.
We push to docker-registry-publish.example.com  and pull from docker-registry.example.com
We cannot push to docker-registry.example.com
I cannot find a way to have docker, or notary, sign an image without pushing it first. What I would like to be able to do is something like this:
docker push docker-registry-publish.example.com/team1/app1:1.0
docker tag docker-registry-publish.example.com/team1/app1:1.00 docker-registry.example.com/team1/app1:1.0
$some_way_to_sign docker-registry.example.com/team1/app1:1.0

There is no 'docker sign' command, the only way for docker to sign an image is to push it, as far as I know. 'notary sign' needs a file, and I do not know how to feed it a docker image.
Is there a way to have either docker, or notary, just do the signing?
Thank you!
Answer: These are the steps I would do.
First, generate the key using docker trust key generate and name it ${key}
Then, load the key and add the signer for the image
docker trust key load --name ${key} ${key}.pub
docker trust signer add --key ${key}.pub ${key} docker-registry-publish.example.com/team1/app1:1.0

Next, build the image:
docker build --disable-content-trust=true -t docker-registry-publish.example.com/team1/app1:1.0 .

And then, sign the image:
docker trust sign docker-registry-publish.example.com/team1/app1:1.0

Verify the keys and signature:
docker trust inspect --pretty docker-registry-publish.example.com/team1/app1:1.0

And, finally, push it:
docker push docker-registry-publish.example.com/team1/app1:1.0


JVM: most simple way to alter code of a dependency library?

Question: Most of the time, I don't like Javascript and would prefer strict and compiled languages like Scala, Java, Haskell...
However, one thing that can be nice with Javascript is to be able to easily change code of external dependencies. For exemple, if you have a bug and you think it's one of your dependency library you can easily hack around and swap a library method by your own override and check if it's better. You can even add methods to Array ou String prototypes and things like that... One could even go to node_modules and alter the library code here temporarily if he wants to.
In the JVM world this seems to me like an heavy process to just get started:

Clone the dependency sources
Hack it
Compile it
Publish it to some local maven/ivy repository
Integrate the fixed version in your project

This is a pain, I just don't want to do that more than once in a year
Today I was trying to fix a bug in my app, and the lib did not provide me enough information. I would have loved to just be able to put a Logger on one line of that lib to have better insight of what was happening but instead I tried to hack with the debugger with no success (the bug was not reproductible on my computer anyway...)
Isn't there any simple alternative for rapidly altering the code of a dependency?
I would be interested in any solution for Scala, Java, Clojure or any other JVM language.
I'm not looking for a production-deployable solution, just a quick solution to use locally and eventually deployable on a test env.
Edit: I'm talking about library internals that are not intended to be modified by the library author. Please assume that the class to change is final, not replaceable by library configuration, and not injectable by any way into the library.
Comment: What you want is not directly possible, because the languages you mentioned are shipped by binaries and not by sources. Furthermore, because they are statically typed, it is required that all transitive dependencies are available at compile time. You can touch the binaries on the JVM with aspectJ, but it is difficult to use. Clojure is dynamically typed, maybe they have a solution for the binary distribution problem. But it wouldn't be anything you could use for other JVM languages. Overall you (we) are out of luck here.
Answer: I disagree that AspectJ is difficult to use, it, or another bytecode manipulation library is your only realistic alternative.
Load-time weaving is a definite way around this issue. Depending on how you're using the class in question you might even be able to use a mocking library to achieve the same results, but something like AspectJ, which is specifically designed for augmentation and manipulation, would likely be the easiest.
Answer: In Clojure you can re-bind vars, also from other namespaces, by using intern. So as long as the code you want to alter is Clojure code, that's a possible way to monkeypatch.
(intern 'user 'inc dec)
(inc 1)
=> 0

This is not something to do lightly though, since it can and will lead to problems with other code not expecting this behavior. It can be handy to use during development to temporarily fix edge cases or bugs in other libraries, but don't use it in published libraries or production code.
Best to simply fork and fix these libraries, and send a pull request to have it fixed in the original library.
When you're writing a library yourself that you expect people need to extend or overload, implement it in Clojure protocols, where these changes can be restricted to the extending/overloading namespaces only.


Is there a high temperature glue that I can use on a cook top?

Question: We have a 1 year old Frigidaire gas range (This model or a near sibling, purchased from Lowes).  The burner grates appear to be painted cast-iron, while the surface below them is a polished and painted metal of some sort.  To protect the lower surface from damage, the grates have several tiny feet.  I'm not sure if the feet are rubber or plastic; they have a texture which is kinda half-way between.
One of these feet has now fallen out.  It has a quarter-inch diameter rod piece, which fits into a hole in the cast-iron.  It doesn't look like anything broke (no residue from tabs on the back end of the foot) but it now freely comes out and won't stay.  So, I'm looking for ways to re-attach the foot.  I'm thinking maybe some form of high-heat industrial glue, which will bond to cast-iron and plastic.  Food safe would probably be a plus; not that it's in contact with food but if the glue gave off fumes when exposed to heat that would be bad.  Are there any glues which meet all these requirements?
UPDATE
I finally managed to talk to Frigidaire about this, and thought I'd update with the info they gave me in case anyone wants it in the future.
They do sell an adhesive for this; it's terribly expensive.  Also, these rubber feet things are not covered by warranty, which may explain why not many other people discuss this; it's a part that's expected to fail, and people just ignore it.  Personally, I kinda like my stove top level and un-scratched.
Similar to @Steven, they recommended a high-heat glue.  When I asked about heat requirements, they suggested shopping in automotive supply stores for glues suitable for car engines.  So I'm off to see how those compare.
Answer: A silicon based glue should be able to withstand these temperatures. Makes sure to verify the max temp on the package. Silicon glue
Answer: I was poking around some to see what other were saying about this because I am having the same issue with my stove after replacing some of the rubber feet.  Found something on Amazon that looks like it would work.  Thought I would share.
Red Devil Industrial Grade Heat Resistant Rtv Silicone Sealant
Product Description
Sold as each. 10.1 Oz. Cartridge. Red. When fully cured withstands -85 deg. to 600 deg. F (intermittent). Apply at 10 to 100 deg. F. Seals oven belts, heating elements in appliances, flanged pipe joints, fired heaters, access doors and drying ovens. For porcelain, ceramic, glass, marble, fiberglass, painted surfaces, non-oily surfaces and most metals. Resists cracking, shrinking, peeling and vibration. WIthstands +25% joint movement. Waterproof and weatherproof. Red. UL listed. Meets military spec MIL-A-46106A. Meets FDA regulation No. 21 CFR 1772600 when fully cured and washed. Authorized by USDA for use in federally inspected meat and poultry plants. Manufacturer's number: 0809/0I. Country of origin: United States. Distributed by Red Devil, Inc.
Comment: Dow Corning 736 High Temp RTV Silicone is another that would fit the bill. We use it in the aviation industry.
Answer: Sugru is a self-curing, food safe plastic that is relatively high heat tolerant. It's moldable which is a huge plus.


Practical Solution For Giant Spike Balls

Question: The dungeon has giant swinging spike balls that cause no end of frustration to explorers such as myself.  They dare to keep bold, intrepid, totally-not-thieving adventurers out of the depths with their inability to be destroyed!...Or do they?
I have tried removing the block that they rest on to no avail, but is there any practical way to remove the giant spike ball that plagues the dungeon?  Or, failing that, is there an elegant solution to dealing with these grossly annoying obstacles?
Answer: According to http://terraria.gamepedia.com/Spike_Ball:

They spawn and despawn off-screen like any other enemy — if you leave a room and return later, it will have a different configuration of Spike Balls.

So unfortunately, any steps you take to control an individual spike ball will be rendered moot when you leave and come back because the spike ball will almost certainly have moved.
EDIT:
Here's a way to potentially use this for your benefit: If there's a Spike Ball in an especially difficult position (say, so that it makes it impossible to get to a chest), you can leave the area and come back later. Unfortunately, since navigating the dungeon is nasty enough, this will only help with the worst Spike Balls.
Answer: According to here: Spike Ball
"It is possible to hurt and kill the Spike Ball with the Thorns buff using the Thorns Potion."
Comment: I'm not sure I'd call that practical, though; they respawn just like normal enemies, and you have to take damage in order to "kill" them. At that point, it's still probably easier to just avoid them or eat the damage as you run past. :)
Comment: While it's still in the game, it might be semi-useful for extended dungeon delving, assuming they don't respawn TOO quickly.
Comment: That's also listed as an anomaly, so it may be patched out later.
Comment: Yeah I haven't ever tried to destroy them.  I just would rather tank the damage.  But as of now it seems Thorns are about the only way to damage them.
Answer: By experience, it seems that spike ball despawn quickly enough when going off screen. Mining the center block might help with that.
But you'd have to evade them once, or maybe go back.
Answer: The spike ball, as of most recent patches, cannot be killed through damage. Since it passes through blocks, it cannot be halted or blocked.
Spike balls only spawn in the presence of a hanging Marching Bones banner. This is a hidden secret of much of the dungeon. Most of the problem enemies only spawn under certain banners.
Have you ever noticed how many banners there are in the dungeon?
Have you ever noticed how (while the spawn rate is high everywhere) certain problem enemies seem to only appear in certain areas?
Banners work similarly to some statues. In that placing them in certain areas/biomes can cause certain enemies spawn rates to skyrocket. This can be manipulated to farm certain enemies.
The dungeon is filled with unique banners only found in the dungeon. Removing these banners will limit or eliminate the spawn potential of certain enemies, such as Spike Balls, Dark Casters, and Cursed Skulls (not sure about the dragon skull variety).
Removing the Water Candles from the dungeon also has an effect on reducing enemy spawn rates nearby. This affects all enemies (except Spike Balls, because their spawn is tied directly to the Marching Bones Banner). However, even with full torchlight, removal of all banners and Water Candles, it is impossible to eliminate the enemies' spawn completely without removing the dungeon biome (less than 40 green brick/wall in a screen area).
Best bet for avoiding Spike Balls is to identify and remove all Marching Bones banners. And all other Banners while you're at it.
Sources:
Personal Experience.
Official Terraria Wiki.
By the way, most questions you ever have are much more quickly and efficiently answered by visiting the Official Terraria wiki (just google Terraria Wiki). You also usually end up with answers to questions you didn't have. I, nor my controllers would ever have survived the transition from normal to Hardmode without that site. Covers all platforms.
Enjoy!
Comment: The banners in the dungeon merely indicate which types of enemies will spawn. They have no effect on the actual spawn rates. Water candles, on the other hand, do have an effect, so removing them is a way to reduce the spawn rate.
Comment: Neither banners nor statues affect spawn rates. [Spike balls](http://terraria.gamepedia.com/Spike_Ball) spawn at random like any other enemy. The [Marching Bones banner](http://terraria.gamepedia.com/Banners_(decorative)#Faction_Flags) is purely decorative. Some [statues](http://terraria.gamepedia.com/Statue) can be activated to spawn enemies, but they don't do anything on their own. This entire answer is highly misleading, except for the part about Water Candles.


Aligning text in java JPanel

Question: I am a new student of java.This is a college project, a math test in a gui.
I have problems with alignment.
I would like to do this in my gui when I run the program
                        Math Test - 10 exercises  (this in the middle)
                           about 2 spaces here

1. How much is one added to one?  ( this is an example. the math problems are going to be word problems with several sentences.)

a space here

Your answer, please.   here goes a JTextField (4)

about 2 spaces here

2.  here goes exercise number 2

etc. etc.

What do you think is better for the math word problems JLabel or JTextArea?
here I imported swing and awt
public class MathTest extends JPanel
{
    public JTextField stu;

    public MathTest() {
         JLabel m=new JLabel ();
         m.setText ("Math Test - 10 exercises");
         add(m);

         JLabel exone= JLabel();
         exone.setText("1. how much is one added to one?");
         add(exone);

         JLabel y= new JLabel();
         y.setText ("Your answer, please.");
         add(y);

         stu= JTextField (4);
         add(stu);
    }
}

The programs works but I cannot align the labels and the JTextfield.
Thank you.
Comment: You'll want to look into using a [`LayoutManager`](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). My personal recommendation is the very flexible [`MigLayout`](http://www.miglayout.com/). It takes a little while to learn, but is well worth it.
Comment: It might help to take a screenshot of what it looks like now and then draw a picture of what you want it to look like.
Answer: you can use
setSize(x,y);

dimension according to your choice
or simply use Net bean editor that can provide facility for drag and drop
Answer: If you dont want learn any layout manager. Use absolute layout for a Jpanel.
Then you can place your label wherever you want.
Jpanel.setLayout(null);
JLabel lb=new JLabel("hi");
lb.setBounds(x,y,width,height);

Aligning text in java JPanel


In a Kubernetes watch operation for list of pod, are resourceVersion guaranteed to be monotonically increasing?

Question: From Kubernetes API Concepts > Efficient detection of changes:

When retrieving a collection of resources (either namespace or cluster scoped), the response from the API server contains a resourceVersion value. The client can use that resourceVersion to initiate a watch against the API server.
When you send a watch request, the API server responds with a stream of changes. These changes itemize the outcome of operations (such as create, delete, and update) that occurred after the resourceVersion you specified as a parameter to the watch request. The overall watch mechanism allows a client to fetch the current state and then subscribe to subsequent changes, without missing any events.

When I tried a watch operation (using kubernetes python client) I get a stream of kubernetes events, the events themselves do not have a resourceVersion, the object inside the event (kind: Pod) do have resourceVersion.
from kubernetes import client,config,watch
config.load_kube_config(context='eks-prod')
v1 = client.CoreV1Api()
watcher = watch.Watch()
namespace = 'my-namespace'
last_resource_version=0
for i in  watcher.stream(v1.list_namespaced_pod, namespace, resource_version=last_resource_version, timeout_seconds=5):
   print(i['object'].metadata.resource_version)
   last_resource_version = i['object'].metadata.resource_version

The resource version are output in the order they are received and they are not monotonically increasing at least in the initial batch of events:
380744163
380641499
380710458
380775853
380525082
381044514
380676150
380641735
380566799
380806984
380566585
380710721
378885571
380524650
380710218
380806798
373502190
380566206
381044372
380524615
380676624
380806573
380775663
380605904
380743917
380606153
380676388
380744368
380641258
380775416
380606397

But can I assume that if this watch is disconnected I can safely resume from the highest resource version I've seen? In the above case, can I safely resume from 381044514 (the highest)  without missing events?
Answer: From Resource Version Semantics

You must not assume resource versions are numeric or collatable. API clients may only compare two resource versions for equality (this means that you must not compare resource versions for greater-than or less-than relationships).

So in principle no you can't use the "highest" resource version because they are not really numeric or sortable. The best you can do is use the latest resourceVersion that you received as is , verbatim. And be prepared to get a resource too old that you are supposed to handle by retrying without specifying a resource version, in that case you must also handle the case where you will likely receive some events more than once.
This scenario where the resourceVersion in the last event received is not the actual latest/most recent is easily reproducible in EKS 1.21 where the initial response to the watch will return the events in more or less random order. If I send two watch requests simultaneously I'll get the same 30 events but in different order.


JFreeChart PeriodAxis :29 minutes fractions

Question: I am trying to use PeriodAxis in a chart to graph some time series data. The first data point occurs at 2012-01-08 19:00:00 and the final data point occurs at 2012-01-09 19:00:00.
When the chart is drawn, the tick labels start at 19:29 and end at 19:29. I want them to start at 19:00 and end accordingly -- that is, I don't want the :29 minute fractions. I have tried to set the tick label increments to 1 hour increments using setStandardTickUnits(), but that didn't change anything. I can't seem to find any other methods for this class that would allow me to change the tick units.

Sample code:
PeriodAxis domain = new PeriodAxis(null, new Hour(19, new Day(8, SerialDate.JANUARY, 2012)),
            new Hour(19, new Day(9, SerialDate.JANUARY, 2012)));
domain.setAutoRangeTimePeriodClass(Hour.class);
PeriodAxisLabelInfo[] periodLabels = new PeriodAxisLabelInfo[2];
periodLabels[0] = new PeriodAxisLabelInfo(Hour.class, new SimpleDateFormat("HH:mm"));
periodLabels[1] = new PeriodAxisLabelInfo(Day.class, new SimpleDateFormat("MMM dd, yyyy"));
domain.setLabelInfo(periodLabels);

domain.setLowerMargin(0);
domain.setUpperMargin(0);
TickUnits tu = new TickUnits();
tu.add(new DateTickUnit(DateTickUnit.HOUR, 1));

domain.setAutoTickUnitSelection(true);
domain.setStandardTickUnits(tu);

Answer: In your case, the chart starts at 19:00, and the tickUnit is 1 hour.
The issue here is that the PeriodAxis divides the horizontal axis in 24 periods, each period being represented by an org.jfree.data.time.Hour object. It then displays a label at the middle of the period : 19:29, 20:29...
In order to get what you want, you can either use a DateAxis instead of PeriodAxis, or use "hh:00" as a date format, which will replace the minute by 00.
Comment: I need to use the PeriodAxis so i will set my date format to "hh:00". Thanks.


Count records in each month using Month(dateField) in SQL

Question: I have a large table containing c650,000 records. They are individuals with email addresses and one of the fields is 'dateOfApplication'. I have been asked for a breakdown of how many people signed up in each month.
I'd like the results to look something like
Month     Year     Total
1         2017     50763
2         2017     34725

And have made a target table in this format to put the results in. I've been able to use Month(dateOfApplication) to get the month component of the date using
SELECT DISTINCT
(SELECT COUNT(1) FROM [UG_Master]
WHERE MONTH([UG_Master].dateOfApplication) = '6') as Total

To return particular months, but don't really know how to get one row for each month it finds.
Comment: Hint:  `GROUP BY`.
Comment: Which dbms are you using? (That query is product specific.)
Answer:
but don't really know how to get one row for each month it finds.

You can use GROUP BY  :
SELECT MONTH([UG_Master].dateOfApplication), COUNT(1)
FROM [UG_Master]
GROUP BY MONTH([UG_Master].dateOfApplication);

If you want year wise months then include year also :
SELECT YEAR([UG_Master].dateOfApplication), MONTH([UG_Master].dateOfApplication), COUNT(1)
FROM [UG_Master]
GROUP BY YEAR([UG_Master].dateOfApplication), MONTH([UG_Master].dateOfApplication);

Comment: what if they have records from previous years, it's seemed to me like you also need to group by the year column right?
Comment: Wonderful - worked perfectly, thanks. I'd forgotten about Group By, but still wasn't on the right lines until this! Thanks.


What is advantage of using Object.assign()?

Question: what is advantage of using Object.assign() compare with direct assign?
e.g>
Object.assign(obj, {a: true});
obj.a = true;

Answer:
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Which means you can assign multiple values at a time

It is also super handy for copying whole objects. It's often used to merge "option" objects with some default values (similar to _.extend).

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Comment: Also super handy for copying whole objects. It's often used to merge "option" objects with some default values (similar to _.extend)


Story Mapping: How to write initial epics and user stories?

Question: We are trying to do a story mapping session for a new project (a student portal).
Since this is my first time doing this and we don't have a business analyst in the team that could help me, I'm struggling with how to write the epics and the user stories. I've seen examples of these but for eCommerce or an email (example attached below).

Image Source
I would like to know how would you write the epics or user stories for a student portal? What would you write? has anyone here have experience with this that could provide me some initial map or idea?
For example: In our student portal students should login, go to classes, view school news, etc. How could this map to epics and user stories?
Answer: You want to do this from the point of view of the user. Imagine one of the students is sitting down with you explaining what they would use the portal for. For example, a student might say something like this:
"Those first couple days of classes are so confusing. I can never remember the exact times and classroom numbers of my classes. I wish I could just look them up quick on my phone. Oh, and I never realize I've forgotten the classroom until right before class, so it can't be a pain in the butt to navigate to the information."
Great, now let's turn that into a user story:
As a new student new to a class, I want to be able to quickly access the time and location of my classes so that I don't have to remember them.
That last sentence I don't think I'd even try to phrase in the "As a, I want, so that." form. I'd just present exactly that problem to the team and brainstorm some ideas to solve it.
Rapid/Paper Prototypes
I highly recommend making use of simple paper prototypes. This will allow you to play ideas out quickly and you'll find usability flaws and opportunities long before you invest a lot of time and money building the application.
Answer: I think you are probably on the right track - Write a narrative, a step by step from one person's perspective from Logging in, to getting familiar with the portal, to finding what they need, and submitting data (course changes, questions)  These are steps going across as a testable, demonstrable, potentially releasable plan.
the way to divide it up into columns is to find the themes emerging.  the Story to change a password is similar to changing their username, both for Account Setup.  So you may end up with a Epic for Account Setup.
Answer: This write-up is, in my opinion, the best intro to story mapping at agilevelocity.com, [2017-08-09]:
Story Mapping 101, By David Hawks
I did extensive search for various ways to understand story mapping.
This blog post was the best source I could find.
Here is a sum up of the strongest points, most relevant to answer the question:
Initial story map draft

Try to convey the sense of a workflow.
Try to recognize and avoid gaps so that the business contexts remains clear.
Jeff Patton coined the idea of story maps aiming to tackle user experience requirements.
Develop the requirements in collaboration with the stakeholders.
Walk through the problem, with the Subject Matter Experts (SME) to tell a story of activities and tasks they would perform. If there's more than one SME have each to write and then merge stories  together.
Use post-it notes to pin the story horizontally to the wall: this is a draft, to be re-shaped.

Creating a working story map

You should already have a set of activities and tasks on board.
Group activities to be done together, or if you have options to follow a certain path.
Search for gaps in stories. View as different user personas, and scenarios.
Detect important items and set on top position on board.
Place levels of priority vertically: must, should, could.
Now your map should allow different iterations. Estimate and refine your work scope.

Update

Showing the progression to stakeholders helps to keep track of progress.
Tracking changes at sprint reviews is more informative than communicating backlog.
You not only keep track of requirements but also give continual visibility.
Also check how to transform a backlog into a story map: Course 201.

Also, with more time and detail, I strongly recommend Jeff Patton' book:
User Story Mapping: Discover the Whole Story, Build the Right Product.
Answer: I wanted to ask a question somehow associated to what's being dicsussed here. We have ran a design sprint after the end of which we managed to test a simplified flow of the designs elaborated with 14 users. We are now bringing those learnings into the design making sure that we address those feedback in the design.
QUESTION: how would you move from the design into planning the dev work? I was thinking of running a similar activity to a story mapping mentioned here, taking the designs as starting point breaking it down by key Tasks with the steps associated to it.
Doe this make sense? Has anybody ran a similar exercise?
Comment: Great addition to the original question! It's been 4 years since I wrote this post and since then in my experience story mapping is an excellent activity that helps bridge the initial project definitions with creating an initial development backlog.  I've also seen people creating the backlog with spreadsheets but story mapping being so visual and spatial has always worked very well for our teams. So well that other teams has followed this approach too! We always create a story mapping and then we start moving the epics and stories in the postits to a management tool like JIRA or Zenhub.


How to select random three rows in Sybase against value check for other column

Question: I have a table like below with approx 1 million rows.
col2 has all the alphabets(consonant + vowels)
col1 has random words
COL1          COL2 ......
val1          A
val2          A
val3          A
val4          A
val5          B
val6          B
val7          B
val8          B
.             .
.             .
.             .
.             .
.val100000    Z

Now i want to get the result as random three rows with col2 in (A,E,I,O,U)
As a hack I used min and max function to get the two numbers.But that doesn't behold the random property.
Any help would be greatly appreciated here.
Answer: you can use NEWID(),
like this
select *
from (select row_number() over (partition by col2 order by NEWID()) rownum, m.*      from myTable m
where m.col2 in (A,E,I,O,U)) sel
where sel.rownum=1

Comment: THis is giving me just one row against A.
Comment: Better use ORDER BY RAND2()


How would I intuitively know to use a function of x or y?

Question: I'm doing fine with solving solids of revolutions using disk, washers and shells, but often times I get confused with making the problem a $f(x)$ or $f(y)$.
I think when one is using disk and washers, you use $f(x)$ if you are rotating the solid around the $x-axis$ and $f(y)$ if the solid is rotating around the $y-axis$.  But when using shells, how do I pick which to use?
He is a sample problem that I drew out graphically and felt like I could use $f(x)$ or $f(y)$ but the solution shown only shows the options of using $f(x)$
Set up the integral to find the volume of the solid created by revolving the region bounded by $y=x^2$, $y=0$, and $x=3$, about the y-axis, using the method of shells. DO NOT EVALUATE THE INTEGRAL!
I guess is my confusion is when looking at the functions graphically it seems like I can get a value by examining the function at both $x, y$, but clearly that's not correct.
Do you have any advice for me?
Answer: If rotating around the $y$-axis, use $f(x)$, if rotating around the $x$ axis, use $f(y)$
When rotating around the $y$ axis the equation for integration is $$2\pi \int_{a}^{b} x f_h(x) dx$$ where $f_h(x)$ gives the height of the function.   Conversely, when rotating around the $x$ axis,
We see that we must put the height in terms of $y$. As a result the formula changes to
$$2\pi \int_{a_y}^{b_y} f_h(y) dy$$ and we must also remember to change $ a \to a_y$ and $ b \to b_y$
Comment: Wow thank you so much for this!


Defining an index combining two tables with Djapian

Question: I've got the following Restaurant and Comment models. I'm doing full text search on some fields of the Restaurant model, as shown below in the RestaurantIndexer class. How can I do a full text search including the comments (i.e. a search returning Restaurant instances with the query contained in one or some fields defined in RestaurantIndexer or in the comment field of Comment instances)?
*********Restaurant model***************
class Restaurant(models.Model):

    name = models.CharField(max_length=100)
    country=models.ForeignKey(Country)
    city=models.ForeignKey(City)
    street=models.CharField(max_length=100)
    street_number=models.PositiveSmallIntegerField()
    postal_code=models.PositiveIntegerField(blank=True,null=True)
    category=models.ManyToManyField(Category, blank=True,ull=True)
    slug = models.SlugField(unique=True)

*********Comment model***************
class Comment(models.Model):

    user = models.ForeignKey(User)
    restaurant = models.ForeignKey(Restaurant)
    submit_date = models.DateTimeField(blank = True, null = False)
    comment = models.TextField()

*********Restaurant indexer***************
class RestaurantIndexer(Indexer):
    tags = [
        ('name','name'),
        ('city','city'),
        ('country','country'),
        ('category', 'category'),
        ('tag','tag')
    ]

#how can I add Comment.comment?

space.add_index(Restaurant, RestaurantIndexer, attach_as='indexer')

Comment: What do you use for indexed search?
Answer: Djapian supports a dot notation to resolve fields and the path parts of tags in Indexer declarations. It also supports callables and using their result.
However, you don't need any of that since you just need to get all comments for a restaurant, you may simply do:
class RestaurantIndexer(Indexer):
    tags = [
        ('name','name'),
        ('city','city'),
        ('country','country.name'),
        ('category', 'category'),
        ('tag','tag'),
        ('comments', 'all_comments_text'),
    ]

class Restaurant(models.Model):
    # ... fields

    @property # could also be a method, since callables work
    def all_comments_text(self):
        return " ".join(map(lambda x: x.comment, self.comment_set.all()))

Note that this simply joins all comment fields on all related comment objects with a space. Should do for indexing, though.
Comment: Thank you stefan, again python saved the day for me!


I keep getting the error "canvasContext.fillRect" in this following code

Question: Every time I run the app and open the console this error "pong.js:25 Uncaught TypeError: canvasContext.fillRect is not a function at drawEverything (pong.js:25)" keeps coming up every second, at first I thought it was because I didn't spell "fillRect" properly, but I cannot figure out why this is happening, any ideas? Thanks
var canvas
var canvasContext;
var ballX = 50;

window.onload = function() {
    canvas = document.getElementById('gameCanvas');
    //get context to draw on
    canvasContext = canvas.getContext('2d');

   setInterval(drawEverything, 1000);

}

function drawEverything() {
    ballX = ballX + 20;

    console.log(ballX);
    canvasContext.fillStyle = 'black';
    canvasContext.fillRect(0,0,canvas.width,canvas.height);

    canvasContext.fillRect = 'white';
    canvasContext.fillRect(225,210,200,200);
    canvasContext.fillStyle = 'red';
    canvasContext.fillRect(ballX, 200, 50, 25);

}

Answer: your are overriding your fillRect function with string
canvasContext.fillRect = 'white';


Showing a function is bijective and finding the inverse.

Question: The function is as follows:
$$F:D^2(0,1) \rightarrow \Bbb R^2$$
$$ F(x)=\begin{cases}\tan\left(\frac{\pi||x||}{2}\right)\frac{x}{||x||}&, x\neq0 \\ 0  & ,x=0 \end{cases}$$
I am trying to show this is function is 1:1 and onto on the open disk of radius 1 and centered at 0 in 2 dimensions to a disk of infinite radius. I have tried to represent the magnitude using coordinates but I don't think I am approaching the problem correctly. Any advice would be appreciated
Comment: I hope the edit is correct. Feel free to roll back if not
Answer: Informally speaking, the key is that this function acts radially: it only scales each vector $x$ by a numerical factor along the same line. So as long as it's one-to-one and onto on each line thru the origin, by mapping the "$[0,1]$" segment of that ray emanating from the origin onto the entire ray, the same is true for the map as a whole. (These lines have the origin in common, but it's dealt with separately in the definition of this function anyway.)
More rigorously, we could switch to polar coordinates: represent each $x\in\mathbb{R}^2$ as $x=(r\cos\theta,r\sin\theta)$ with $0\le r$ and $0\le\theta<2\pi$ to avoid ambiguity. The domain of this function is then $D^2(0,1)=\{x=(r\cos\theta,r\sin\theta) \mid 0\le r<1,0\le\theta<2\pi\}$. And the function simplifies into
$$F(x)=F[r,\theta]=\begin{cases}\tan\left(\frac{\pi r}{2}\right)\cdot(\cos\theta,\sin\theta)&, r\neq0 \\ 0  & ,r\end{cases}$$
or even purely in polar coordinates (using brackets for polar coordinates to avoid confusion with cartesian coordinates)
$$F(x)=F[r,\theta]=\begin{cases}\left[\tan\left(\frac{\pi r}{2}\right),\theta\right]&, r\neq0 \\ 0  & ,r\end{cases}$$
Now we can see that points with different polar angles $\theta$ will have different images under this function. And for a fixed $\theta$ and assuming $r\neq0$, the function $r\mapsto\tan\left(\frac{\pi r}{2}\right)$ maps $(0,1)$ onto $(0,+\infty)$ in a one-to-one fashion.
Comment: Hm interesting I didn't think to use polar coordinates. This simplifies it a lot. It still is not obvious to me how to get an inverse formula though.
Comment: Using $\arctan$.
Comment: is it simply [2arctan(y)/pi,theta]
Comment: It should be (when y doesn't equal 0). I verified it by plugging each one into the other and checking it was the identity. Thanks for the help and insight.
Comment: @numtheory1555242: Yes, that's right (the inverse, I mean). And then it can also be expressed in terms of $y$ similarly to how the original function was given: $F^{-1}(y)=\left(\frac{2\arctan(\|y\|)}{\pi}\right)\frac{y}{\|y\|}$ for $y\neq0$. You're very welcome!


Can I install two chef clients on a Linux server so that both two clients can manage the linux server?

Question: I want to install one chef client on a linux server to manage the server by executing shell command. While there is a reboot command in one of the recipes in the run list, and the rest recipes don't continue to execute after the server reboot. As I haven't found a way to solve it, I wonder if I can install two chef clients on a Linux server and execute different recipes so that the rest recipes can continue to execute after the server reboot. Anyone can help? Thanks.
Comment: Welcome to Stack Overflow! Unfortunately questions like these are [off-topic](https://stackoverflow.com/help/on-topic) for Stack Oveflow, and therefore should be asked here:
[SuperUser](https://superuser.com) ot here: [Unix and Linux](https://unix.stackexchange.com).
Answer: Putting two clients on a single device, or two Configuration Management tools on the same box in general, is a Bad Idea. Even if you could do it the cognitive load increase from determining when to update what where going forward is going to open you up to mistakes.
The proper approach is to put restart flags in your recipes; before you call the restart resource you set a flag (which can be a files contents or even existence, an environment variable, or any number of other persistent data objects) to indicate that a restart was performed. If its to be periodic you can instead look at something like the last time a file was accessed with its atime property. Then you do logic around your steps that require a reboot, guarding against a reboot if the flag no-restart flag is set or triggering it if you have a restart flag set, your choice. That way you'll have a chef converge with a restart that skips part of your runlist, then later another run that skips the unnecessary restart process.
Another good option is to just pay more attention to how you have your resources ordered. If the restart is in your last runlist item and is notified with the :delayed timing then it will be the last run resource, meaning the rest of your recipes would have already converged. If you need a complete converge every time then that is the option you should embrace.
Option 1 is a Ruby-centric solution and will require you to embrace dev work. Option 2 is more pure Chef with some Ruby sprinkled in and you can read up on notifying resources in the docs here: https://docs.chef.io/resource_common.html#notifications
There is an option 3 where you change the runlist during the chef run, which you could use to remove the recipes that require the reboot, but I think you'd benefit more from option 1 or 2.


Compile-time performance difference between if(flag) and if(flag !=0)?

Question: Is there any performance difference between
if (flag) {...}

or
if (flag!=0) {...}

Considering both compiler execution time or resources needed.
Comment: Then yes there's a difference, but you need an *extremely* high resolution clock to be able to notice the difference. Or have millions or even *tens* of millions of such statements in a single source file. And there might even not *be* a (measurable) difference, since the the compiler must do different things for the two different expressions, and those differences might outweigh each other.
Comment: Types, types...
Comment: To clarify, you're not asking about the resulting code being generated by the compiler, but about the compilation process itself?
Comment: More text means the compiler has to parse more text. Might be a couple of nanoseconds in difference there.
Comment: @Some programmer dude YES
Comment: To be fair, the author is clearly asking about the _performance differences_ of the two approaches, while the linked duplicate seems exclusively about questions of style, readability, maintenance, etc. The author could have made it clear in the title though, rather than leaving it to the last sentence.
Answer: No, there is no practical difference, if flag is an integral type.


Given matrices $A$ and $B$ solve for $P^{-1}AP=B$

Question: Given
$A =
\begin{bmatrix}
0 & 1 & 0\\
0 & 1 & 4 \\
0 & 0 & 2
\end{bmatrix}
$ and
$B=\begin{bmatrix}
0 & -2 & 3\\
0 & 1 & -1 \\
0 & 0 & 2
\end{bmatrix}$. Find $P$ such that $P^{-1}AP=B$.
Initially I wanted to set this up in the same way you would solve this as a eigenvectors/diagonalizable problem. Since $B$ is not a diagonal matrix, setting the columns of $P$ as the eigenvectors won't help us.
One thing that I noticed is that $A$ and $B$ have the same eigenvalues.  (I am not sure if this is important or not.)
Comment: if $QBQ^{-1}=RAR^{-1}$, then $B=Q^{-1}RAR^{-1}Q=P^{-1}AP$ with $P=R^{-1}Q$
Comment: don't see how this helps me solve for $P$. As I would need to guess and check until I get two matrices that work
Comment: if you know how to diagonalize $A$ and $B$, you don't need to "guess and check"
Comment: @J.W.Tanner Im just a bit confused by how you got $QBQ^{-1}=RAR^{-1}$. We know that the diagonal matrix is $D = Q^{-1}AQ$ and $D = R^{-1}BR$. Putting this together gives us $Q^{-1}AQ = R^{-1}BR \iff RQ^{-1}AQR^{-1} = B$. But that is different then what you used.
Comment: Your $Q$ is the inverse of my $R$.  Using your notation, we have $Q^{-1}AQ=R^{-1}BR$, so $P^{-1}AP=B$ when $P=QR^{-1}$
Answer: Similarity is an equivalence relation on the space of square matrices.
If you can diagonalize $A$ and $B$ to the same matrix $D=Q^{-1}AQ=R^{-1}BR$,
then $RQ^{-1}AQR^{-1}=B$, so take $P=QR^{-1}$.
You can change coordinates from one basis to another
if you can change both of them to eigenvector coordinates.


A Problem Ocurred While Checking for Updates [Ubuntu 18.04]

Question: It keeps appearing this red signal in the top right of my screen with this error. If I run sudo apt update all I got is:
Hit:1 http://ppa.launchpad.net/oibaf/graphics-drivers/ubuntu bionic InRelease
Hit:2 http://archive.ubuntu.com/ubuntu bionic InRelease
sh: 1: /usr/lib/cnf-update-db: not found
Reading package lists... Done
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/lib/command-not-found/ -a -e /usr/lib/cnf-update-db; then /usr/lib/cnf-update-db > /dev/null; fi'
E: Sub-process returned an error code

Thanks.
Comment: please edit your question to include your OS and version
Answer: This should help you fix your problem. Please check, if ls -la /usr/bin/python is pointing to python 2.x or 3.x first.
Comment: it points to 2.7 and runned sudo apt-get -f install but then happens the same...
Comment: now I think it goes beyond this. python may be totally broken because I cant open any software or update program without saying that it is misses something ou there no such file or directory... neither terminal. i'm using xterm


Error **Uncaught TypeError: Cannot read property 'noun' of undefined** while fetching data from json

Question: I am trying to fetch data from url, but I am facing an error

Uncaught TypeError: Cannot read property 'noun' of undefined**,

Can anyone tell me why this error is appearing?
https://codepen.io/Thakur92411/pen/bZMObY?editors=1011

var googlelink = "https://googledictionaryapi.eu-gb.mybluemix.net/?define=apple&lang=en";

$.getJSON(googlelink, linkdata);

function linkdata(worddata) {
  console.log(worddata.meaning.noun.defination[0])
}

Comment: [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/a/358993/3082296)
Answer: worddata and noun are not objects. They are both arrays. Use
worddata[0].meaning.noun[0].definition

Here's a snippet:

let googlelink = "https://googledictionaryapi.eu-gb.mybluemix.net/?define=apple&lang=en";

function linkdata(worddata) {
  console.log(worddata[0].meaning.noun)
  console.log(worddata[0].meaning.noun[0].definition)
}

$.getJSON(googlelink, linkdata);

Answer: Everything looks good, the only problem is that you are not reading the response correctly. Once see the below code for your reference.
apiLink = "https://googledictionaryapi.eu-gb.mybluemix.net/?define=apple&lang=en";
$.ajax({
  "url": apiLink,
    success: function(response){
    console.log(response[0].meaning.noun[0].definition);
  }
});

Comment: How is this different than the answer which is already posted? Please don't add extra noise.


Problem getting value of text input in react native

Question: I've tried to console.log the value of the text input but I get the error "undefined is not an object (evaluating 'this.state.inputValue')". What's the problem? Thank you!
class SearchScreen extends React.Component {
  state = {
    inputValue: "",
  };

  search() {
    console.log(this.state.inputValue);
  }

  render() {
    return (
          <View>
            <TextInput
              onChangeText={
                ((inputValue) => this.setState({ inputValue }),
                this.search)
              }
              value={this.state.inputValue}
            />
          </View>
    );
  }
}
export default SearchScreen;

Answer: The problem is in the way you've implemented it. Please try as below...
class SearchScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
    };
  }

  search() {
    console.log(this.state.inputValue);
  }

  render() {
    return (
      <View>
        <TextInput
          onChangeText={(inputValue) => {
            this.setState({ inputValue });
            this.search();
          }}
          value={this.state.inputValue}
        />
      </View>
    );
  }
}

export default SearchScreen;

Comment: Thanks, it works. One last question: if I write in the input "hello" the console retrieves "hell" (the last word is always missing unless I type something else or click the spacebar). Do you know why?
Comment: @Unaidu Yes, that's because `this.search()` gives the result BEFORE the state value is updated. It takes a little time to update the state. (Microseconds) But, the search function is executed before the state is updated. So, you always see until one before last letter in your console.  But, you don't need to worry. The state value is already updated.
Answer: This problem occurred because two things.
First:
The this.setState is a async function.
If you pass a function after the setState this will work like a .then() in a promisse.
Second:
If you pass one function after another separating them by ',' the rightmost function will be executed first
You can resolve this doing something like that:
onChange={ inputValue => {
  this.setState({ inputValue });
  this.search();
}}

Or you can try something like that:
class SearchScreen extends React.Component {
  state = {
    inputValue: "",
  };

  search = () {
    console.log(this.state.inputValue);
  }

  setSearch = inputValue => {
    // The function 'search' will be execute after the state was set

    this.setState(
     { inputValue },
     () => this.search()
    );

  }

  render() {
    return (
          <View>
            <TextInput
              onChangeText={ inputValue => this.setSearch(inputValue) }
              value={this.state.inputValue}
            />
          </View>
    );
  }
}
export default SearchScreen;

Answer: You didn't set the value of state property. provide a value to setState.
this.setState({property : value})
Comment: You can use that syntax if the variable has the same name as the property, see [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) on 'New notations in ECMAScript 2015'
Answer: The problem is this line:
onChangeText={
    ((inputValue) => this.setState({ inputValue }),
    this.search)
}

You can use the short function notation only when your function has one statement:
(inputValue) => this.setState({ inputValue })

You actualy have 2 statements though, so you need to create a full function block using {}
(inputValue) => {
    this.setState({ inputValue })
    this.search()
}


Tableau - API Call to Show Everything a User Has Access To

Question: is there an API call, or a link of API calls in which I can show the following structure
<code>Sites User Has Access To
 - Projects User Has Access To
 -- Workbooks User Has Access to
 --- Views User Has Access To (Including Thumbnails)
</code>
I'm currently using a mix of the API and directly accessing (not strictly true but that's another story) the PostgreSQL DB. It works and it s pretty neat hack, but I'd rather avoid hacks
I was using 8.3 but now on the latest v9 release
Thanks
Answer: I'm using Tableau API to do this, it seems pretty straightforward, but maybe I'm missing something.
Following API reference:
Tableau REST API reference

Sign in and impersonate, use retrieved token in following API calls
Query sites
For each site query workbooks
For each workbook query views
For each view download preview image
Sign out
Comment: My point was the need for one single call rather than, as in your example, multiple calls
Comment: The "link of API calls" part threw me off. As for doing something like this in a the single API call - sorry I'm not aware of anything like this in Tableau.
Comment: How would I view what projects a user has access to?
Comment: Provide that user's id during sign-in (user-to-impersonate) : http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Sign_In , use returned Token to query Projects with Tableau REST API, it should do the trick.
Comment: The problem I have is that NT authentication is used on the website so can't pass username/password to authenticate, just username.
Comment: Looks like I don't fully understand what is your Tableau setup. If you use Active Directory it should be possible to set it up as a authentication method in Tableau, no impersonation should be required. If you use AD just for website, then I would need to know how are you synchronising users between Tableau and your website and what authentication method do you use to access Tableau. Maybe we could move this discussion somewhere else, comments are a bit limiting. I've updated my profile info.


Real-time linting of Python with VSCode

Question: Recently I'm using VSCode as my Python IDE, and I install
DonJayamanne/pythonVSCode, which supports linting. However, the linter only works when saving, but what I want is real-time linting. The workaround suggested by the author is to set files.autoSave to on, so that the linter will work whenever the file is automatically saved. There's a relevant discussion on Github, for your reference.
Since I don't want to turn on auto-save function, is there any way to do real-time linting of Python with VSCode? Or is there any suggested extension?
Comment: answer was received here. https://stackoverflow.com/questions/53597752/visual-studio-code-can-you-have-real-time-linting-for-python
Answer: If you use shift + cmd + P (or ^+ctrl+P for windows) or go to View > Command Palette and type "Lint"
The Command Palette allows you to execute different commands, from here you can enable/disable Linting and select which Linter you would like to use. Most popular is PyLint but you can select Flake8 or Pep8 or whatever you like.
I believe you need to do these things before the linter works in real-time.
To scan for problems with your code without saving first, use shift + cmd + M, you will receive an error code in the vscode Terminal.
Answer: EDIT2, 27 Mar 2024
Just only use this config to real time linting.
{
    "python.defaultInterpreterPath": "/usr/bin/python3",
    "editor.formatOnSave": true
}

My installed extensions are

python
pylint
pylance
python debugger
autopep8

EDIT1
Update 4 Jul 2022
New version of python extension deprecates "python.pythonPath" and suggest to use this instead.
"python.defaultInterpreterPath": "/usr/bin/python3",

Put these lines in .vscode/settings.json
{
    "python.linting.pylintEnabled": true,
    "python.linting.enabled": true,
    "python.pythonPath": "/usr/bin/python3",
    "editor.formatOnSave": true
}

And install autopep8 package.
Use pip to install it
python3 -m pip install autopep8
Or in Debian based as python3-autopep8 exists in repo you can run
sudo apt install python3-autopep8
And then python linting on vscode will work.
Also, the Warning menu will activate.
Hint that I set run linter onsave.

Real-time linting of Python with VSCode


Can you make floated elements in a div not wrap?

Question: (The target browser is IE8)
I have a div that contains a list of elements floated left. The elements width can change at runtime. I'd like to make it so that if they longer fit in the div it just gets cut off and doesn't wrap to a new line.
It only seems to work if the item is on a line by itself:
This page demonstrates the problem:
(The text input's width needs to change at runtime)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

            xItem 1

            <input type="text" style="width:300px" maxlength="30"/>

Comment: When you say that the input's width will need to change, do you expect to change the maxlength value or the style width value (or both)? Will you also change the enclosing div style width value? Will enclosing div enclose on a single set of elements, or multiple rows?
Answer: You can do that easily by adding another block element around the floated ones, with high width and overflow set to hidden. Also, you'll need to set overflow:hidden to the original parent container.
Note that if the width of the floated elements exceed the width of the new block element mentioned above, they will wrap again. So I recommend a high value for that.
EDIT: I see you have a div with an ul and some li's inside. So you don't have to add a new element, since the ul is also a block element and it is already there.
Here is your code with some corrections:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

            xItem 1

            <input type="text" style="width:300px" maxlength="30"/>

I hope it will work for you. :)
Comment: I updated w/ a more concrete example. It doesn't seem to work for me. The text input goes to the next line when its too wide.
Answer: overflow:hidden on the parent container should do the trick.
Comment: overlow:hidden is not enough, you need to set its width to a higher value to allow overflowing. And if you do that in the parent container, it will definitely not fit its original context. See my post.
Comment: Really?  Funny how CSS works sometimes... i would have never thought of this.
Answer: Could you use "nowrap"? probably just for text mind you
Answer: It seems like you're looking for this sort of behaviour, no?
div.aclb {
    overflow: hidden;
}
div.aclb ul {
    white-space: nowrap;
}
div.aclb li {
    display: inline;
}


Testing elixir release build with exrm

Question: I am building phoenix application with exrm.
Good practice suggests, that I should make tests against the same binary, I'll be pushing to production.
Exrm gives me the ability to deploy phoenix on machines, that don't have Erlang or Elixir installed, which makes pulling docker images faster.
Is there a way to start mix test against binary built by exrm?
Answer: It should be noted that releases aren't a binary file. Sure they are packaged into a tarball, but that is just to ease deployment, what it contains is effectively the binary .beam files generated with MIX_ENV=prod mix compile, plus ERTS (if you are bundling it), Erlang/Elixir .beam files, and the boot scripts/config files for starting the application, etc.
So in short your code will behave identically in a release as it would when running with MIX_ENV=prod (assuming you ran MIX_ENV=prod mix release). The only practical difference is whether or not you've correctly configured your application for being packaged in a release, and testing this boils down to doing a test deployment to /tmp/<app> and booting it to make sure you didn't forget to add dependencies to applications in mix.exs.
The other element you'd need to test is if you are doing hot upgrades/downgrades with your application, in which case you need to do test deploys locally to make sure the upgrade/downgrade is applied as expected, since exrm generates default .appup files for you, which may not always do the correct thing, or everything you need them to do, in which case you need to edit them as appropriate. I do this by deploying to /tmp/<app> starting up the old version, then deploying the upgrade tarball to /tmp/<app>/releases/<new version>/<app>.tar.gz, and running /tmp/<app>/bin/<app> upgrade <version> and testing that the application was upgraded as expected, then running the downgrade command for the previous version to see if it rolls back properly. The nature of the testing varies depending on the code changes you've made, but that's the gist of it.
Hopefully that helps answer your question!
Comment: To add to this excellent answer, keep in mind that release doesn't contain test code and it also doesn't include `mix`, so running tests on the release can't technically work. You could of course consider integration/acceptance testing, if you deploy the release to some staging server and run some black box tests (e.g. by checking the outcome of various http requests).
Comment: @tkowal You can still use System.get_env within your code, so you can set environment variables and read them as you'd expect, the difference is in the configuration of your application, as the configuration won't change based on `MIX_ENV` anymore (this is because you are not using Mix in a release, either to run it, or to read configuration). So the config will be whatever environment you ran `mix release` with (unless you edit sys.config on your target system).
Comment: @sasajuric Good thing to point out! Though you can actually add the `mix` application as a dependency, and include it in the release, but as you can probably guess, it's neither recommended or guaranteed to even work properly ;)
Comment: Thank you, that was, what I actually expected, but I just wanted to be sure. One more question. It is compiled with `MIX_ENV=prod`, but will the actual release read the enviroment variables? So that if I have MIX_ENV=stag with other database credentials, it should still work correctly? Thanks bitwalker for the great software :)

Testing elixir release build with exrm


Angularjs expressions - How complex can they be?

Question: I have a json object that is a serialization of a list so is just an array of json objects.
Can I use the like of JSONSelect to bind a value?
If not then how can I bind id.name where id==2 to a dom element?
<code>{"data": [ { "id":1, "name":"Rob"}, {"id":2, "name": "John"} ] }
</code>
Comment: Can you elaborate a bit more?  What does the html you are trying to bind code look like?
Comment: In practice what I have is 2 'lists'; a set of 'questions' that are rendered a html and a set of 'current answers'. There is a reference in the question data to the answer value and I need to bind the answer value to the question element. The problem is that the 2 lists are not in the same order and questions can be repeated (on separate tabs).
Comment: I have found that by turning the answer list into a dictionary helps but I was interested to find out if I could bind say, "data[id=1].name" or using something like JSONSelect ".data .id:val("1") ~ .name"; but I need two-way binding.
Answer: You will need to do some proccess on your json data:
<code>function getNameForId(data, id) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].id === id) return data[i].name;
    }
}
</code>
then, you can bind the reslut.
see jsFiddle


Domain services

Question: We have started our projects with DDD design principles, I heard that any business logic needs two or more domain objects interaction should be written as domain services.
My question is:

Since my business logic includes saving of more than one domain or access many domain objects for validation purpose, can I pass repository inside the service method or can I access using DIContainer.
In case of operation A I will build List<Specification> (Specification classes which contain validation) and pass on to domain services from application layer. So my domain service validates and does business logic.
Can domain service use CRUD operation in itself.

I am really confused where to draw a line between application service and domain service.
Can I get any good samples which has application services, domain services, domain specifications with repositories involved.
Answer: Answer is here: http://gorodinski.com/blog/2012/04/14/services-in-domain-driven-design-ddd/
Actually these rules apply:
1) domain entities do the job
2) if in some function more entities are involved, changed - a domain service may be the solution
3) no, domain layer should not know anything about: transaction, saving, locking, etc. neither should load entities... if you need something like that use INeedSomeStuffFromRepo. Interface is defined in the domain layer, implementation is inside app. services. This way you could also doi locking, f.e. IExecuteThisFncToLockBeforeManipulatingWithAnObject
4) saving, transaction is in the app service side. i use persistence by reachability, so even if i have  an aggregate, entity with other entities related, it's enough to save the parent...
Answer: Domain service actually is the Pure fabrication in GRASP. everything does not fit in an entity or a value object.

Domain services


WhatsApp Web is asking to update Chrome while using Chromium

Question: I am using Chromium Version 71.0.3578.80 (Official Build) on Ubuntu, running on Ubuntu 16.04 (64-bit).
This morning my WhatsApp Web tab asked me to update Chrome with the following message:

WhatsApp works with Google Chrome 36+
  To use WhatsApp, update Chrome
  or use Mozilla Firefox, Safari, Microsoft Edge or Opera.

What should I do to get WhatsApp Web running again?
Comment: WhatApp webdevs have to learn about feature detection: https://en.wikipedia.org/wiki/Feature_detection_(web_development)
Comment: This is broken again, and the UA trick dosent resolve it.
Answer: The problem seems to be with the User agent Chromium for Linux is using right now. It is using Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.80 Chrome/71.0.3578.80 Safari/537.36 which WhatsApp web is recognizing as an older User Agent which Chrome used before version 36. I have also observed that the problem is with Chromium for Linux only since on the other hand WhatsApp web seems to work perfectly under Chromium version 71.0.3578.80 on Windows which uses User agent as Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3641.0 Safari/537.36.
So, to run WhatsApp web again you need to change the User Agent. Do remember to clear all cookies and temporary data to get these working since temporary data might create problems. There are two ways to change user agent:
1. Using Chromium Settings:

Open New Tab and press Ctrl+Shift+I to open Developer Tools
Click on Hamburger menu (vertical dots) and choose More tools - Network conditions

Go to the Network conditions tab (should appear in bottom right), disable the option Select automatically and choose Chrome - Windows from drop-down menu.

Note: You need to perform all things again once WhatsApp web is opened in new tab or Chromium is relaunched since Settings are applied only for that Tab and aren't remembered for a particular site.

2. Using an extension:

Download and install User-Agent Switcher for Chrome
This extension doesn't have any User agents for Chrome. So, you need to add a new custom User Agent or use in-built user agents, for example, Internet Explorer/Safari/Firefox.
If you want to stick to "Chromium on Ubuntu" as User Agent:

Right Click (or two finger tap) on the extension in top bar and click on Options
A list will open which would look like

Click on New User-agent name. Give any name you like and as User-agent enter this Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.75 Chrome/73.0.3683.75 Safari/537.36. Give group name as Chrome, in Append?, choose Replace and in Flag field enter New. Click on Add.

Now, click on extension in top bar and change the UA to this newly created custom UA or some other UA (if not created).

In this case UA is applied universally to all tabs.

Once you're done with one of the above ways, open WhatsApp Web to login.
Comment: this works for me only if i delete cookies for web.whatsapp.com first
Comment: @DiegoBetto Chromium doesn't have any UA as *Chrome - Ubuntu/Linux* in-built. Also, I've used UA of Chromium for Windows for second approach. Since in this solution we are focused on a particular site so IMO it doesn't matter if we change OS if we know about the site.
Comment: Change user agent string but avoid changing OS, keep linux based. It works and it avoids you problems with web apps that uses os detection
Comment: I tried many solutios, and the first one was the only that really works for me, THANKS!!!
by the way, why does Chrome dev tools doesnt't show none of the linux browsers in options? evil guys
Comment: @Rodrigo Actually Spoofing user agent allows developers to check how their web apps will react to different browsers on different platforms. IMO Linux have very less market share (about 2% if we consider normal users) that's it doesn't have that. You can also observe that for mobile, we have UA built in for Android and iPhone only (no Windows, Symbian phones) because of their market share.
Comment: Awesome, this works - thanks! However, any refresh or restart breaks it again for me. I have to clear site data and re-connect after any refresh / restart :-/
Comment: I tried the first method (again) today and found that "chrome windows" is still a useragent that triggers the "please upgrade" message. I then selected "edge windows" and now I'm "in"....
Answer: Installing a browser extension IMHO is a bit overkill.
Instead, I've changed the Chromium icon in gnome to run the browser with --user-agent option.

Close Chromium.

Customize .desktop:
  cp /var/lib/snapd/desktop/applications/chromium_chromium.desktop ~/.local/share/applications
  vim ~/.local/share/applications/chromium_chromium.desktop
  # search "/snap/bin/chromium %U",
  # replace with "/snap/bin/chromium --user-agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36' %U"

Then, reload Gnome:

Press Alt+F2
Enter restart and press Enter.
Comment: This is awesome. Worked like magic, though I added a comment to help me out well into the future when I totally forgot I did this and can't figure out why the UA is hardcoded in the stupid shortcut. After doing this, you'll [obviously] have to drop and re-add your icon. If/when searching for the Chromium shortcut, you'll likely now [obviously] see more than one (probably two), and will have to figure out which one was just added. FYI, this even gets you past one more hurdle in getting Netflix to work. Thanks again.
Comment: Way better than accepted solution!
Comment: Is this still working for you? I tried and I still get the message asking me to update chrome
Comment: @maxime1992, i've reloaded the `web.whatsapp.com` tab on my `Chromium 80.0.3987.162 (Official Build) snap (64-bit)` and it works as usual.
Comment: @maxime1992, you can check which command line parameters are in use. Write `chrome://version/` in chromium address bar. It will show the browser version, but also the "Command Line:" section. My browser has `/snap/chromium/1071/usr/lib/chromium-browser/chrome --no-default-browser-check --no-first-run --password-store=basic --user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 --flag-switches-begin --flag-switches-end --disable-webrtc-apm-in-audio-service`.
Comment: It's even easier when you create a Chromium shortcut via menu -> 'More tools' -> 'Create shortcut...' (and don't forget to click 'Open as window' to have it behave more like a real app). This will generate a .desktop file on your desktop, which you can edit with any text editor. There you can easily add the user-agent string as described above. When done, save the file and right click it. From the menu, select 'Allow Launching'. Done!
Answer: This trick worked for me. I use Version 81.0.4044.129 (Official Build) snap (64-bit)
Open url chrome://flags/#freeze-user-agent
Enable "Freeze User-Agent request header" option
once you relaunch browser, WhatsApp Web will open without problem.
Comment: Works perfectly on Ubuntu 20.04. Thanks!
Comment: "Freeze User-Agent request header" has been re-named "Reduce User-Agent request header". However, enabling it appears to make no difference to this problem (Ubuntu 20.04).


Calculate Mean for Each Unique Value up to a certain date

Question: Data for my example.
date1 = seq(as.Date("2019/01/01"), by = "month", length.out = 48)
date2 = seq(as.Date("2019/02/01"), by = "month", length.out = 48)
date3 = seq(as.Date("2019/02/01"), by = "month", length.out = 48)
date4 = seq(as.Date("2019/02/01"), by = "month", length.out = 48)
date = c(date1,date2,date3,date4)

subproducts1=rep("1",48)
subproducts2=rep("2",48)
subproductsx=rep("x",48)
subproductsy=rep("y",48)

b1 <- c(rnorm(48,5))
b2 <- c(rnorm(48,5))
b3 <-c(rnorm(48,5) )
b4 <- c(rnorm(48,5))

dfone <- data.frame(
                "date"= date,

                "subproduct"=
                  c(subproducts1,subproducts2,subproductsx,subproductsy),
                "actuals"= c(b1,b2,b3,b4))

This creates Jan 2019 for date2,3,4 with value 0.
 dfone <-dfone %>%
 complete(date = seq.Date(from = min(date), to = as.Date('2021-06-01'), by = 'month'),
       nesting(subproduct), fill = list(actuals = 0))

QUESTION: This calculates the mean for each unique sub product and replaces 0's with the mean of each, but how do I have a hard cutoff so the mean is only based off Jan-2019 to Dec-2020 and not Jan 2019 to Dec 2022?
library(dplyr)
dfone_new <- dfone %>%
     group_by(subproduct)  %>%
     mutate(actuals = replace(actuals, actuals == 0,
         mean(actuals[actuals != 0], na.rm = TRUE))) %>%
     ungroup

Answer: We may need one more logical expression while subsetting the 'actuals' i.e. the 'date' should be between the 2019 Jan and 2020 Dec while calculating the mean
library(dplyr)
library(tidyr)
dfone %>%
     group_by(subproduct)  %>%
     mutate(actuals = replace(actuals, actuals == 0,
         mean(actuals[actuals != 0  &
    between(date, as.Date("2019-01-01"), as.Date("2020-12-31"))],
         na.rm = TRUE)))


igraph assign a vector as an attribute for a vertex

Question: I am trying to assign a vector as an attribute for a vertex, but without any luck:
<code># assignment of a numeric value (everything is ok)
g<-set.vertex.attribute(g, 'checked', 2, 3)
V(g)$checked
</code>
.
<code># assignment of a vector (is not working)
g<-set.vertex.attribute(g, 'checked', 2, c(3, 1))
V(g)$checked
</code>
checking the manual, http://igraph.sourceforge.net/doc/R/attributes.html
it looks like this is not possible. Is there any workaround?
Up till now the only things I come up with are:
store this

information in another structure
convert vector to a string with delimiters and store as a string
Answer: This works fine:
<code>## replace c(3,1) by list(c(3,1))
g <- set.vertex.attribute(g, 'checked', 2, list(c(3, 1)))
V(g)[2]$checked
[1] 3 1
</code>
EDIT Why this works?
When you use :
<code>    g<-set.vertex.attribute(g, 'checked', 2, c(3, 1))
</code>
You get this warning :
<code>number of items to replace is not a multiple of replacement length
</code>
Indeed you try to put c(3,1) which has a length =2 in a variable with length =1. SO the idea is to replace c(3,1) with something similar but with length =1.  For example:
<code> length(list(c(3,1)))
[1] 1
> length(data.frame(c(3,1)))
[1] 1
</code>


Alternative to Kotlin Coroutines in Java?

Question: Is there an alternative to Kotlin Coroutines in Java? I have Kotlin code in which I want to perform facial recognition on one dispatcher, while updating the bounding boxes on the other. I tried to automatically convert the code to Java, but the coroutines part was not converted.
The code is something like this:
withContext( Dispatchers.Default ) {
    //perform face recognition
}

withContext( Dispatchers.Main ) {
    boundingBoxOverlay.faceBoundingBoxes = predictions
    boundingBoxOverlay.invalidate()
    isProcessing.set(false)
}

Comment: Coroutines work via the koltin compiler rewriting some code so, no coroutines for you in Java. Maybe the question here is 'why are you trying to convert kotlin to java?'. Oh and by the way you can keep a few files in Kotlin and rewrite the rest in Java.
Comment: The "easiest" is to just use some other thread. That will require to rearchitect some possibly large part of your code.
Comment: Thanks for suggestion but thread management in this case would be very difficult.a and there will be a lot of overhead. Is there any way to use the koltin coroutines in java code? @al3c
Comment: Because the app is written in java. I am adding the feature of Face recognition and it requires coroutines to run concurrently to constantly update the frames and recognize the faces.
Answer: For the most part...you can't.
Kotlin coroutines rely on transformations performed by the compiler recognizing suspend function calls and handling them specially, tracking their state and resuming them correctly.  The Java compiler doesn't do this.
This, unfortunately, means you'll probably end up needing to substantially restructure your code to something callback-based.  The best way to do that is going to depend on what you're doing.
Answer: Perhaps you can use an ExecutorService to implement concurrent behaviour.
The following could help, but the exact solution would depend on how you use the methods too. The withContext() will run both methods concurrently and wait for both of them to finish.
final ExecutorService executorService = Executors.newFixedThreadPool(2);

public final void withContext(){
 final Future<?> futureFacial = this.executorService.submit(this::withContextFacial);
 final Future<?> futureBounding = this.executorService.submit(this::withContextBoundingBoxes);
 futureFacial.get();
 futureBounding.get();

}
private final withContextFacial( ) {
    //perform face recognition }

private final withContextBoundingBoxes() {
    boundingBoxOverlay.faceBoundingBoxes = predictions
    boundingBoxOverlay.invalidate()
    isProcessing.set(false) }

Kotlin has language level support for coroutines while Java doesn't. That means that you have to workaround this fact and model the solution in another way.
There are multiple solutions to this already in the Java SRE. Such as: Threads, ExecutorService, ForkJoin.
And then multiple libraries and approaches outside JRE such as the Actor model or reactive programming.
Answer: NO
Java compiler does not support suspendable computations for its threads. It only supports synchronous (Blocking) computations only.
But Java language has something close similar to the kotlin coroutine is Thread pool.
(Thread pool - a managed collection of threads that runs tasks in parallel from a queue. New tasks are executed on existing threads as those threads become idle).
Comment: Unfortunately, a Thread <> a Job, so Java thread pools are still not analogous to Kotlin coroutines
Answer: You could write your coroutines, than decompile code and use java-class for coroutine, but it seems to be so non-flexible approach, also you should deal with continuations.
In case of java - just use RXJava instead of coroutines, it is well known approach for concurrency


Three tangent circles and they are tangent to a line

Question: Let $c_1$, $c_2$ and $c_3$ three external tangent circles. Their centers are $O_1$, etc. The three circles are tangent to a single line $r$. The problem is to prove that $O_1O_2O_3$ is a triangle with an obtuse angle.
Tries: I have tried Euclidean geometry, analytical geometry and trigonometry and even inversion. No success so far.
Comment: Can you add a picture? Or what exactly do you mean by external tangent circles? Do you mean their interiors are disjoint? Also are the circles pairwise tangent?
Comment: It is not easy to draw. The three circles are tangent pairwise and ther are tangent to a single line. By "external tangency" I mean that the smaller circle is outside the greater one (the distance between the centers of two external tangent circles of radius $r_1$ and $r_2$ is $r_1\color{red}+r_2$).
Comment: So.... If we have two tangent circles and we draw a line that that touches each circle once (so it is mutually tangent to both) then are you say that there is a third very smaller circle kind of resting in the crock between the line and the the two bigger circles, and is small enough to be tangent to the line but also to the two bigger circles? Like this?  https://www.analyzemath.com/Geometry/challenge/three_circles_problem.gif
Answer: Ok thanks for the clarification. Two observations to start. First, the three circles must be on the same side of the line if they are all tangent to it. Therefore, we will choose the common tangent line to be the $Ox$ axis and the three circles to lie in the upper half plane. Second, note that one of the radii of the circles has to be smaller than the other two to allow the other two circles to be tangent. By dilating and choosing the coordinate axes nicely, we can assume the smaller circle has radius $1$ and is centered at the point $(0,1)$.
Let the other radii be $a$ and $b$ and recall that $a>1$ and $b>1$. Let the centers of these two other circles be $(x,a)$ and $(y,b)$ respectively (since they are both tangent to the horizontal axis, clearly the heights off the horizontal axis will be $a$ and $b$ respectively). Moreover, $x$ and $y$ cannot have the same sign, so wlog let's take $x<0<y$.
Now let's figure out the value of $x$. By the assumption of the $a$ circle and the small circle being tangent, we must have that the distance between the centers of these two circles is exactly $a+1$. Therefore $x^2+(a-1)^2=(a+1)^2$ and so $x=-2\sqrt{a}$. Similarly we get $y=2\sqrt{b}$. So we reduced to the case of the circles having centers $(-2\sqrt{a},a), (0,1), (2\sqrt{b},b)$ and radii $a,1,b$ respectively. Let us denote the centers by $A,O,B$ respectively.
Next, the 'outer' circles are also tangent, meaning that the distance between $(-2\sqrt{a},a)$ and $(2\sqrt{b},b)$ is exactly $a+b$. In other words, $4(\sqrt{a}+\sqrt{b})^2+(b-a)^2=(a+b)^2$. After simplification, this implies $ab=a+b+2\sqrt{ab}$.
Now we show that the angle $\angle AOB$ is greater than $\frac{\pi}{2}$. To do this it suffices to show $AB^2>AO^2+BO^2$, i.e., that $(a+b)^2>(a+1)^2+(b+1)^2$. Simplifying, this condition boils down to $ab>a+b+1$. But we know that $ab=a+b+2\sqrt{ab}$ and both $a>1$ and $b>1$ by construction. Therefore $2\sqrt{ab}>2$.