Will this plumbing connection to my sink be viable?

Question: I'm trying to understand if this plumbing configuration looks viable. Hoping to get some help on this. I'm not sure if the slope will work.
Comment: This will probably work fine, but a much simpler arrangement can be purchased for $5 or $10 (if you are in the US) as a kit with only about 4 parts.
Comment: If you use a spigot end trap adapter instead of a hub end, the p trap could be a little higher and probably not need that upward turn. Also, you could turn the p trap around directly toward the trap arm. Functionality-wise it might not matter, but it would look neater.
Comment: Thanks for the help! Ended up being able to get a piece that connected directly to my sink drain and gave me back the space I needed to get the slope with the p-trap and fewer pieces.
Answer: I think it is viable, I probably wouldn't change this just for the sake of it.  But if you're already working on it and want something easier to maintain with fewer parts .... this entire kit is $7 and may be all you need.  You may need an additional compression nut and washer at the wall end, although these kits sometimes come with some extras.

Addressing the question about slope, if you are referring to the slope of the bend highlighted in yellow that in itself is not a problem.  The trap water level will be where indicated in green, and everything in between will be wet.  Just imagine the whole thing is the trap.  Hopefully it's all very water tight.
Ideally (and if you replace as suggested) the trap resting water will be entirely inside a solid piece with no joints.  In fact, I'll change my advice: for that reason alone you ought to splurge the $7 on the replacement.  Note that a useful element of the suggested replacement is a slip joint that allows you to install at the right level easily.
Comment: Is that required for the horizontal exit of a trap?  A) I don't think it is, and B) I assumed the slope question pertained to the unnecessary extra elbow that slopes upward after the trap (but can be thought of as part of it) and not to the metal pipe exiting the wall, which I assumed is outside OP's current scope.  I may of course be wrong about all those things.
Comment: Better as an answer than a comment! ;) +1
Comment: @jay613 - Answer might be improved by addressing slope which is one of the concerns raised by the OP. 1/4" per foot is required. Not sure from the pic that the current setup has that.
Comment: Thanks for the help! Ended up being able to get a piece that connected directly to my sink drain and gave me back the space I needed to get the slope with the p-trap and fewer pieces.


PulseAudio doesn't load "module-echo-cancel" after restarting

Question: I had a problem with my microphone and solved it by adding load-module module-echo-cancel to /etc/pulse/default.pa and running pulseaudio -k after it. It solves my problem but when I restart computer it dose not load again and I have to run pulseaudio -k command every time I shutdown and start the computer again. What do I have to do?
Answer: There is a man page for default.pa, which says:

The  PulseAudio  sound  server  interprets  a  configuration  script on startup, which is mainly used to define the set  of  modules  to  load.
When  PulseAudio  runs  in  the  per-user  mode and ~/.config/pulse/default.pa exists, that file is used. When PulseAudio runs  in  the  per-user  mode  and that file doesn't exist, /etc/pulse/default.pa is used.
When PulseAudio runs as a system service, /etc/pulse/system.pa is used.

This suggest you might try duplicating your load module in /etc/pulse/system.pa
It seems like it might be loading as a system service when you reboot your computer, but in per-user mode when you run pulseaudio -k.  Therefore, if you move the line to the system-wide settings, it should available from reboot or after a -k.
Comment: it dose not work :((
Comment: What do you get when you run `pulseaudio --dump-conf`?

Also: In `/etc/pulse/daemon.conf`, what options are set for `default-script-file=` and is `load-default-script-file=` set to yes?
Comment: ```default-script-file = /etc/pulse/default.pa``` and ```load-default-script-file = yes```
Comment: use    ~/.config/pulse/default.pa to load your module (create it if not existing)


$G$ acts faithfully on $\Omega$, $A\leq G$, $A$ transitive on $\Omega$. Then $|C_G(A)|$ is a divisor of $|\Omega|$.

Question: $G$ acts faithfully on $\Omega$, $A\leq G$, $A$ transitive on $\Omega$. Then $|C_G(A)|$ is a divisor of $|\Omega|$. If in addition $A$ is abelian then $C_G(A)=A$. $G$ and $\Omega$ are finite.
Let $\Gamma:\Omega\times G \to \Omega$ be the action. Then the restriction $\Theta$ of $\Gamma$ to $\Omega\times A$ is an action and we are told it is transitive. Let $|\Omega|=n$. $\Gamma$ induces a homomorphism $\Gamma':G\to S_n$ that is one to one. Also $\Theta$ induces a homomorphism $\Theta':A\to S_n$ which is the restriction of $\Gamma'$ to $A$. Therefor as $\Gamma'$ is one to one so is $\Theta'$, that is $\Theta$ is faithful.
The image of $G$ under $\Gamma'$ is isomorphic to $G$ and a subgroup of $S_n$. Hence $|G|$ divides $n!$ (1). Also, if $\alpha\in\Omega$ and $A_\alpha$ is the stabilizer of $\alpha$ in $A$ then $|\Omega|=|\alpha^A|=  |A|/|A_\alpha|=|A|/|G_\alpha\cap A|$ (2) because of the transitivity of $A$. Aside from this I don't find any further equations to help me prove the statement. Could somebody give me a hint?
Comment: Not sure if I'm missing something but what do you mean by "image of $G$ under $\Theta'$"? Did you mean $\Gamma'$? Because $\Theta'$ is not a function defined on $G$.
Comment: It was a typo. It's "under $\Gamma'$". I already corrected it.
Comment: In case it wasn't clear, my answer is meant to be a hint, together with why you would think that this is the right approach to take.
Answer: First, we need that $C_G(A)$ acts semi-regularly on $\Omega$, i.e., no non-identity element of $C_G(A)$ stabilizes a point on $\Omega$. To see this, let $g\in C_G(A)$ stabilize a point $x\in \Omega$. Since $A$ is transitive on $\Omega$, for any $y\in \Omega$ there exists $a\in A$ such that $xa=y$. But then $g^a=a$, but as is standard, if $g$ stabilizes $x$ then $g^a$ stabilizes $xa=y$. Thus $g$ stabilizes $\Omega$, and $g=1$. This proves that $C_G(A)$ acts semi-regularly on $\Omega$.
Each orbit has length $|C_G(A)|$, by the orbit-stabilizer theorem, and so $|C_G(A)|$ divides $|\Omega|$, as needed.
Comment: $xa_i=x_i$, $i=1,2,...,n$, $xg=x$, $x_ig=xa_ig=xga_i=xa_i=x_i$, $g\in G_{x_i}$ for all $i$, for all $i$ $H_x\leq G_{x_i}$.
Comment: But $\Omega=\{x_1,...,x_n\}$. Then the elements of $H_x$ act like the identity permutation on $\Omega$. SORRY, $H=C_G(A)$.
Comment: Right. So the elements of $C_G(A)$ stabilize every point in $\Omega$. Since $G$ acts faithfully on $\Omega$...
Comment: $H_x=1$ for all $x\in C_\Omega(H)$.
Comment: $H_x=1$ for all $x\in \Omega$. Thus $C_G(A)$ acts semi-regularly, i.e., fixed-point-freely, on $\Omega$. So if the orbits of $H$ on $\Omega$ are all the same size, then you are done. I've added the next part to the answer.
Comment: $a=1$. But we said $g$ fixes $x$. $g\in H$ does not mean $g$ fixes $x$!
Comment: Yes, I replaced that comment with the correct next stage, sorry.
Comment: $H:= C_G(A)$, $x\in \Omega$, $|x^H|=|H|/|H_x|$. But $H_x=1$ by semi-regularity. So, $|x^H|=|H|$. I.e. all orbits have the same size, namely $|H|$. So $|\Omega|=|H|q$ for some integer $q$ and $|H|$ divides $|\Omega|$ as was to be proved. Thanks a lot!
Comment: I've now edited the answer so it gives a full proof.
Comment: And why should $C_G(A)=A$ if $A$ is abelian?
Comment: If $A$ is abelian then $A\leq C_G(A)$, so all of the statements you have proved about $C_G(A)$ hold for $A$. You should be able to show that $A$ is regular and $C_G(A)=A$ then.
Comment: Of course $A$ is regular because it is a subgroup of $C_G(A)$. But how do I prove the orbit of $x$ under $A$ is equal to the orbit of $x$ under $C_G(A)$?
Comment: I guess you have done this already, but what is the orbit of $x$ under $A$?
Comment: Yes, after posting I realized ($H:= C_G(A)$) $A\leq H$ implies two things: $x^A\subseteq x^H$. But $x^A=\Omega$ ($A$ transitive). Hence $x^H=\Omega$. And $A_x\leq H_x$. But $H_x=1$ as was proved. Hence $A_x=1$. From this $|\Omega|$ can be computed in two ways and $|A|=|H|$ results.
Comment: It's quicker even to note that $|C_G(A)|$ divides $|\Omega|$, $|A|\geq |\Omega|$, and $A\leq C_G(A)$.
Comment: I see. Well, again thanks a lot.


drop-down menu closing issue in wordpress?

Question: I already succeed to added the transition effect when hover the cursor to drop-down menu (click the "M" logo) in my own wordpress theme but when the cursor being away from drop-down menu don't show  the transition effect when closing. You can check out my own theme on this link for further info.
Here drop-down css style:
<code>.dropdown-menu {
    border-bottom-right-radius: 77px;
    border-bottom-left-radius: 77px;
    /* background: url(img/submenu.png) no-repeat scroll right/ 91% 100%; */
    position: absolute;
    height:0;
    top: 100%;
    left: 0;
    z-index: 1000;
    display: none;
    float: left;
    min-width: 153px;
    padding: 1px 0;
    margin: 2px 0 0 0;
    list-style: none;
    font-size: 14px;
    text-align: center;
    background-color: transparent!important;
    border: 1px solid #ccc;
    border: 1px solid rgba(0,0,0,0.15);
    background-clip: padding-box;
    opacity: 0;
    top: 35px;
    visibility: hidden;
    -webkit-transition:height 300ms ease-in;
    -moz-transition:height 300ms ease-in;
    -ms-transition: height 300ms ease-in;
    -o-transition:height 300ms ease-in;
    transition:height 300ms ease-in;
    overflow: hidden;
}

.navbar-nav li:hover .dropdown-menu {
    opacity: 1;
    top: 105px;
    visibility: visible;
     height:300px;
}
</code>
So How I can add the transition effect when drop-down menu closing?
Answer: Instead of transitioning only the height you could try
<code>-webkit-transition: all 300ms ease-in;
-moz-transition: all 300ms ease-in;
-ms-transition: all 300ms ease-in;
-o-transition: all 300ms ease-in;
 transition: all 300ms ease-in;
</code>


Javascript multiple script tag are allowed?

Question: I have an html file where I see two javascript tag :
<code><script type="text/javascript">
  var varname = .... etc
</script>

<script language ="JavaScript">

 function namefunction . . . etc

</script>
</code>
is this allowed? Or can create issue with loading js in the page?
Comment: why are you all voting down the post? At least provide a reason to improve! Not acceptable
Comment: muliple script tags are allowed in an html.
Answer: There is no problem in using multiple Script in html.
How it is loaded is depending on which on the order it is added into the html.
Answer: It is totally allowed. It shouldn't cause any issues whatsoever.


Improperly configured at . error in Django REST framework

Question: When I access the base URL of http://127.0.0.1:8000/ I get the following error
ImproperlyConfigured at /
Could not resolve URL for hyperlinked relationship using view name "wallet-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.

When I try to access the admin URL it works fine but when I access my data URL which is http://127.0.0.1:8000/wallets I get a 404 error page not found?
This is my serializers.py file
from rest_framework import serializers

from .models import Wallet

class WalletSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Wallet
        fields = ('__all__')

My views.py file is the following
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import WalletSerializer
from .models import Wallet

@api_view(['GET'])
def getData(request):
    queryset = Wallet.objects.all()
    serializer = WalletSerializer(queryset, many=True, context={'request': request})
    return Response(serializer.data)

This is my Models.py file
from django.db import models

class Wallet(models.Model):
    raddress = models.CharField(max_length=60)
    def __str__(self):
        return self.raddress

I was using a simple class in my views.py file instead of 'GET' functions which I am doing now and I was also using routers in my urls.py file but I removed all that so I could create CRUD functions but I face this problem now
Comment: Can you add the `Wallet` model to your question?
Comment: I have added models.py file
Comment: Why are you using a `HyperlinkedModelSerializer`? You need to create an API url pattern named "wallet-detail" that takes a pk parameter and returns a single wallet if you use that serializer class, it adds a field named "url" that returns a link to the detail API for the model and by default uses the view named "-detail"
Comment: how do I do that can you refer me somewhere or paste here if possible?
Comment: Try using `serializers.ModelSerializer` instead of `serializers.HyperlinkedModelSerializer`, do you need the links if you don't have the detail APIs?
Comment: Alright that works but IDK what you mean when you say detail API's
Comment: That serializer adds a `url` field https://www.django-rest-framework.org/api-guide/serializers/#hyperlinkedmodelserializer, that field renders a link to the object using the the view named `-detail` by default https://www.django-rest-framework.org/api-guide/relations/#hyperlinkedidentityfield. You don't have an API that returns a single wallet (a detail view) so you have nothing for that field to link to
Comment: alright so adding, ModelSerializers is the best practise in your opinion?
Comment: Yes, using `serializers.ModelSerializer` should be fine. If you need to include the link to a detail view you can do it later when you have the API
Comment: Well isn't what I am doing called building the API?
Comment: Or an API is a different thing lol, confused
Answer: try using ModelViewSet instead of your own custom view as they do in the tutorial
https://www.django-rest-framework.org/tutorial/quickstart/
Also, you might want to check the HyperlinkedModelSerializer documentation, as they are a bit picky
https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/


php cache expiration time for file_exists() or similiar functions

Question: as per php documentation for file_exists()

The results of this function are cached. See clearstatcache() for
  more details.

But it doesn't provide information for how long php will hold this information in cache. I've checked documentation for clearstatcache()
but no such information is there. Googling also not helped this time.
I'm building an application where file_exists is called to generate some output, and since the file being checked can be removed by any time by any user, i need to be sure if it really exists before generating output.
Calling clearcache() before file_exists() will solve the purpose, but just for curiosity I'd like to know for how long PHP will cache files information (default time) and by which variable i can this change cache expiration time?
EDIT 1: In real, checking again with file_exists() after deleting file returns false, but if it is so, what is the meaning of cache as written in documentation ?
EDIT 2:
<?
var_dump(file_exists('/home/user/filecheck.php'));
sleep(20);
// after running script, sleep for 20 seconds just to quickly delete this file manually before file_exists is called again.
// unlink is not used since as per documentation it'll clear php cache.
var_dump(file_exists('/home/user/filecheck.php'));
?>

and the response of script is
boolean true

boolean false

That means php is not caching file_exists information if file exists even for same execution, then why it is written in documentation that "the results of this function are cached"?
Comment: PHP caches that information for the duration of the request
Comment: See  comment in [this bug report](https://bugs.php.net/bug.php?id=28790) - `You guys realize that the stat cache is per-request, right? You only need to clear the stat cache before a file_exists() call if you A. did a stat for it, and B. either created or deleted it on that request. In which case you shouldn't need
to stat it again since the success status of the create/delete will tell you
whether the file is there or not. Perhaps for long-running daemons or something this becomes more of an issue, but for a typical web request the stat cache typically saves you dozens of system calls.`
Comment: @MarkBaker Youre pointing to bug with date: 2004-06-15 15:43  isn't it strange to think of it now. I think this issue is fixed during 11 years...
Comment: @num8er - I was specifically pointing to a comment in the bug that specifically answered the OPs question about the duration of the cache; and although I don't see anything to say that the bug has been closed, I would hope that it has been resolved now
Comment: duration of request ???
Comment: PHP executes individual requests to the webserver, each in its own thread; and when the response is returned to the webbrowser, then the request terminates
Comment: so you mean it caches for current execution of script.
Comment: Yes, the cache is wiped when PHP ceases executing each individual request
Comment: @MarkBaker, please reread the edited question.
Comment: The above is where I understood that the cache is for the duration of the request, which is from the PHP internals team..... I have no explanation of why it isn't working in this way for you
Comment: but I don't care, I'm trying to be away from php, cuz this lang/interpretator become mainstream, everybody are "pro" with php (:  I prefer nodejs for now, but maybe in future switch to D language.
Answer: How long the stat cache will cache the information is configurable in your php.ini file using the realpath_cache_ttl variable. Default seems to be 120 seconds.
Answer: You don't need to clearstatcache() because in manual says:

You should also note that PHP doesn't cache information about
  non-existent files. So, if you call file_exists() on a file that
  doesn't exist, it will return FALSE until you create the file. If you
  create the file, it will return TRUE even if you then delete the file.
  However unlink() clears the cache automatically.

also to avoid some errors it's better use is_file() if You want to check existence of file and is_dir() for directory, because file_exists() will return true if path that exists both is file or is directory.
p.s. to prove that if file deleted it's not cached: http://joxi.ru/eAO55BF4ojZjmo
about meaning of cache: again read this manual: http://php.net/manual/en/function.clearstatcache.php

When you use stat(), lstat(), or any of the other functions listed in
  the affected functions list (below), PHP caches the information those
  functions return in order to provide faster performance.

it means that cache is for file stats, to not to reread it every time, clearstatcache() removes stat cache for this file and forces reread them.
P.S. actually it's stupid to cache stats without explicitly enabling it by user with something like: ini_set('cache_file_stats', true) it would be better to give control of it to user.
Comment: but if previously file was there and file_exists was called, php will cache file information. and then if file will be removed, file_exists will again return true.
Comment: In real, checking again after deleting file returns false, but if it is so, what is the meaning of cache ?
Comment: have You checked in real life?
Comment: meaning of cache is not to reread stats of file, look at: http://php.net/manual/ru/function.stat.php


Using ViewBag vs directly referencing static property across numerous views

Question: I am trying to centralize some rather static info, e.g. a user's name or a logo image URL. The code I'm cleaning up originally would look this information up in each controller action that needed it and set it within the strongly-typed model. This caused numerous blocks of the same (and sometimes slightly different, depending on the author) code to be repeated throughout the application.
I've created a static property that builds this info e.g.
public static class SampleInfo
{
    public static string LogoUrl
    {
        get {
                string logoUrl = "would-do-something-to-store/look-up-image-here";
                return logoUrl;
            }
    }
}

and now I can reference SampleInfo.LogoUrl and to get the URL instead of looking it up individually each time. But at the moment, this field is still passed to the view within the model, so I would still have to type Model.LogoUrl = SampleInfo.LogoUrl every time.
One thought would be to replace  in the views with  and then set ViewBag.Logo = SampleInfo.LogoUrl; inside the base controller that all the controllers are using. It seems like most people frown on using ViewBag at all, but this seems like a very good option as it is only set in one place and if the view references @ViewBag.Logo, it will be able to automatically pull it from the base controller without any extra coding. All of the data specific to a particular view would still be passed through the strongly-typed view, just the logo would be removed from the model and placed in the ViewBag.
In this same line of thinking, I could just change the image to  and directly reference the static property, skipping the ViewBag completely.
Would skipping the ViewBag and directly referencing the static property be a fine alternative or bad/worse coding practice?
A third thought would be to add code to the base class or an action filter that would look for a particular field (e.g. Logo) within the current model and set it, if it is present. I'm not sure, however, if this is easily accomplished in a dynamic fashion?
Comment: You may want to reexamine why you've got so many places that output the logo in the first place. It's likely that you could leverage Layouts and RenderAction to bring that responsibility into a single controller/view.
Comment: It's not that it is a singular data field spread out in every view, but there are a few fields that are sometimes used throughout the site. The majority of these are located within a layout page and some partial views that multiple views reference. It's a good point either way.
Answer: I recommend using the format
Your views are already tied to your web site assembly so I don't see an issue with directly referencing this variable from within your views.
Comment: Thanks, this is what I was leaning toward - it seems like it would be the cleanest way to keep specific info centralized and it doesn't have to introduce a ViewBag middle layer.
Comment: I will even go so far as to add a namespace to the web.config in the views directory (this is the equivalent of adding a using statement to each view) so that I can put the static variable in a namespace with other constants.  See the 2nd answer on http://stackoverflow.com/questions/3239006/how-to-import-a-namespace-in-razor-view-page for details.


What does airflow in the sump pit mean?

Question: I have a sump pit in my basement with a pipe that comes from the drain tile. The drain tile does not see day light anywhere, it's all near the footings of the foundation.
I can feel a strong flow of air coming from the pipe. Where would that be coming from? Is that normal?
Here's a picture. The top of the picture is the exterior wall of the house, the pipe is coming in from the drain tile.
Comment: Do you have a radon fan?
Comment: No radon fan installed anywhere
Comment: So cold air is falling thru your drain tile.  No big deal.  What are you concerned about?
Comment: Could be a broken natural gas line in close proximity to your drain tile.  Is there any odor?
Comment: No odor, still checking out what it could be.
Comment: @CarlWitthoft I could imagine myself asking this same question because it would be very disconcerting to feel air blowing out of what I presumed to be a closed system.  Somewhere my presumption was wrong and I would want to figure out how.
Answer: I am a residential builder, but I would suspect this "air flow" is best explained through psychrometrics and the concept of "natural draft".
The air inside the drain tile system will likely be much cooler than the temperature in the basement.  That temperature difference begets a pressure difference, with the cooler air being more dense than warm air. Nature, forever seeking homeostasis, tries to reconcile the pressure difference between the two areas..... and a draft is formed.
This phenomenon can also be known as the "stack effect" when dealing with building construction, and is one of the causes of thermally inefficient homes.  Improperly sized HVAC systems and things such as ventilation fans in bathrooms and range hoods will also serve to depressurize the house.
From a building inspector's point of view there is absolutely nothing to be worried about.
Answer: Usually sump is used for various reasons. In a tropical/sunny regions water is harvested into the sump that falls on the roof during rainy season so that ground water gets replenished in between concrete jungles (cities).
Check when that kinda pipe is running nearby your surroundings. Sometimes air does flow due to tunneling effect based on seasonal changes and that none can tell. Another reason why that put holes are there is if the pit gets overflowed it will come out through that and passage of air instead of different atmospheric pressures when it's dry. Pit is made of different layers of soil like gravel sand charcoal etc etc for filtering the waste water from polluting ground water or water bodies nearby.
Else someone has a underground basement and it's for ventilation :p

What does airflow in the sump pit mean?


Load custom font file from application specific folder

Question: My Win32 application has to load a custom font file from ProgramFiles folder.
Is it possible to load a custom font file from custom location?
If so how can I load a custom font file?
Please suggest.
Thanks,
Answer: Use AddFontResource or AddFontResourceEx
Note:

When an application no longer needs a font resource that it loaded by
  calling the AddFontResource function, it must remove that resource by
  calling the RemoveFontResource function. This function installs the
  font only for the current session. When the system restarts, the font
  will not be present. To have the font installed even after restarting
  the system, the font must be listed in the registry.
Comment: @ manuell sorry for my very late replay.. Yes it works fine. Thank you.


Do settlers need access to the ground to farm?

Question: I usually make a tree house sort of thing, get my settlers in it, and cut off access to the ground.
Do I need someone on the ground to farm, or can they do it from the tree house?
Comment: A more general question of "do settlers need access to stuff for it to work or is assignement enough" would fare better, that is strangely specific. And weird. What do you do when more arrive?
Comment: So, a treehouse jail for those who follow the recruitment signal to your trap? Thats hilarious :D
Comment: When you assign a settler to food production they go to the plants and perform an animation where they bend down and tend to the plants. But I don't know what happens if they can't reach the plants and whether they still produce food.
Comment: The one garden I bothered to build is in a backyard, right up against a house. I'm constantly finding one or two NPCs clipping into the house almost entirely. I'm guessing they still technically "have access" but it may also be an indicator that the whole thing is just for show. You don't need a complicated "treehouse" to test this either. Just set up a bell, call the NPCs, then put up walls all around them so they can't go anywhere.
Answer: Your settlers do not need to have physical access to the the tasks they've been assigned to. Scavengers and farmers will still collect resources even if they cannot reach them.
However, I have noticed that settlers will not be at the last locations they were when I fast travel away and subsequently return to settlements. This means you may find settlers tending to crops on the ground when returning to your settlement.


What language is the music in NieR:Replicant?

Question: NieR:Replicant's lyrics seem to be written in French/Latin, but I can't quiet pinpoint what language the music is in.
Any thoughts on what languages it could be ?
Comment: [Same question _(and I assume, answer)_ for the sequel](https://gaming.stackexchange.com/questions/304030/what-language-is-the-musics-lyrics-in)
Comment: @BlueRaja-DannyPflughoeft It is the same answer. The accept answer even has a quote stating "Its an invented language, *same with the OST of NieR 1*."
Answer: According to an interview on the Playstation Blog, NieR Replicant's lyrics are written in a made-up language named "Chaos Language" that was created by Replicant's signer Emi Evans.

Perhaps one of its most unique details was the made-up lyrics Emi created, suitably named "Chaos Language", invented to sound as if our modern languages had drifted away for thousands of years to finally become indistinguishable to us. "The reason we went for this mysterious made-up language is because we felt that as game music, having lyrics which you can recognize and understand might distract you from the gameplay," explained Yoko Taro, the game's director, when I met him in 2017 ahead of the launch of Nier's sequel, Nier:Automata.
Source: PlayStation Blog - NieR Replicant singer Emi Evans talks music, Chaos Language, and more

The same fictional "Chaos Language" was also used for several songs in NieR: Automata.
I recommend reading the full interview with Emi Evans, as she explains the specific languages that inspired Song of the Ancients, Grandma, The Wretched Automatons, and Kainé.
Comment: It's not just NieR: Replicant that uses Chaos language, it's also used for nearly all vocals in NieR: Automata.  The exception is the song Weight of the World which in addition to Chaos language has English and Japanese versions.  It's possible that NieR: [Re]incarnation also uses Chaos language, but I haven't played that one yet.
Comment: The song "Weight of the World" is featured in three languages: Japanese,  English and French. There are however some hard copy versions of the game which don't have French (don't quote me on that).


Declaring checked exception using throws clause that is never thrown in the body of the method

Question: I understand that catching a checked exception that is never thrown in the corresponding try block is invalid. Because the compiler itself would have forced the programmer to handle the exception if it was to occur.
For example, this code snippet -
try
{
}
catch(IOException e)
{
}

is invalid.
But why doesn't the compiler work the same way for the method that throws a checked exception that has never been thrown in the body of the method?
For example, this code snippet -
void test() throws IOException
{
}

is surprisingly valid.
Please explain the reason behind it. TIA.
Comment: Methods have to be allowed to declare they throw an exception, even if they don't actually throw it, because overriding methods (may) declare that they throw checked exceptions that the base class method throws. And overrides of those methods may need to throw the exceptions.
Comment: Does this answer your question? https://stackoverflow.com/questions/35184092/why-is-catching-checked-exceptions-allowed-for-code-that-does-not-throw-exceptio
Comment: Not exactly. It emphasizes more on catching checked exceptions. My question is regarding declaring checked exceptions that are never thrown.
Answer: Because you might want to allow subclasses to throw this exception.
public abstract class Parent {
  public void doStuff() {}
}
public class Child {
  // this is illegal, because you throw more exceptions than the overridden method
  public void doStuff() throws IOException {}
}

This is even more intuitive for interfaces, the (non-default) methods of which will never throw an exception but can declare it.
Answer:
It is a compile-time error if a catch clause can catch checked
exception class E1 and it is not the case that the try block
corresponding to the catch clause can throw a checked exception class
that is a subclass or superclass of E1, unless E1 is Exception or a
superclass of Exception.

This tells you all these are valid:
try { }
catch(Exception e){}

--
try{ }
catch(NullPointerException  e) {}

--
try{ }
catch(ArrayIndexOutOfBoundsException  e) {}

--
try{ }
catch(RuntimeException e) {}

--
try{ }
catch(Error e) {}

--
try{ }
catch(Throwable e){ }

It's not related to a void block. It's related to an impossible path to your checked subclass of Exception.

What happens with subclasses of Exception? For example IOexception: Those are unreachable catch blocks. Nothing in the try block can lead to that exception, so the compiler just tells you: this block would never be executed, as it would never catch that subException.
The difference with throws: The concept of unreachable code doesn't exist in this context. The possibility of a method throwing an exception doesn't end in the deffinition of the method. For example:
abstract void readFile(String path) throws IOException;

This method doesn't even have a block, as it's an abstract method. It's easy to guess that this line won't ever throw any IOException. But it defines a behaviour for the extensions that will implement it. In order to override it, your method must throw the IOException.
In the same way, if someone overrides your test method:
@Override
void test() throws IOException
{
   readFile(file);
}

It's not impossible to happen, in contrary to your first try-catch block.
Answer: Java follows the rule "handle or declare".
If there is a checked exception declared in your code, you must handle it (in a try/catch block) or declare it (adding 'throws' on method signature).
When you say your method may throw an exception, everyone using your method must handle or declare that exception. If you handle it, you are making your code capable of recovering. If you declare it, you are passing the problem to the caller.
The compiler is fine if you declare 'throws', he knows what to do when your method will be called.
If you declare an exception that is not actually there, you are making users of your code aware that, in a future release, you may add that exception. Users will be prepared for the day you will add that exception.
Answer: Specifying says that method can throw an exception or can not throw. But compiler don't check it, because he can't, actually. So try block only check specifying. The
point is compiler don't see deference between actual calling exception and method's specifying. If you call test() in try block, it'll valid. Sorry for my English)


Can I run a coroutine in python independently from all other code?

Question: I have a piece of code that I need to be ran every hour. What's the best way to run that piece of code independently from all the other code (It's a telegram bot) without having to refactor everything?(Now I know I can use aiogram for this but I'm using different lib) I'm looking for something like a unity c# coroutine (where you simply StartCoroutine and you have that function ran in parallel), but on python 3.9. I've been searching so much for something not very complicated, that I'll be glad even if this piece of code interrupts my main code while executing, as it takes around 1 second to complete.
Answer: You could put your code in a function, then call it using the threading module.
from threading import Thread
from time import sleep

# Here is a function that uses the sleep() function. If you called this directly, it would stop the main Python execution
def my_independent_function():
    print("Starting to sleep...")
    sleep(10)
    print("Finished sleeping.")

# Make a new thread which will run this function
t = Thread(target=my_independent_function)
# Start it in parallel
t.start()

# You can see that we can still execute other code, while other function is running
for i in range(5):
    print(i)
    sleep(1)

And the output:
Starting to sleep...
0
1
2
3
4

Finished sleeping.

As you can see, even while the function was sleeping, the main code execution continued.


Control F with Equal Sign in Excel

Question: I'm trying to use Control+F in my excel workbook but I have an issue. I have 2 sheets that I compare. Sheet A has a record of all my logs and Sheet B has my logs.
When I input the records into Sheet A I simply use = [cell value] from Sheet B. I do this because it's much quicker to use the equal sign then to retype all the information from Sheet B.
However, I can't use the Control+F function to look up my records in Sheet A. Sheet A cell B5 shows "360 LLC" the cell value is ='Sheet B'!E10. So when I type 'Sheet B'!E10 in the Control+F pop-menu I get the record "360 LLC"
Is there a way I can use Control+F to look up "360 LLC" by typing in the pop-up menu 360 LLC instead of 'Sheet B'!E10?
Thanks.
Comment: In the Find and Replace Dialog, under Options, Look in Values.
Answer: When you have the Find box up, select Values for the Look in:  field.  If you don't see these selections, click Options.
Comment: I never knew about this "Look in" option. This is perfect, thanks!
Comment: Is there a way I can lock the "Lock in" to stay on "Values"? I closed my workbook and opened to test it and it reverts back to "Formulas".
Comment: I think the only way to do this is with an Auto_Open macro.  However, I've never tried that.

Control F with Equal Sign in Excel


rotate and repeat image using xml

Question: I want to set background image with rotation and repeating the background image.
For repeating
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/border"
android:tileMode="repeat" />

For rotation
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:toDegrees="90"
    android:pivotX="50%"
    android:pivotY="50%"
    android:drawable="@drawable/border">

Now I want to combine this code in one drawable and want to use as background
I'm trying like this but not working
<?xml version="1.0" encoding="utf-8"?>
   <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
     android:tileMode="repeat" >

   <rotate xmlns:android="http://schemas.android.com/apk/res/android"
      android:fromDegrees="90"
      android:toDegrees="90"
      android:pivotX="50%"
      android:pivotY="50%"
      android:drawable="@drawable/border">
</rotate>

</bitmap>

Comment: you will probably need a custom Drawable, i dont think it can be done in xml only
Answer: I would suggest you to use a custom view. I also tried that for my animated background. Just use thread, handler and canvas.scale() method for rotating the view background. And one thing i wanna ask. Whats the need of setting as background? You can set the rotating drawable as a background view and do the other things on the view above with transparent background.
Comment: I have border image that is divided into two parts. one part of is corner image another part for middle part of two corner that is repeating image
Comment: hi @JatinMalwal i want same result but no luck...can you please provide any code...you can find my question here http://stackoverflow.com/questions/38890063/android-graphics-camera-rotation-scaling-my-image
Answer: <?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="-45"
    android:pivotX="50%"
    android:pivotY="50%">

    <bitmap
        android:alpha=".5"
        android:src="@drawable/image"
        android:tileMode="repeat" />
</rotate>

Comment: Can one specify the size or scale in the same file?
Comment: @rraallvv You can enclose  tag inside  tag and item you can specify android:width and android:height

rotate and repeat image using xml


Vue.js: instantiate functional component programmatically

Question: when I instantiate functional component using this code
const Component_Constructor = Vue.extend(Component);
let component_instance = new Component_Constructor();
component_instance.$mount();

the component gets undefined context argument on the render function
how can i pass parameters (props, slots, children, ...) to the component?
Answer: the only workaround I found so far is to wrap the functional component into another normal component like this:
let AComponent = {
    functional: true,
    name: 'a-component',
    render(h, context) {
        return h('div', context.children[0].text);
    }
};
let template = `<a-component>test content</a-component>`;
let WrapperComponent = Vue.extend({
    components: {AComponent},
    template,
});
let componentInstance = new WrapperComponent().$mount();
let content = componentInstance.$el;

Comment: Doesn't this completely defy the purpose of using functional components?
Answer: As one of the vuejs core team said here https://forum.vuejs.org/t/functional-component-with-vue-extend/40752, you can not mount functional component manually.
$mount() need a vue instance, that a functional component does not have.


Should I leave the drain open on my compressor for storage?

Question: I just got a new air compressor for occasional finish nailing and tire inflation. I understand that I need to open the bottom drain to let out any condensation (i.e., this question) after each use.
Should I also store the compressor with this valve open? Is it a bad idea to do so? If it makes a difference: I only plan to use it once or twice a month and live in a very dry climate.
Comment: Anecdotally, my experience (father and grandfather's practices, handed down) has always been to drain the tank completely after each use, then close the drainage valve for storage.  This prevents environmental contaminants (moisture, dust, insects) from getting into the tank.  But now I'm curious if there's a more formal answer to this.
Comment: I always let it drain after each use, and then close it back up again. I *think* I'm doing it right.
Comment: I've noticed my shutoff valve doesn't work as well, and I used to always leave it open during storage. Perhaps a seal dried out or else it's just a cheap valve. With a tank designed to handle over 100psi, the natural atmospheric pressure changes shouldn't effect it in the slightest.
Answer: Leave the valve closed during storage to prevent moisture, dust, and insects from entering the tank (as @Scivitri wisely mentions in his comment).
Even though any additional moisture could be drained form the tank later, it's more difficult to get the dust and insects out. And they're what's likely to clog up any attachments. They'd also potentially clog the drain valve itself and essentially cause a slow leak until they were removed.
Comment: It sounds logical, but also conflicting with the owner's manuals cited below.  Perhaps if the debris/bugs is a concern it would be best to leave the valve barely open, or to cover it tightly with something like a zip-tied cloth to act as a permiable filter/barrier
Answer: Directly from owner's manual (Central Pneumatic 6 gallon model 67696)

Drain tank of moisture after each day's use.
  If unit will not be used for a while, it is best to leave drain
  valve open until such time as it is to be used. This will
  allow moisture to completely drain out and help prevent
  corrosion on the inside of tank.
Answer: Should be covered in the owner's manual if you can find it.  The manual for mine says to leave the valve open in storage.  Presumably to let the internal/external environment stay equalized to minimize condensation.
Answer: I did scuba diving for years. The general rule was to always leave a minimum amount of air pressure in the vessel, when not being used, so that moisture, or anything else, could not get into the tank. This sounds like good advice for any pressurized vessel as moisture is the #1 cause of corrosion/damage.
Comment: Ben, our SCUBA fills are very dry air to prevent dangerous corrosion and contamination. Thus, we store with a bit of positive pressure. Air compressors do not condition (dry, filter, etc.) their air first and thus there's plenty of moisture to drain from the tank. My manual also states to **leave the drain open** during prolonged storage. It's a Central Pneumatic brand from Harbor Freight.
Comment: There are several reasons dive shops want the tank pressure to be above 2-3 hundred psi. The first is so the shop knows only breathing air is in the tank, very few home compressors can pump to 200 lbs. If the tank has several hundred lbs the shop knows the tank should be clean & dry inside. We don't usually leave tanks full because the tank over time will loose its elasticity and fail the next hydro test (required every 5 years). My breathing air compressor has 3 water separators prior to my bank bottles or fill wip this is not true with standard aircompressors, they put the water in the tank.
Answer: I have always drained my compressors perhaps three times a year , and use it quite often. Depending on the air temp outside, and if it goes down under the freezing temp, I leave the valve open, just in case there is condensation in the tank, but most of the time there is none that comes out after use. Does not make sense to me to leave the valve open at all. Keep the contaminants out of the unit. Chances are that it will do more harm to the inside that prevent anything else.


Can I control storage size in Berkeley DB JE?

Question: I want to use Berkeley DB JE like a disk cache for my application. And max size of cache should be 30 Gb. That is why I need to control it.

Is it any ways to know the size of storage from the code (Java)?
Can I use clearing algorithm like a LRU and Berkeley will clear the db when storage size is over 30 gb?
Maybe some useful information about it?

And, yes, I already read oracle docs (and didn't find needed info).
Answer: If you're using Berkeley DB JE 7.5.11 or later releases, you may want to take a look at the setMaxDisk(long totalBytes) API, which could be used to set the upper limit for your data storage.


Validating Cells Within a Table While Editing

Question: Currently, I have a table where I can edit a row and save it after i am done editing. I want to be able to add validation so for example if the email cell doesn't include an email, then it will not save. I am wanting to display a dialog box displaying the error if you click save and a field hasn't been validated. How can I do this?
Here is what I need:
Buyer ID - numbers only
POC Name - text only
POC Email - email only
POC Phone - phone number only

Relative Javascript:
$(document).ready(function() {
    $('.edit').click(function() {
        var $this = $(this);
        var tds = $this.closest('tr').find('td').not('.mr_id').filter(function() {
            return $(this).find('.edit').length === 0;
        });
        if ($this.html() === 'Edit') {
            $this.html('Save');
            tds.prop('contenteditable', true);
        } else {
            $this.html('Edit');
            tds.prop('contenteditable', false);
        }
    });
    });

Relative HTML/PHP:
<?php
    foreach ($dbh->query($sql) as $rows){
    ?>

        <?php echo intval ($rows['MR_ID'])?>
        <?php echo $rows['MR_Name']?>
        <?php echo $rows['Buyer_ID']?>
        <?php echo $rows['MR_POC_N']?>
        <?php echo $rows['MR_POC_E']?>
        <?php echo $rows['MR_POC_P']?>
        <button class="edit" name="edit">Edit</button>
        <button class="delRow" name="delete" onclick="deleteRow(this)">Delete</button>

jQuery imports:

        <title>Stage Rebate Master HTML Table</title>

        <link rel="stylesheet" type="text/css" href="html_master.css">

Answer: I wrote you a little somthing to get you started, you'll need to add more switch case conditions (I handled buyer_id only) and add the dialog box (I used #myDialogBox) but I think you'll be okay :)
$(document).ready(function() {
    $('.edit').click(function() {
        var $this = $(this);
        var tds = $this.closest('tr').find('td').not('.mr_id').filter(function() {
        return $(this).find('.edit').length === 0;
    });
    if ($this.html() === 'Edit') {
        $this.html('Save');
        tds.prop('contenteditable', true);
    } else {
        var isValid = true;
        var errors = '';
        $('#myDialogBox').empty();
        tds.each(function(){
             var type = $(this).attr('class');
             var value = $(this).text();
             switch(type){
                 case "buyer_id":
                     if(!$.isNumeric(value)){
                          isValid = false;
                         errors += "numbers only in buyer id\n";
                      }
                     break;
             }
        })
        if(isValid){
            $this.html('Edit');
            tds.prop('contenteditable', false);
        }else{
            alert(errors);
        }
    }
});
});

Comment: Unless, there is something I am needing to add, it isn't seeming to work for me in my code.
Comment: Whenever I run it and the table comes up...if I edit the buyer ID so that the cell is blank or there are letters/words, it still lets me save it
Comment: Hmmm interesting....I added my jQuery import code into my post....do those seem correct?
Comment: you might have a conflict - since you use 2 jQuery files (local one and google's one) is there a reason for that?
Comment: there is no reason for it...let me take one out and see if that works
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/124805/discussion-between-jameson-the-dog-and-rataiczak24).


A button with choices

Question: I have list of buttons that can be pressed or unpressed individually (like checkbox functionality). Some of the buttons can also have some attributes (+ or -), but it's uncommon to select those attributes, the far most common is just to use the initial button values.
See my attached image:

The idea of the design is to let users just click the values they want, which is a pretty fast way of doing the choices. If the user want's to add the attribut + or - (available on "b" and "c") - press the button and after some delay a drop down list appears with the choices.
The disadvantage of this, as I see it, is that I try to merge two standard UI elements - a button and a drop down list, is it intuitive?
Unfortunately I don't have the time to make a user testing scenario to test this.
Can I get some feedback on this? Can you suggest a better way of adding + or - to "b" and "c"?
Comment: Are you designing for mouse interaction or touch?
Comment: There's already quite a bit of precedence for this. Examples: Tools pallets in apps like Photoshop, split buttons as you see in many MS apps such as Word, touch devices such as iOS's keyboard.
Comment: Designing for mouse interaction. It's for software, not a website.
Comment: A key feature is that the attributes "+" and "-" are rarely selected, so I feel that the menu doesn't have to be "in your face" obvious. But I don't want users to miss the opportunity to add those attributes - if they want to.
Answer: For mouse interaction you can use split buttons instead of menu buttons. In the buttons "A", "B", ... above you can choose the pressed or unpressed state. With the drop down buttons below you can choose the attributes.
See microsoft ui guidelines
Example with split buttons (not styled):

Other approach: The selection of the attributes is displayed when the mouse is over buttons "A", "B" ....
Comment: thanks for the input. I prefer, as stated on another reply, to keep the number of buttons as low as possible (as any designer would, I guess). But this is an option if the combined drop down/button isn't working out for some reason.
Answer: The way you've proposed it is the way OmniGraffle does it, and I've always found it quite intuitive.  A few details of their implementation:

Their long press is really short; no more than a couple hundred milliseconds before triggering the dropdown.  Makes it feel snappy and responsive.
If the user actually clicks on the small arrow in the lower-right corner of the button, it triggers the dropdown immediately.  While it requires a bit of dexterity, it's nice to have that option available if you know what you want is in the menu.
As you diagrammed, you're retaining the user's selection if they select a sub-item, making it the 'default' choice on the top button.  In my opinion, this is the correct behavior, and it's what OmniGraffle does, too.
As KatDNA mentioned above, make sure you're designing for desktop (mouse) usage.  The interface would necessarily be a bit different on touch (although long-touch is acceptable in a gestural interface to reveal greater complexity, as well)
Comment: It works only for an exclusive selection.
Comment: Yes, this approach seems to be widely used in different programs, and should be pretty straight forward. Thanks for the input on the suggested button behaviors.
Comment: @Sysscore - it will work in my case - a, b, c, d and e are not exclusive selection (for example none, all or just "a" and "c" can be selected). But only one attribute can be chosen for each button, and that is what I need.
Comment: @Hendrik - You're right. With mouse click of the buttons you change the pressed state. With mouse click on the small arrow you can change the attribute (the second point from Daniel). That works.
Answer: My first thoughts on this:
Is it quite necessary to first hide the options and bring into view only after clicking the button? That can come as a surprise to the first time user.
If the button could include the plus and minus signs above and below the symbol [a/b/c/d] and the UI logic is hidden from the user, that might make it much more intuitive. Perhaps also reduce the number of clicks needed.
Comment: What I prefer in my design is the minimalistic design - I want to reduce the number of buttons as much as posible (but, of course, not to a point where it's not intuitive what to do)

A button with choices


How to install JDK5 in Ubuntu 11.04

Question: I have installed 11.04 in my machine. I have installed JDK6 from the repository. My problem is I need to install JDK5 in my machine I have used the following command but its not working.
<code>~$ sudo apt-get install sun-java5-jdk
</code>
It gives the following messages:
<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package sun-java5-jdk
</code>
Please help
Answer: You can manually download it from here: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html  and then install it.
Comment: As a java developer I can confirm that a manual install is the best option for java. Just make sure that you set your paths correctly: `export JAVA_HOME=/data/dev/java/java6 - export PATH=$JAVA_HOME/bin:$PATH`. Pretty easy to switch between different java versions and JDKs that way.
Comment: Can you also give the instructions for installing it once the .bin file is downloaded. Oracle does not have any instructions. Thanks in advance.

How to install JDK5 in Ubuntu 11.04


Move the virtualenvs to another host folder

Question: By error, I forgot to specify the WORKON_HOME variable before creating my virtual environments, and they were created in /root/.virtualenvs directory. They worked fine, and I did some testing by activating certain environment and then doing (env)$ pip freeze to see what specific modules are installed there.
So, whe I discovered the workon home path error, I needed to change the host directory to /usr/local/pythonenv. I created it and moved all the contents of /root/.virtualenvs directory to /usr/local/pythonenv, and changed the value of WORKON_HOME variable. Now, activating an environment using workon command seems to work fine (ie, the promt changes to (env)$), however if I do (env)$ pip freeze, I get way longer list of modules than before and those do not include the ones installed in that particular env before the move.
I guess that just moving the files and specifying another dir for WORKON_HOME variable was not enough. Is there some config where I should specify the new location of the host directory, or some config files for the particular environment?
Answer: Virtualenvs are not by default relocatable. You can use virtualenv --relocatable <virtualenv> to turn an existing virtualenv into a relocatable one, and see if that works. But that option is experimental and not really recommended for use.
The most reliable way is to create new virtualenvs. Use pip freeze -l > requirements.txt in the old ones to get a list of installed packages, create the new virtualenv, and use pip install -r requirements.txt to install the packages in the new one.
Comment: Ok, I was just worried that if I try to set up new virtualenv, something could go wrong because of the WORKON_HOME change. After all, there are bunch of executable files in it. But now I just deleted the failed virtualenv's folder, created with `mkvirtualenv env` anew, and reinstalled the packages. Success! I still don't know what for are those files in the WORKON-HOME, but for now I have functional virtualenvs and I am happy.
Answer: I used the virtualenv --relocatable feature. It seemed to work but then I found a different python version installed:
$ . VirtualEnvs/moslog/bin/activate
(moslog)$ ~/VirtualEnvs/moslog/bin/mosloganalisys.py
python: error while loading shared libraries: libpython2.7.so.1.0: cannot open shared object file: No such file or directory

Remember to recreate the same virtualenv tree on the destination host.


Getting Caret position from JTextArea

Question: I can get row number and column number from Jtextarea by using,
   int caretpos = textArea.getCaretPosition();
   int row = textArea.getLineOfOffset(caretpos);

   int column = caretpos - textArea.getLineStartOffset(row);

How can i get the caret position from row number and column number?
Comment: I guess you are looking for this line `int startOffset = tarea.viewToModel(new Point(x, y));`. Your **row and column** variables can act as **x and y** respectively, in the example that proceeds. For more info have a look at this [example](http://stackoverflow.com/a/10463120/1057230)
Comment: @Gagandeep Bali please I'm sure that you know that better, then this comment should be nice answer :-)
Comment: @mKorbel : I just realized, though the example can give answer to the end question that arises, as to how to insert a String at a specified location by the OP, in another thread, though how to calculate the `CaretPosition` is a bit tricky :-)
Answer: for both your questions, answer could be deleted

Document is Model for JTextComponents
you can to determine int start / end for every row(s)
you can to determine int start / end for Caret by CaretListener
for listening of changes from view is there DocumentListener
for preventing / modifying of input is there DocumentFilter

Getting Caret position from JTextArea


Complex Index Match Only the Month and Year

Question: Using a formula I'm trying to populate table 1
Like this

Conditions are:
-Matching only the month and year
-Combine all qty in the same month
I'm thinking something like index match with month()&year()...
Maybe there is a better formula on how to do this?
Comment: Are the headers `Jan-20` actual dates formatted `mmm-yy` or are they and actual text string?
Comment: Sounds like `SumIfs` would be more appropriate... sum quantity where where the month matches, the year matches, and the fruit matches.
Answer: If the headers on Table 1 are dates formatted mmm-yy  The use this:
=SUMIFS($C:$C,$A:$A,$F2,$B:$B,">="&EOMONTH(G$1,-1)+1,$B:$B,"<"&EOMONTH(G$1,0)+1)

If the headers are text then use this:
=SUMPRODUCT(($A$2:$A$7=$F2)*(TEXT($B$2:$B$7,"mmm-yy")=G$1),$C$2:$C$7)

Comment: you would change `$A:$A,$F2` to `$A:$A,$F2 & " *"` in the sumifs.  In the sumproduct you would change `($A$2:$A$7=$F2)` to `(ISNUMBER(SEARCH($F2,$A$2:$A$7)))` @GimGanDi
Comment: I was just posting similar to this after making the comment about sumifs, thoguh I made columns for month and year in the table... completely forgot about end of month function (`eoMonth`)...
Comment: I couldn't understand the formula but it works.
But say if the fruits are labeled apple 32, apple 31, apple 45 etc.,
Can we add a formula so that it's looking up values before the space?
It's like a text to column delimited by a space
Answer: Given a pivot table can (easily, dynamically and with versatility) return:

others with a very similar requirement my prefer a different solution.


aiohttp with aiohttp-devtools hot reload

Question: I want a similar reloading to what django runserver does.
If I change a python file I want the application to reload.
I've installed aiohttp-devtools and run with adev runserver, yet no reload when I change python files.
Just to be clear, I'm not talking about browser refresh, just the python reloading. I will click the refresh button in the browser myself.
Answer: from aiohttp docs, something like
## filename: app.py

from aiohttp import web
import json

async def handle(request):
    response_obj = { 'status' : 'success' }
    return web.Response(text=json.dumps(response_obj))

app = web.Application()
app.router.add_get('/', handle)
if __name__ == '__main__': web.run_app(app)

and then, based on aiohttp-devtools, in the project directory:
 adev runserver .


What materials can be used to prevent polyurethane glue from sticking to unwanter surfaces?

Question: I am making some board and batten shutters and am using four 5-inch boards to assemble each shutter (each board is ¾ x 5). Since they are going to be outside the house and exposed to the elements, I've decided that a quality polyurethane glue is probably the best choice for gluing the boards together. I also want the shutters to be reasonably flat, so I've decide to clamp them from all four sides (the flat surfaces and sides). For the flat surfaces I'm planning on using 2 x 3 boards with carriage bolts on the ends. But what I don't want happening is for those boards to get glued to the shutter.I originally thought I could prevent that from happening by using wax paper or aluminum foil, but after reading about the properties of polyurethane glue, which will bond just about anything to anything, I'm not sure those are practical choices. I even thought maybe polyethylene garbage bags might be a viable choice. They would probably still get glued to the shutter but could be sanded off afterward and should prevent the polyurethane glue from penetrating to the wooden clamp.Is this a viable alternative, and does anyone have any better suggestions?
Comment: You're not trying hard enough. Some materials do repel polyurethane.  I know because I use them for paint trays and stencils.   I am talking  about real polyurethane paints not latex or alkyds that have pre-cured polyurethane powder in them.
Answer: The following is a carry over from a CNC video I saw many moons ago, but have lost the link.
Give the selected adhesive a sacrificial material on which to bond. Your thoughts of using plastic bags aren't far off, but let's add in a layer of adhesive that you can remove.
If you cover the clamping boards with wide painters tape where the glue is going to contact them, you'd be able to remove the tape from the clamping boards leaving the adhesive side exposed and likely mostly shredded.
If it's practical and possible to apply the tape to the shutter boards with the adhesive side pointing at the shutter boards, you may also reduce the amount of cleanup, as the tape will peel off, again possibly in shreds, leaving behind the tape adhesive and the extruded glue from the shutter joins.
You may be able to minimize the extruded glue by taping on one side the shutter boards along the entire length of the join while held together, then bending the taped joint open and applying the glue. When the boards are flattened, it would be easier to wipe off the glue from only one side, then apply more tape to keep that side from bonding to the clamping boards.
Comment: I have used painters tape but then used a razor knife to score it at the edge and then the tape and glue peel off nicely.


How many Memoria do i need to unlock the Full Story?

Question: I'm playing Dissidia NT, only in Local/Arcade Mode, and i'm getting Memoria while advancing, using different characters and leveling them up, actually i got 8 Memoria, i could enter on the story mode but i want to know first how many Memoria do i need to unlock the full story, so when i start, i won't be stopped to play from the start to the ending.
On the Story mode menu, there are tons of nodes to unlock, and i'm asumming every node is 1 Memoria each, but maybe not, and because i'm not wanting to unlock anything of it yet, i'm asking here.

Thanks for reading me, i'll be waiting for a reply.
Answer: You need 30 Memoria to complete story mode.
Each node and group of nodes cost one Memoria to unlock.
The last node requires 3 Memoria to unlock.
Comment: Thank you very much! Now i won't stop playing until i get 30 memoria, already got 12 :)


Is there any way I can split Location column to Latitude and Longitude?

Question: ALTER TABLE My_table ADD Latitude  VARCHAR(8000)
ALTER TABLE My_table ADD Longitude VARCHAR(8000)

SELECT
    [Latitude] = CONVERT(VARCHAR(8000), SUBSTRING('[Location 1]', ',', 1)),
    [Longitude] = CONVERT(VARCHAR(8000), SUBSTRING('[Location 1]', ',', -1))

I get this error

Argument data type varchar is invalid for argument 2 of substring function.
Comment: Why would you store latitude and longitude as strings?
Comment: @Abde . . . The appropriate data type is a decimal of some sort, perhaps `decimal(10, 6)`.
Comment: Please don't tag spam.
Comment: @GordonLinoff  Thank you for your quick response.I might have putted wrong datatype. I was not sure which data type is suited for Latitude and Longitude.
Comment: Have you tried smaller varchar lengths? aside from 8000?
Comment: @barudo This is one of the sample record I have in my database (39.2346264640, -76.6031273836). yes I have tried with smaller varchar lenghts
Comment: You need different `SUBSTRING` parameters, and the use of the `CHARINDEX()` function. Try: `SELECT [Latitude]=CONVERT(Decimal(16,13), SUBSTRING(Left([Location 1], Len([Location 1])-1), Charindex(',', [Location 1]) + 1, Len([Location 1]))),
 [Longitude]=CONVERT(Decimal(16,13), SUBSTRING([Location 1], 2, Charindex(',', [Location 1]) - 2)`
Answer: Here is a sample based on your data elements. It selects out the Latitude and Longitude based on my understanding of what your query was attempting. This works on a variable for testing purposes:
DECLARE @a varchar(60)
SET @a = '(39.2346264640, -76.6031273836)'

SELECT [Latitude]=CONVERT(Decimal(16,13), SUBSTRING(Left(@a, Len(@a)-1), Charindex(',', @a) + 1, Len(@a))),
    [Longitude]=CONVERT(Decimal(16,13), SUBSTRING(@a, 2, Charindex(',', @a) - 2))

The output in this case was:
Latitude            Longitude
-76.6031273836000   39.2346264640000


How to print to bash file descriptors in awk

Question: I would like to open a file descriptor in bash an later output to that from within awk.
Consider the following bash script:
#! /bin/bash

exec 6>&1
awk 'BEGIN{print "FD1" >/dev/fd/1 ; print "FD6" >/dev/fd/6 }'
exec 6>&-

The problem is that the above is outputting nothing at all.
I use Gnu Awk.
Answer: Put double quotes around the special device file:
awk 'BEGIN{print "FD1" >"/dev/fd/1" ; print "FD6" >"/dev/fd/6" }'

See third from last sentence here for explanation.


Ubuntu 14.04.02 Vs Ubuntu 14.10

Question: I am straight forward asking this question. Why shouldn't I upgrade to 14.10 from 14.04 , apart from the reason that 14.04.02 is LTS.
Moreover everywhere I see the advertisement that "More smarter and faster than ever, Ubuntu 14.10"
Comment: What features of Ubuntu you usually use?
(Development? )
Comment: I avoid non LTS simply because upgrading every 6 months can be very troublesome especially if you use ubuntu for development. Upgrades bring new software but can break old and sometimes needed software. With LTS versions you often avoid these issues.
Comment: This question is primarily opinion based. You will have to examine the differences between support and what your intentions of use are, and make a decision on your own which upgrade path is better for you.
Comment: @ubuntu99: yes I am using ubuntu for development , I basically do web, java as well as android apps.
Comment: Stick to LTS version
Answer: I have version 14.10 at the office and version 14.04.2 at home and I see no difference whatsoever. However, version 14.10 does have a different kernel, which might prove useful if you have some hardware problems in version 14.04. Other changes, from what I read, are minor.
If you are not having hardware problems, I'd say that the reason why you shouldn't upgrade are: (i) 14.04 is LTS (but you said it already) and (ii) generally I find it better (from personal experience) to stay one release behind. The reason for that is that this way you give some time for bugs to be fixed and you avoid some headaches that are related to these bugs. Other than those reasons, I can see no good reason to support (or not) this decision.
Comment: The kernel from 14.10 is available for hardware enabling in 14.04 now, as is the newer Xorg.

Ubuntu 14.04.02 Vs Ubuntu 14.10


Create a list of random even numbers in a specified range using only randint

Question: I'm trying to create a random list with numbers from 0 to 10,000 (inclusive). I need to get a list with even numbers only.
This is my code:
from random import randint

def test(mini, maxx, quantity):
    myl = [randint(mini, maxx) * 2 for i in range(quantity)]
    return myl

print(test(0, 10000, 4))

If I try that, I go past the range of 10000 (because the * 2).
Also, I can only use the randint function.
How do I achieve the desired result?
Answer: Generate random numbers from 0 to 5000 and multiply by 2. You have to operate over the correct range if you want to ensure proper results, and include the fact that your bounds are both inclusive:
def test(start, stop, n):
    start, stop = min(start, stop), max(start, stop)
    realmax = (stop - start + 2) // 2 - 1   # Range from zero, inclusive
    realstart = start + (start % 2)         # Offset to ensure even result
    return [randint(0, realmax) * 2 + realstart for _ in range(n)]

In case you are wondering where (stop - start + 2) // 2 - 1 comes from.

stop - start + 1 is the size of your inclusive range.
Another + 1 is necessary to make // 2 act as a ceil-divide instead of a floor-divide. Taking the range 12-14 as an example, you would want to generate two options, not one.
// 2 just halves the range, but keeps it an integer.
The final - 1 converts a range size into a range boundary, since randint is inclusive and we are starting from zero.
Comment: It's a shame that `randint` is a constraint as `return random.choices(range(start, stop+1, 2), k=n)` is nice and elegant.
Comment: @JonClements. Agreed.
Answer: Use the following code -
import random
>>> lst = []
>>> def evenrandom(lst):
    for i in range(10):       #assuming we need 10 random numbers
        num = random.randint(1,10000)       #note: I have started from 1
                                            #with intention
        if num % 2 == 0:
            lst.append(num)
        else:
            lst.append(num -1)
    return lst

>>> print(evenrandom(lst))
[6932, 1690, 5526, 1282, 8332, 2024, 8600, 9500, 1264, 4350]

Comment: The `if` can be rephrased as `lst.append(num - num%2)`. That being said, you should start from zero, otherwise the probability of getting zero will be less than all the other numbers in your range.
Answer: def test(mini,maxx,quantity):
    myl = [randint(mini,int(maxx/2)) * 2 for i in range(quantity)]
    return myl

Comment: 12, 14 is a totally valid input. My point is that your function assumes that mini is going to be zero, which it's generally not, or it wouldn't be an input.
Comment: What if you put in `mini=12, maxx=14`?
Comment: obviously, don't do that:) You should check the input validity elsewhere.


Is it possible to style an custom element of Polymer with an external css file

Question: Is it possible to style a custom element with an external css file that is linked on the index page but not in an element itself. I haven't found any documentation about using a css file not within the element itself.
I have something like this example.

/* Use of only 1 css for all elements */
<link href="css/custom.less" rel="stylesheet/less" type="text/css">

<my-element></my-element>

<my-other></my-other>
<my-other2></my-other>

The problem is that the styling has been done in Firefox but not in Chrome.
So I know it's not a problem with the css.
Css looks something like this.
my-element {
    header {
        background-color: @article-color;
        text-align: center;
        margin-bottom: 25px;

        h1 {
            color: #ffffff;
        }
    }
}

/* Styling of other elements */

I know I can use css within the polymer element itself, but I don't want to do this. I have multiple elements and I want to style all of them within one css file that I link in the index file like in the example.
Answer: It is possible to style custom elements from the index file using a ::shadow or the /deep/ pseudo-element.
Example:

<my-element></my-element>

But please know this before you use it,according to the Polymer docs this method is not very efficient in execution, meaning it could potentially slow the rendering of the page if used a lot.
More info about ::shadow and Styling Custom elements at:
https://www.polymer-project.org/0.5/articles/styling-elements.html
https://www.polymer-project.org/0.5/docs/polymer/styling.html
Comment: I tested the difference from styling inside the element or external and there is indeed a noticeable loading difference. So I will place my css inside the element.


What is going on here? An inmate beatdown?

Question: I have a Protective Custody (PC) dormitory for snitches and ex-cops, and I have one that is "Extremely Volatile". I didn't get the usual flash of a guard icon when there is a fight, and there's no sound bit for this fight, but it looks like the guards are beating the hell out of the inmate. The mouseover says the inmate is "Spoiling", but I have no idea what that means. A reddit post showed something similar but didn't provide any answers. Also, the PA wiki doesn't show anything for "Spoiling" in the Status Effects section.
Any thoughts on what is going on here?

Update: Two in-game days later, this is still happening, the guards are really working this guy over. Man he can take a beating!
Update Two: On a hunch, I reclassified him as a Minimum Security inmate, and ended his permanent lockdown (How I keep the PC inmates in their dorm, has worked so far) and the guards tazed him immediately and then left. I reclassified him as PC/Permanent Lockdown and it seems fine. I have no idea what happened here though, still looking for answers.
Update Three:
This seems to me to be a bug, as I originally thought and Sumurai8 thought as well. The issue was that he was constantly being violent, and permanent lockdown with other inmates didn't do any good either. I ended up taking care of the issue old-school: I removed his PC status, ended his permanent lockdown and assigned him to the max-sec wing. He immediately went into the common room to lift weights, where 3-4 other tough looking fellows were there. An inmate with a bandana followed him into the common room, and took care of the problem. He already had a life sentence, so what's another one? Issue resolved. I almost feel guilty about it. If only inmate Doney could have controlled that temper. #shawshank #gonnahaveanaccident.
Comment: If he is volatile I'm guessing he was starting the trouble and the guards were reacting to it. Check his needs, if he has a high freedom need being on permanent lock down would probably keep him constantly pissed off. Strange that moving him to minimum and back to protected custody seems to have fixed it, it might have been a bug that came out of a loop of some sort with the reclassification.
Comment: Well since then, he has picked fights with the guards, but it's the usual fight, with a flashing guard icon and they taze him, and fight over. Previous it was a neverending beatdown. Probably a bug I'm guessing.
Answer: I believe the "Spoiling" action takes place when the bladder need is filled up, and the prisoner can not reach a toilet in time. It's bladder will go down, as will it's hygiene. When a prisoner is in "fight mode" it will ignore any of its needs. It will only beat anything that comes in its path.
The Spoiling behaviour type is what happens when the privacy need it not met. The privacy need is not met because you locked people up in a dormitory. Consider building seperate cells for your protected custody inmates.
Your inmate should have been knocked out and put in cuffs when they started fighting, but it seems it was bugged. By manually taking control and changing how the prisoner was classified, you started a different traject where the prisoner is cuffed, and transported.
I recommend to use the permanent lockdown feature only for prisoners that are otherwise dangerous to the prison (e.g. gang leaders). Use the designated "protected custody" for ex-cops and snitches, so those prisoners can fulfil their needs.
Comment: Another solution is to simply feed PC prisoners at different times, where other prisoners aren't in the canteen
Comment: Protected Custody and Permanent Lockdown are not mutually exclusive. If I put them in PC, they will still eat in canteens during the Eat regime, and get shanked there, unless I build them a separate canteen, but usually I don't have enough PC inmates to warrant it.

Also, I've seen dozens of inmates "Defecating and Urinating" (that's what it says in the action piece) when they don't want to/can't make it to a toilet in time, and I've never seen the word "Spoiling" anywhere else.
Comment: I've looked up the file with needs. The Bladder need causes the Urinating behaviour if not met, the Bowels need causes the SoilSuit behaviour, which I mistook for the one you encountered. The Spoiling behaviour is what happens when the privacy need is not met, which is caused by locking people up in a dormitory with other inmates. I still recommend to only put dangerous prisoners in permanent lockdown. You only have to build a 4x6 canteen and an even smaller kitchen. Permanent lockdown causes riots.
Comment: That only works if you lock up the rest. Otherwise prisoners will wander into that general area for some reason or another.
Comment: @Sumurai8 You can lock your PC prisoners in your PC wing by having it accessible only through a corridor marked as "staff only". That way prisoners will be unable to leave it on their own during free time and will only escorted through it by a guard when they have some important business to attend to (cell transfer, release...).


Using NOT in quick filters

Question: We have an option in our system to use a quick filter as "not"
See example:

We have a keyboard shurtcut to use this option but the downside is that users are not aware of that option.
Second is that visually it is probably not good to use strikthrough as it affects filters readability.
Do you have some ideas on how to visualize this in a better way?
And how to expose this option?
Comment: The problem is that you're using an **antipattern**, this is NOT the way to use pills in filters. The whole idea is that you only show those pills you're using to filter results, and the only available interaction should be the *"delete"* action. Hence, since it's an antipattern, you might expect problems (as you already have found). If you want to keep the filters visible at all times, you should use `checkboxes` which users can enable and disable without any cognitive effort.
Comment: It may be, the colors can help too. And, as @Devin told, try to use `checkboxes`, possibly, for most frequently used keywords.
Answer: Nothing is more clear than explicit text.
Why don't you say exactly that:

Filtering "Design" not "New" not "In progress"

Maybe color code the tags for additional effect.
I don't know how do users add those filters, but maybe it's good idea to do two lists:

Including Design
Excluding New In progress
Answer: I don't think it's necessary to interfere with the text. Using show and hide icons would be enough:
Comment: Thanks, It should be clear to the users that "Phase - is not - New, In Progress" I'm not sure it's not confusing, I would assume it means something like show/hide values.

Using NOT in quick filters


Fourteen indviduals are to be divided into comittee of three, four and seven members

Question: How many ways can the individuals be grouped?
$${14\choose3}\cdot{11\choose4}\cdot{7\choose7}$$
Is this the right way to approach this?
Comment: Yes, that looks right to me!
Comment: @Billy Thank you for the help
Answer: Yes, your answer is fine. It reduces to the multinomial coefficient
$$\binom{14}{3,4,7}=\frac{14!}{3!\,4!\,7!}$$
if you write it out and perform the most obvious cancellations:
$$\binom{14}3\binom{11}4\binom77=\frac{14!}{3!\,\color{green}{11!}}\cdot\frac{\color{green}{11!}}{4!\,\color{magenta}{7!}}\cdot\frac{\color{magenta}{7!}}{7!\,0!}=\frac{14!}{3!\,4!\,7!}\;.$$
Comment: @Thomas: No, that was a mental hiccup.
Comment: Really, Brian, cyan on white? Even I had trouble reading this. You'd better hope that Asaf doesn't come across this answer.
Comment: @Rick: I prefer red, but I was consciously avoiding it for precisely the reason that you have in mind, blue doesn't contrast well with black, and yellow is worse than cyan. It's a toss-up between green, which has mediocre contrast with black, and cyan, which to my eye is brilliantly present but hard to read against the white background. I've changed it to green, but I'm not at all sure that it's a net improvement.
Comment: It's a bit better, at least for me. I've never tried it and frankly don't know how I'd do it in LaTeX, but I recall having seen cancelling strikethroughs as one might do on paper. Maybe I'll go over to the TeX SE site and ask.
Comment: @Rick: There's a `\cancel{}` that produces a diagonal cancellation, but it's not in the MathJax library.
Comment: Well, it can be brought into MathJax on demand by using `\require{cancel}`, but the cancel package is of limited use for our purposes. I was amused that the documentation ends with the sentence "I don't recommend that you use this package at all".
Answer: The answer is simplest written as $\,\dfrac{14!}{7! \,4!\, 3!}.\,$
The factorial $N! = N.(N-1)\cdot (N-2) .. 3\cdot 2\cdot 1$ being the number of permutations possible for a group of size $N.$
Comment: But 14!/(7! 4! 3!) is the same as what the original poster wrote, isn't it?
Comment: @ Johannes Thank you for helping me out
Comment: @Billy -- correct, but I thought it more insightful to represent it in this simple form.


How to create a Video Player

Question: I'm trying to create a simple video player with 3 buttons: play, stop and pause. My video will be from the raw folder or at a server url that I will upload it to. Do you have any tutorial on this in order to get some ideas? Also, I have created a media player with a song, but I think that this can't work for videos, right?
Comment: another way would be to add a flash video player in my project and just add my video inside it..
Comment: If you made it flash, you'll limit your product to those few phones that support flash.
Comment: another ready video player except from flash??
Comment: Look at your answers!  Those aren't flash!
Answer: There's a project sample in the SDK for the VideoView. You can attach a MediaController to it, which will show you play/pause stop and skip buttons. It's also on the developer website, here.
Answer: this may be what you are looking for: http://davanum.wordpress.com/2009/12/04/android-%E2%80%93-videomusic-player-sample-take-2/
To make this more abstract, the VideoView Widget is what you need.

How to create a Video Player


Expand/collapse group nodes in ExpandableListView based on passed Cursor values?

Question: I've got a ExpandableListView widget that is populated using an adapter based on the SimpleCursorTreeAdapter as shown below. I I query my SQL database for the ListView's group titles as well as a boolean value to whether the group should be expanded or collapsed (which is returned in a Cursor). I then feed this Cursor to my adapter and the list is populated and displayed.
The only thing I can't do, is have the group nodes in the ListView be expanded or collapsed based on the boolean value in the supplied Cursor. I want to have this happen when the activity containing this ExpandableListView widget is initally created, loaded, and displayed.
Is there a way to have my adapter take the boolean values supplied in the Cursor object and use them to expand or collapse these group nodes?
public class MyExpandableListAdapter extends SimpleCursorTreeAdapter
    {
        public MyExpandableListAdapter (Cursor cursor, Context context, int groupLayout,
                                        int childLayout,
                                String[] groupFrom, int[] groupTo,
                                       String[]childrenFrom,int[]childrenTo)
        {
           super(context,cursor,groupLayout,groupFrom,groupTo,childLayout,childrenFrom,childrenTo);
        }

    @Override
    protected Cursor getChildrenCursor(Cursor groupCursor)
    {
        String strCategory =
                   groupCursor.getString(groupCursor.getColumnIndex("strCategory"));

        Cursor cur = mainActivity.mDbHelper.getCardTitlesForCategory(strCategory);

        return cur;
    }
}

Thanks for your suggestions and advice.
Comment: I am doing something similar HERE http://stackoverflow.com/questions/10611927/simplecursortreeadapter-and-cursorloader
Answer: Yes, there is a way!
I had the same problem and I used this code in my Activity:
private void expandGroups() {
    // ExpandableListView scheduleListView
    int itemsCount = this.scheduleListView.getCount();
    if(itemsCount > 0) {
        long timeNowSec = (new Date()).getTime()/1000 - ONE_DAY_SEC;
        Cursor cursor = null;
        SimpleCursorTreeAdapter adapter = (SimpleCursorTreeAdapter)this.scheduleListView.getExpandableListAdapter();
        for(int i=0; i<itemsCount; i++) {
            cursor = adapter.getGroup(i);
            long dateSec = cursor.getLong(cursor.getColumnIndex(DbDefinitions.TABLE_PAIRS.FIELD_DATE));
            if(dateSec > timeNowSec) {
                this.scheduleListView.expandGroup(i);
            }
            else {
                this.scheduleListView.collapseGroup(i);
            }
        }
    }
}

In this code I expand all groups where date older then current date.
Hope this helps.
Answer: Try this (place code to your activity onResume() or another useful place). After ExpandableListView and adapter are initialized, you can expand group nodes depending by cursor values:
    Cursor groupCursor = your_adapter.getCursor();
    if( groupCursor.getCount() > 0 && groupCursor.moveToFirst() ) {
        do {
            boolean isExpanded = groupCursor.getInt( ....) > 0;
            if( isExpanded ) {
                your_list_view.expandGroup( groupCursor.getPosition() );
            }
        } while( groupCursor.moveToNext() );
    }


Reactstrap: "Adjacent JSX elements must be wrapped in an enclosing tag"?

Question: I'm trying to make a faux shopping website for my React course and I keep getting the following message:

Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>? (53:6)

Here's a look at the code that should, in theory, work.
import React from 'react';
import ReactDOM from 'react-dom';
import Producto from './Componentes/producto';
import './App.css';
import {Container} from 'reactstrap';
import {Row} from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
      {/* Plantilla para producto disponible en producto.js */}
        <Container>
          <Row>
              <Producto
                titulo='Doom Eternal PS4'
                imagen='https://www.weplay.cl/pub/media/catalog/product/cache/d406ac87fd7d160c9527a5559b847e93/p/s/ps4_doom-eternal.jpg'
                descripcion='Los ejércitos del infierno han invadido la Tierra. Ponte en la piel del Slayer en una épica campaña para un jugador y cruza dimensiones para detener la destrucción definitiva de la humanidad.'
                precio='666'
              />
              <Producto
                  titulo='Nintendo Switch'
                  imagen='https://images-na.ssl-images-amazon.com/images/I/71ivrWiYkLL._AC_.jpg'
                  descripcion='Consola Nintendo Switch Black'
                  precio='229.000'
              />
              <Producto
                titulo='Consola SONY PS4'
                imagen='https://estaticos.elperiodico.com/resources/jpg/9/8/playstation-sony-1370947347089.jpg'
                descripcion='Consola PS4 SLIM 500GB '
                precio='199.990'
              />
              <Producto
                titulo='Consola XBOX ONE'
                imagen='https://compass-ssl.xbox.com/assets/dd/2e/dd2ef163-a130-403a-a394-a5b11c1533c8.jpg?n=Xbox-Family_Image-0_X1S-1111_496x279.jpg'
                descripcion='Consola Xbox One solo juegos digitales '
                precio='229.000'
              />
              <Producto
                titulo='Consola New Nintendo 2DS'
                imagen='https://http2.mlstatic.com/nintendo-2ds-xl-black-and-turquoise-nuevo-D_NQ_NP_615117-MLM27995821063_082018-F.jpg'
                descripcion='2DS XL Black Turqoise'
                precio='129.990'
              />
              <Producto
                titulo='Big Chungus PS4'
                imagen='https://static.wikia.nocookie.net/big-chungus/images/7/7a/AB851D95-0AA6-496D-83FC-6616222C8F01.jpeg'
                descripcion='El videojuego más del mundo'
                precio='999.999.999'
              />
          </Row>
        </Container>
  );
}

export default App;

Here's the GitHub repo, if anyone would like to run this locally.
I've tried adding several different containers for the code such as

 and <fragment>, but none would work. What am I doing wrong?
Answer: The comment above the  tag is considered to be its own JSX element, because it's enclosed with curly braces. Move it one line below and it will work fine!
<Container>
{/* Plantilla para producto disponible en producto.js */}

Answer: I cloned Your project and added one crucial thing. React fragments, shorter syntax works perfectly fine  <></>.
Example in Your case:
function App() {
  return (
    <>
      {/* Plantilla para producto disponible en producto.js */}
      <Container>
        <Row>
          <Producto />
          <Producto />
        </Row>
      </Container>
    </>
  );
}

export default App;

App.js from Your repo.
import React from "react";
import Producto from "./Componentes/producto";
import "./App.css";
import { Container } from "reactstrap";
import { Row } from "reactstrap";
import "bootstrap/dist/css/bootstrap.min.css";

function App() {
  return (
    <>
      {/* Plantilla para producto disponible en producto.js */}
      <Container>
        <Row>
          <Producto
            titulo="Doom Eternal PS4"
            imagen="https://www.weplay.cl/pub/media/catalog/product/cache/d406ac87fd7d160c9527a5559b847e93/p/s/ps4_doom-eternal.jpg"
            descripcion="Los ejércitos del infierno han invadido la Tierra. Ponte en la piel del Slayer en una épica campaña para un jugador y cruza dimensiones para detener la destrucción definitiva de la humanidad."
            precio="666"
          />
          <Producto
            titulo="Nintendo Switch"
            imagen="https://images-na.ssl-images-amazon.com/images/I/71ivrWiYkLL._AC_.jpg"
            descripcion="Consola Nintendo Switch Black"
            precio="229.000"
          />
          <Producto
            titulo="Consola SONY PS4"
            imagen="https://estaticos.elperiodico.com/resources/jpg/9/8/playstation-sony-1370947347089.jpg"
            descripcion="Consola PS4 SLIM 500GB "
            precio="199.990"
          />
          <Producto
            titulo="Consola XBOX ONE"
            imagen="https://compass-ssl.xbox.com/assets/dd/2e/dd2ef163-a130-403a-a394-a5b11c1533c8.jpg?n=Xbox-Family_Image-0_X1S-1111_496x279.jpg"
            descripcion="Consola Xbox One solo juegos digitales "
            precio="229.000"
          />
          <Producto
            titulo="Consola New Nintendo 2DS"
            imagen="https://http2.mlstatic.com/nintendo-2ds-xl-black-and-turquoise-nuevo-D_NQ_NP_615117-MLM27995821063_082018-F.jpg"
            descripcion="2DS XL Black Turqoise"
            precio="129.990"
          />
          <Producto
            titulo="Big Chungus PS4"
            imagen="https://static.wikia.nocookie.net/big-chungus/images/7/7a/AB851D95-0AA6-496D-83FC-6616222C8F01.jpeg"
            descripcion="El videojuego más del mundo"
            precio="999.999.999"
          />
        </Row>
      </Container>
    </>
  );
}

export default App;

Output in VScode terminal

Output in browser (console). I blurred the images for obvious reasons.


java.lang.NullPointerException Error in Robolectric tests

Question: I'm trying to test a method for saving to the internal memory on android but All my tests for it are coming up as "Test in error" when I package the app with Maven, when I check the individual test results it says there was a java.lang.NullPointerException in the class, From what I've read it might be something to do with the context that I pass in but I've tried several different methods on generating a context and nothing's worked so far, any advice on how to get these to work would be greatly appreciated. The code for the test:
@RunWith(RobolectricTestRunner.class)
public class SaveSystemTest {

SaveSystem testSS;
Route testRoute;
@Before
public void setup()
{
    testRoute = new Route(new LatLng(54.6279022,-5.9146021), new LatLng(54.6279022,-5.9146021),"testRoute");
    testSS = new SaveSystem("testSave",Robolectric.application.getApplicationContext());
}

@org.junit.Test
public void saveTest()
{
    boolean b = testSS.save(testRoute);
    assertTrue(b);
}

The Code for saveSystem.save (Didn't originally have the try catch but I added that trying to get this to work):
public boolean save(Route file)
{
    routeList.add(file);
    try
    {
        if(saveToMemory())
            return true;
        else
            return false;
    }catch (Exception e)
    {
        Log.d("SaveSystem", "Exception: " + e);
        return false;
    }
}

Code for saveSystem.saveToMemory:
private boolean saveToMemory()
{
    try
    {
        FileOutputStream fos = context.getApplicationContext().openFileOutput(saveFileName,Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(routeList);
        os.close();
        return true;
    }catch (Exception e)
    {
        Log.d("SaveSystem", "Exception: " + e);
        return false;
    }
}

Comment: You should include exception stack trace and specify code line where exception is thrown.
Comment: I'm relatively new to android development, how would I get the exception stack trace using maven?
Comment: it depends on your specific situation. If you're using surefire plugin check out `target/surefire-reports` directory for verbose reports on test executions.
Comment: [here's](http://pastebin.com/GAHXLJ8h) the stack trace
Answer: If you use members in your class which are included via Dependency Injection, you should provide a way to pass in a mocked Object for this context, since they are only injected in runtime of your application and not in your tests.
For a good mocking library, have a look at Mockito.
Answer: Stupid mistake, turns out I hadn't initialised the "routeList" List correctly.


NVIDIA kernel installation fails on GeForce 310M

Question: This question is not a duplicate of the question correct kernel source path There the problem was solved be installing the kernel header files. In my case the kernel header files are already installed.
Before you flag as duplicate: I believe I have read all sources to this topic and still the NVIDIA kernel module build fails with 'unable to locate kernel
source'.
Ubuntu 14.04, trying to install
cuda_7.5.18_linux.run (md5sum: 4b3bcecf0dfc35928a0898793cf3e4c6)
~# uname -r
3.19.0-39-generic

~# ll /usr/src/
total 28
drwxr-xr-x  7 root root 4096 Dec 10 15:12 ./
drwxr-xr-x 10 root root 4096 Aug  5 01:12 ../
drwxr-xr-x 24 root root 4096 Dec  4 12:13 linux-headers-3.19.0-37/
drwxr-xr-x  7 root root 4096 Dec  4 12:13 linux-headers-3.19.0-37-generic/
drwxr-xr-x 24 root root 4096 Dec  7 09:45 linux-headers-3.19.0-39/
drwxr-xr-x  7 root root 4096 Dec  7 09:45 linux-headers-3.19.0-39-generic/
drwxr-xr-x  4 root root 4096 Dec 10 14:55 linux-source-3.13.0/
lrwxrwxrwx  1 root root   47 Nov 30 23:38 linux-source-3.13.0.tar.bz2 -> linux-source-3.13.0/linux-source-3.13.0.tar.bz2

When started with
~# sh cuda_7.5.18_linux.run

or
~# sh cuda_7.5.18_linux.run --linux-kernel-path /usr/src/linux-headers-3.19.0-39-generic/

installation fails with the same error: Unable to locate kernel sources...
Comment: Please see http://askubuntu.com/questions/537607/correct-kernel-source-path
Comment: Found a hint in the nvidia installer log. The 310M is not supported in CUDA 7.5. Instead there's a legacy driver that can be downloaded separately.
Comment: I read this question/answer already. It says to install the header files which are there. The problem persists.
Comment: What type of GPU `Ex: GTX 980`
Comment: lspci: 01:00.0 VGA compatible controller: NVIDIA Corporation GT218M [GeForce 310M] (rev a2)
Comment: If you have tried and failed to install the nvidia drivers you may have a bunch of related garbage that's interfering. See: http://askubuntu.com/questions/481414/install-nvidia-driver-instead-nouveau/481540#481540
Comment: What version of Ubuntu do you have?
Comment: Ubuntu 14.04 (see question)
Comment: @ElderGeek I read that QA already. The nouveau driver is not the problem. I blacklisted that and rebooted the system and stopped the lightdm manager successfully.
Comment: I just edited the answer for the legacy driver.
Answer: First run:
wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1404/x86_64/cuda-repo-ubuntu1404_7.0-28_amd64.deb

Then:
sudo dpkg -i cuda-repo-ubuntu1404_7.0-28_amd64.deb
sudo apt-get update
sudo apt-get install cuda -y

After that, it should work.