Prevent /usr/lib/xorg/Xorg from using GPU Memory in Ubuntu 20.04 Server

Question: On an fresh Ubuntu 20.04 Server machine with 2 Nvidia GPU cards and i7-5930K, running nvidia-smi shows that 170 MB of GPU memory is being used by /usr/lib/xorg/Xorg.
Since this system is being used for deep learning, we will like to free up as much GPU memory as possible.
Question: How can we prevent gnome and Xorg from taking up 179 MB of GPU memory?
Output of nvidia-smi
Sat Oct  3 20:27:19 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.66       Driver Version: 450.66       CUDA Version: 11.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  GeForce GTX 1080    Off  | 00000000:02:00.0 Off |                  N/A |
|  0%   54C    P8    11W / 210W |      7MiB /  8119MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 1080    Off  | 00000000:03:00.0 Off |                  N/A |
|  0%   50C    P8    10W / 210W |    179MiB /  8116MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      1109      G   /usr/lib/xorg/Xorg                  4MiB |
|    1   N/A  N/A      1109      G   /usr/lib/xorg/Xorg                166MiB |
|    1   N/A  N/A      1189      G   /usr/bin/gnome-shell                9MiB |
+-----------------------------------------------------------------------------+

Comment: Possible:  https://askubuntu.com/questions/869496/force-xorg-to-use-cpu-not-gpu  Unfortunately I don't have a way to verify it since I only use 1 video card in my system.
Answer: I had the same issue. Many of the suggestions were saying to edit /etc/X11/xorg.conf which doesn't exist for me on Ubuntu 20.04. I needed to keep X11 because I occasionally use X2go or X11 over SSH. I did manage to find a file /usr/share/X11/xorg.conf.d/10-nvidia.conf and then commented out all the lines with #. I was then able to restart X11 with:
sudo systemctl restart display-manager

Voilà, no more GNOME/X11 on GPU.
$ nvidia-smi
Wed Feb  3 19:44:02 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.102.04   Driver Version: 450.102.04   CUDA Version: 11.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  GeForce RTX 208...  Off  | 00000000:01:00.0 Off |                  N/A |
| 27%   33C    P8     1W / 250W |    882MiB / 11019MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 1070    Off  | 00000000:4D:00.0 Off |                  N/A |
|  0%   41C    P8    10W / 151W |      2MiB /  8119MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A   1075324      C   python                            879MiB |
+-----------------------------------------------------------------------------+

Comment: For a remote computer for deep learning processing, it works pretty well. No issue with the resolution drop over an ssh terminal.
Comment: I commented out everything in `/usr/share/X11/xorg.conf.d/10-nvidia.conf`, then restart the display manager as you said. Then my max resolution drop to 1024.
Comment: Careful! I commented out everthing as well but when i commanded systemctl restart, screen went black and did not come back even after several reboots. I had to open the recovery mode root shell and removed commented lines.
Answer: I have a setup with Nvidia 2080 GPU. I have observed that remoting into the machine via xrdp leads to a GPU use of only 14 Mb. If a physical screen is connected, it consumes the memory as per the screenshot posted above.
Edit: Even chrome remote desktop leads to xorg consuming just 14 Mb of GPU RAM
Answer: I just figured out today that since I am remote ssh to server, and most the gpu memory is consumed by gnome_shell and xorg, I can simplify "turn off the auto-login" then my gpu memory usaged is reduced from 450MB to 68MB. That's good enough to me.
(base) ➜  /boot nvidia-smi
Sat Apr 15 18:30:57 2023
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.105.17   Driver Version: 525.105.17   CUDA Version: 12.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  Off  | 00000000:26:00.0  On |                  N/A |
|  0%   53C    P8    19W / 240W |     72MiB /  8192MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A     69418      G   /usr/lib/xorg/Xorg                 61MiB |
|    0   N/A  N/A     69559      G   /usr/bin/gnome-shell                7MiB |
+-----------------------------------------------------------------------------+


Red wool command not working

Question: I am trying to make a mini-game on Minecraft bedrock. In the mini-game different blocks that you place activate different things, but when I tried using the red wool command it kept telling me there was an unexpected error.
The command is:
execute if -43 4 139 Minecraft:wool 14 run setblock -19 4 169 redstone_block replace

I tried everything I could, Minecraft:wool 14, Minecraft:red_wool, etc.
Comment: Welcome to Arqade! Please note that we are *not* a forum, we are a knowledge base of popular questions about video games. We would prefer that you take effort into formatting your posts so that they will serve well for future readers to browse.
Answer: This is an issue with the fact that you used a command that was created for Minecraft Java Edition, but you are attempting to run it on Minecraft Bedrock Edition.
The correct way to accomplish your task on Minecraft: Bedrock Edition would be to use the /testforblock command to test for the block's existence, then follow that with a chain, conditional command block which runs the desired command:
 testforblock -43 4 139 wool 14
 setblock -19 4 169 redstone_block

Red wool command not working


Is there anywhere to archive off unfinished Bugs and PBIs?

Question: In TFS 2010 ss there anyway to move items to a state or something which won't appear in the Product Backlog?
We have 300+ Bugs and PBIs which are never going to be done at this stage. I've like to remove them from the Product Backlog but not delete them.
Answer: In that situation I'd add a new status such as "Not going to do it" or "Never".  Then assign those work items to that status.
Then I'd update the reports to specifically exclude anything with that status.
Answer: The Product Backlog is displaying all PBIs that are not in Closed state therefore if you don't plan to use anymore these PBIs you can set them to Closed state.
Comment: I don't have a "Closed" state in my template. I'll have to edit the template I think and add a new state.
Comment: Indeed, the default Product Backlog of Scrum template is displaying the PBIs that are not in Done or Removed states (not Closed).


How to see if a video link exists or is null

Question: I am playing always the same video link from a financial web site to my Web site. The only change in the link from day to day is the date of the video.
The video for the actual day is not always available at the same time. I have to show the latest video available.
My question is what would be the code to look and see if the link for today exists so that I will use today's link or if null I will show only the latest available video.
Answer: C#
Better to do it from the server and not the client. Look to see if the file is there with C#. If not give it one that is. File.Exists
JavaScript
This is not as good since it means extra http requests. If the file is on the same domain, make an Ajax call to it. Use a HEAD request. If it gets the file, you know it is there. If it errors, you know it is not there.
Comment: Thank you very much epascarello


Get the directory inside the jar

Question: How to get the directory inside the jar?
Let's say I have a jar called foo.jar, how can I make the jar be able to access a file that's like this foo.jar!/text.txt, whereas the class is like foo.jar!/randomPackage/Main.class?
I'm able to do that while still in eclipse, but then when I export the program into a jar, it doesn't work.
Answer: You need to use, e.g., java.lang.Class.getResourceAsStream() to access the file. That will work either inside a jar or on the filesystem.
Comment: @Martin, there *is* no directory in a jar file -- files just have path names associated with them -- so it doesn't make sense to ask for access to it. There's no way to list the files in a jar file without opening it using something like `ZipInputStream`. But note that depending on the argument you pass it (read the Javadoc), the `getResource()` family of methods can find files "next to" class files, or at the root of a classpath entry, or indeed, anywhere along the classpath, inside a jar or out.
Comment: Right, though how can I get the parent directory, because this gets me the directory of the class?
Comment: Prefix the String you pass with `/`, to reference the root of the jar.
Answer: You have 2 main options.

this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");
this.getClass().getResourceAsStream.("/some/pkg/resource.properties");

I just posted this more full post on it recently, getResourceAsStream returns null

Get the directory inside the jar


What spelling dictionaries does Ubuntu use?

Question: Do all applications use the same dictionary for spell checking? If not, which applications use which dictionaries in a typical desktop installation, or where can I find out?
Answer: Some apps are using a common dictionary (such as Evolution, which use aspell-* packages). Some apps are using their own dictionary, such as Libreoffice, which uses libreoffice-l10n-[language code] and language-support-writing-[language code] packages.
Comment: Where can I find out about applications besides those you've used as examples?


More Properties of Entire Functions

Question: A couple more questions about entire functions that I'm having difficulty with:
(1) Suppose $f$ is entire with $f(0)=0$ and $|f(z)|\leq e^{1/|z|}$ for all $z\neq0$.  Must $f$ be identically $0$?
(2) Suppose that $g$ is entire with $g\circ g=g$.  If $g$ is not constant, must $g$ be the identity?
Thanks again for any/all advice.
Comment: The answer to your first question is yes, because $f$ will be bounded entire.
Comment: I see, we use continuity of $f$ to get a bound near $0$, and we have a bound everywhere else
Comment: for 2), take a power series rep and compare (to get $g(z)=z$)
Answer: (1) If $f$ is bounded on $\{z:|z|\leq M\}$ and on $\{z:|z|\geq M\}$, then $f$ is bounded on $\mathbb{C}$.
(2) The equation $g\circ g=g$ implies that $g$ is the identity when restricted to the range of $g$.  The range of a nonconstant analytic function is always so big that if 2 analytic functions agree on this range, then they must agree everywhere.  (E.g., because the range is uncountable, or because it is open.)
Comment: **Proof**: Let $w\in\mathbb{C}$. If there exists $\delta>0$ such that $\left|f(z)-w\right|\geq \delta$ for all $z\in \mathbb{C}$, then the function $g:\mathbb{C}\to\mathbb{C}$ defined by the rule $g(z)=\frac{1}{f(z)-w}$ is an entire function bounded by $\frac{1}{\delta}$. Liouville's theorem shows that $g$ is constant. Hence $f$ is constant. Therefore, if $f$ is not constant, there does not exist a $\delta$ satisfying the prescribed condition. In other words, $w$ is in the closure of $f(\mathbb{C})$ and $f(\mathbb{C})$ is dense in $\mathbb{C}$.
Comment: @RHP: That is overkill, but to answer your question, it would follow from continuity.  Continuous functions that agree on a dense subset are equal.  To avoid overkill, I recommend using the [identity theorem](http://en.wikipedia.org/wiki/Identity_theorem).  Agreeing on an uncountable set suffices; e.g., see http://math.stackexchange.com/questions/27546/zeroes-of-holomorphic-function
Comment: @RHP: In the previous comment Amitesh has provided a proof that the range of a nonconstant analytic function is dense, which is much easier than Picard's theorem but still enough to finish this problem without using the identity theorem.
Comment: This is a very good answer. I was trying to think of how to avoid open mapping, and your remark about uncountability achieves this. Very clever!
Comment: Dylan, thanks.  In turn, I guess the easiest way to see that the range is uncountable is to use connectedness.
Comment: OK, so I just found [Little Picard](http://en.wikipedia.org/wiki/Picard_theorem), which says the range of $g$ is the plane minus at most one point.  So $g$ is the identity, except possibly at this point. How do we get the last step?
Comment: @RHP: You're welcome.  Actually, it might be easier to show that the range contains an infinite bounded set, and this suffices to apply the identity theorem.
Comment: The Identity Theorem seems quite powerful.  I don't like the proofs that show the closed/openness of the set on which $f$ and $g$ agree, but thats probably because I haven't taken topology yet.

More Properties of Entire Functions


Selecting a MySQL row using a $_POST variable

Question: I am having some issues figuring out how to print the actual values from a row that contains the desired column value. I have two php files, quantity.php and quantity-inquiry.php, where quantity.php has a post submit form that redirects through quantity-inquiry.php to perform the actual sql.
quantity-inquiry opening php:
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'db-connect-99k.php';
$db = new mysqli($host, $user, $pass, $databaseName);

if($db->connect_errno > 0){
  die('Unable to connect to database [' . $db->connect_error . ']');
}

//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$searchName = $_POST['name'];
$res = $db->query("SELECT * FROM inventory WHERE name=$searchName");

$searchName is set appropriately from the $_POST (I can echo it out and it prints the correct input from the quantity form field):

 Product Name or PPI required (both not required)

--------------------------------------------------

<form action="quantity_inquiry.php" method="post">
    Product Name: <input type="text" name="name">

    PPI: <input type="text" name="ppi">

<input type="submit" name="submit" id="submit">
</form>

In other words if I type "car" in the form field of quantity.php, $name in quantity-inquiry.php will echo out "car" as the $name variable. The problem I am having is that using $name as my query:
$searchName = $_POST['name'];
$sql = "SELECT * FROM inventory WHERE name='".$searchName."'";
$res = $db->query($sql);

I can never seem to get the actual values. I have tried tons of stuff, for example:
while($row = $res->fetch_assoc()){
    $rowName = $row['name'];
    $rowPPI = $row['ppi'];
    $rowQuantity = $row['quantity'];
    $rowPrice = $row['price'];
}

To set variables followed by

   $rowName
   $rowPPI
   $rowQuantity
   $rowPrice </td}

Doesn't actually select a the field. For example, if I KNOW that I have 'product1' in my inventory table's 'name' column, and it is set as my '$searchName' it doesn't actually select it from the table and print it out as my $rowName, $rowPPI, $rowQuantity, and $rowPrice.
I have tried a number of other things that all end up in some sort of error or incorrect value being printed out. Is my query wrong or am I setting/using my variables incorrectly?
Comment: At a minimum, `WHERE name=$name` should probably be `WHERE name="$name"` (you need a better quoting solution, but that will get you started).  And then you probably also want to get the data out of your result, so something like `while($obj = $res->fetch_object()){ echo $obj->name; }`.
Comment: @bishop I have edited my code. I have tried it as, for example, $rowName = $row->name... as well, but I always end up getting the error on line 18. Also, I had to concat the variable name onto the end of the string in order to add it to the string like you were saying. Thank you for your input
Answer: Instead of this
$searchName = $_POST['name'];
$res = $db->query("SELECT * FROM inventory WHERE name=$searchName");

you should do this
$searchName = $_POST['name'];
$query = "SELECT * FROM inventory WHERE name = ?";
if($stmt = $mysqli->prepare($query)){
    $stmt->bind_param('s',$searchName);
    $stmt->execute();
    $result = $stmt->get_result();

    while($row = $result->fetch_assoc()){
        $rowName = $row['name'];
        $rowPPI = $row['ppi'];
        $rowQuantity = $row['quantity'];
        $rowPrice = $row['price'];
        ?>

            <?=$rowName?>
            <?=$rowPPI?>
            <?=$rowQuantity?>
            <?=$rowPrice?>

        <?php
    }

    $stmt->free_result();
    $stmt->close();
}else die("Failed to prepare!");

Or you can be super fancy and do this:
$query = "SELECT name, pip, quantity, price FROM inventory WHERE name = ?";

if($stmt = $mysqli->prepare($query)){
    $stmt->bind_param('s', $_POST['name']);
    $stmt->execute();
    $stmt->bind_result($rowName, $rowPPI, $rowQuantity, $rowPrice);

    while($stmt->fetch()){
        ?>

            <?=$rowName?>
            <?=$rowPPI?>
            <?=$rowQuantity?>
            <?=$rowPrice?>

        <?php
    }

    $stmt->free_result();
    $stmt->close();
}else die("Failed to prepare!");

Comment: Better solution than my simple one. Mine works but this is obviously much more in depth.
Comment: @zgc7009 thanks! Just a note: My solution protects your database from SQL Injections... The solution you posted still leaves room for SQL Injection.
Answer: So I have just looked at the computer too long. Simple solution to a dumb mistake. I left
$sql = "SELECT * FROM inventory WHERE name='".$searchName."'";

which is right, when I changed the following
$rowName -> $row['name'];

which was wrong. Then when trying to fix it I changed the $sql to
$sql = "SELECT * FROM inventory WHERE name=$searchName";

which was wrong, while changing my variable set to
$rowName = $row['name'];

So long story short if they were set as
$sql = "SELECT * FROM inventory WHERE name='".$searchName."'";
$rowName = $row['name'];

Note - all $row* variables should be set with = and not ->


Are there efficient ways to provide combustion air to heating appliances?

Question: In a previous question we established that there probably should be a vent between my utility room (which opens into the kitchen and living space in general) and the outdoors (in my case the attic, which is a separate issue)
This seems hopelessly inefficient. Is there a better way to provide combustion air to the furnace and water heater, without having a direct vent between my living space and the outside air?
Comment: This type of setup seems like a code loop hole.  I think there is a code against a furnace/water heater getting combustion air from a living space, this way the installer can say the combustion air is coming from the attic.  I would think unless the utility room is air tight, it's probably not drawing too much air from the vent.
Comment: is there cold air coming in through the vent, or are you worried about warm air going out the vent?
Comment: Previous question pointed to http://inspectapedia.com/Energy/Combustion_Air_Details.htm which seems to justify it - I'm just not happy with the solution.
Comment: Given that the registers didn't even show up in my energy audit, I'm assuming it's mostly warm air going out.
Answer: I am a little concerned that you are overthinking this situation. Naill C gave you some good advise in your last question. There are very few houses not built to be virtually air tight with an air exchange system that do not have enough natural air flow to support open combustion appliances.The simple act of opening a door to enter or exit the house allows large amounts of fresh air in during cold weather when windows are closed.  Unless you have made extreme attempt to block all air infiltration, there is probably pleanty of combustion air passing through your louvered/slat door. I totally understand your desire to minimize heat loss from the rest of the house. Before any external venting will improve the situation, the utility room will have to be somewhat sealed from air flow from the living space of the house. In new construction a vent of a calculated size is brought in from the out of doors, screened and baffled, and strategically located just above the floor by the appliance. The mechanical room is almost air tight, insulated and lined in a fire rated material. Since this space is indoors and only calculated amount of outside air is allowed in, freezing is not normally a concern if water utilities are also in the room. Drawing air from an attic can be risky. Obviously some think it a good idea, however there are drawbacks. If the attic is not well ventilated the air may not be sufficient. I simple vent register in the ceiling to the attic will let as much heat up as it pulls air down. In fact, any open path into the attic can be dangerous. A register, vent pipe etc. can act as an easy path or chimney for fire or natural gas to spread quickly into the attic. If you decide to proceed in isolating and venting your open combustion appliances, pick one of the proven techniques and run it by your local building code officer for local compliance. Better safe than sorry.
Comment: I talked to two HVAC professionals, and they both suggested closing off the vent and letting the appliances use house air.
Answer: Any gas burning appliance (water heater in your case) needs to get fresh air from somewhere, and vent the exhaust somewhere outside (venting into the house is deadly).
Since it is in a utility room with a door that is closed most of the time, you need some kind of vent to get fresh air.  You can pull that fresh air from either the (1) insulated living areas of the house, (2) uninsulated/unoccupied areas of the house (attic), or (3) from the outside.
From an efficiency standpoint, (1) seems like a bad idea, because it takes heated/cooled living air to vent outside.  It also seems potentially unsafe, as it allows an easy path for exhaust to get back in to occupied areas if the exhaust vent has issues.  (Not sure what the building codes say.)
Based on your other post, you seem to have (2), which seems to be a pretty good approach.  I'm no expert, but the biggest pitfall I see with (2) is that if your attic is too tightly sealed (stuffy), the water heater could potentially not get enough air to breathe.  In that case, (3) would be the best approach.  But (3) allows uninsulated air into the house, which compromises heating/cooling efficiency.
Basically, I don't think your current setup is particularly inefficient.  If you want to make your house more energy efficient, there are probably other things around the house that need more attention (windows, ducts, insulating hot water pipes, etc).
The only potential efficiency problem I can see with your current setup is heated/cooled living air leaking around/under the door into the utility room, and getting "wasted" by the water heater's combustion.  You can fix this by making the utility room door seal better.  Put something under the door to close off the gap.  Weatherstripping in the door frame.  Basically, treat it as if it were an exterior door.  (Caution: If the air provided by the vent is not sufficient on its own, you may have issues.)
Oh, and since you have at least one gas-burning appliance, make sure you have adequate Carbon Monoxide detectors. They could save your life!  You should have one inside the utility room as a first line of defense, and then one in the occupied part of that floor, plus at least one more on each of the other occupied floors of the house (particularly near your bedroom).  And remember that they go bad and need to be replaced every few years!
Comment: I am as much concerned about heating the attic (ice dams, icicles) as using conditioned air (which of course points to (3))  Other concerns: utility room door is slated; I suppose I could replace it.  Room also has my incoming water pipe, so I wouldn't want the room to get too cold.
Comment: I don't see it heating the attic much, because the air will be flowing IN from the attic, not OUT. I also wouldn't expect the utility room to get too cold, because there is a burner in there making heat.
Comment: The pipe is open on top.  Warm air rises, and we expect the house to be warmer than the attic.  So, especially when furnace isn't running (drawing air), house air will be rising into the attic.
Comment: When the burner for the water heater is running, the warm air of the burner will be rising out out the exhaust flue.  So, air will be getting pulled into the room from any open gaps (e.g. your attic vent).
Comment: @Justin, you're correct that warm air does rise. That's partly why the vent is at the bottom of the wall in your utility room. The coldest air in that room is the only air that can rise to the attic. But since the amount of heat lost will depend on the difference between the temperature in both places, it's better to vent from the attic than the much more extreme (either hot or cold) outdoors.
Comment: BJQ, please read my answer above. Although venting to an attic was used occasionally years ago, it is now considered unsafe and a fire /gas hazard. This feature will always be written up as a " Item of Major Concern" on any home inspection I conduct. Some insurance companies will insist they be removed to extend fire insurance. My last words are "Better Safe than Sorry"
Comment: @shirlock, I'm not surprised it's considered unsafe. I should have been more clear that I was only addressing @Justin's concern about heat loss via the vent NOT that the vent was a good idea. I'm strictly a DIYer-certainly not an inspector or contractor. Thanks for clearing it up though.
Answer: There's a style of ducting where the exhaust and intake are run through the same piece, one inside the other.  This allows some heat exchange, as the intake air is warmed by the exhaust.  The benefit is likely based on the length of the run.
Concentric vent kit:

Picture source: prowaterheatersupply.com
Comment: This type of exhaust/vent is only available on air tight units such as a Rinai closed combustion system. It is referred to as a direct vent unit.
Answer: You need to have a fresh air vent near the appliance otherwise you will be sucking in cold air in another room like your front door. To mitigate any heat loss, you can  use the 5 gallon bucket trick. The outside air vent is connected to a 4" flexible insulated duct. The bucket sits next to the water heater with the duct in the bucket. So cold fresh air for combustion fills the bucket and is available to the appliance, but pretty much stays in the bucket and doesn't fill the whole room up with cold air.
Comment: That bucket isn't going to do a thing. Air is going to flow every which direction, as long as there's a high exhaust and a low air intake, until the space equalizes with the outside temperature.


different time for view and table

Question: Can somebody tell me why there are difference between this:
1)
view2 -> view1 -> remoute_server_table
select * from view2 - needs 8 min
2)
view2 -> table1 -> remoute_server_table
select * from view2 - needs 10 sec
Everything is the same on both variants:

view2 has 5 joins
remoute_server_table is the same

Difference is in using table1 or view1:
view1:
CREATE VIEW view1
AS
SELECT ...
FROM remoute_server_table as o
WHERE CAST(o.Период as Date) >= DATEADD(d,-1, CAST(getdate() as Date))

table1:
TRUNCATE TABLE table1;
GO

INSERT table1 (...)
SELECT ...
FROME remoute_server_table as loc
WHERE CAST(loc.Период as Date) >= DATEADD(d,-1, CAST(getdate() as Date))
GO

SO, table1 ~ view1 by select clause and data.
Edit1: Execution plans are different. There are no indexes for table1 and for view1
Comment: Did you check the execution plan?
Comment: Yes, I did, but could not manage to understand where is the problem. Execution plans are diffrent.
Answer: How do you fill table1, do you fill it before doing a select on it?
When you use the solution with view1 it retrieves the data from the remote server at execution time, this most likely causes the delay.
If you fill table1 before executing the select statement then you select the data from the local server without needing to create a connection to the remote server.
Comment: Yes. I fill table1 before selecting from view2.
So, variant 1 will always suffer from connection to remoute serve?
Comment: I thought that view1 will be executed and will be stored in RAM or in temp_table... Execution plan shows that RemouteQuery cost 24%
Comment: Yes. You could create a SQL Agent Job that fills the table every hour or what suits your requirements, this is how I usually do it. However, if you do not want your table to be empty for 8 minutes you could create an extra "staging area" table where you insert data into before inserting them into the actual table.
Comment: Yes. I thought about such plan.
The issue to use the variant with view1 was to make my SSAS cube's partition be in ROLAP mode and take data from view2 - so it will be uptodate to remoute_server_table.
So, it seems to be only one variant to do this - use sql-jod =(

different time for view and table


how one can calculate a weight average price after a group by?

Question: I have the datatable below :

qty     price     date
5         2        1/25
6         1        1/25
8         3        4/25
1         2        4/25

and I want :

qty     price    date
11       1.45     1/25
9        2.88     4/25

I have already group the datatable by date with

 var groups = ToCalc.AsEnumerable().GroupBy(r => r.Field("trade_date"));

and the qty sum is like :

            foreach (var group in groups)
            {
                qty = Convert.ToDouble( group.Sum(r => r.Field("EXEC_QTY")));
            }

but I don't know how to calculate the weighted average price.
Any idea ?
Comment: possible duplicate of [Weighted Average with LINQ](http://stackoverflow.com/questions/2714639/weighted-average-with-linq)
Answer: weightedAverage = group.Sum(r => r.Field("EXEC_QTY") * r.Field("price"))
     / group.Sum(r => r.Field("EXEC_QTY"));

Add Convert.ToDouble if you really need it.
Since you comment that qty is a double and price is a decimal:
weightedAverage = group.Sum(r => (decimal)r.Field("EXEC_QTY") * r.Field("price"))
     / group.Sum(r => (decimal)r.Field("EXEC_QTY"));

(Wouldn't it make more sense for price to be decimal and quantity to be a double?  Or for both to be decimal?)
Comment: thanks, i tried :             price =Convert.ToDouble( group.Sum(r => r.Field("EXEC_QTY") * r.Field("EXEC_PRICE"))
                    /group.Sum(r => r.Field("EXEC_QTY")));  But EXEC_QTY is a decimal and EXEC_Price is a double , how to handle that ?
Answer:     class Data
    {
        public int Qty { get; set; }
        public double Price { get; set; }
        public string Date { get; set; }
    }
    static void Main(string[] args)
    {
        var data = new Data[] {
            new Data { Qty = 5, Price = 2, Date = "1/25"  },
            new Data { Qty = 6, Price = 1, Date = "1/25"  },
            new Data { Qty = 8, Price = 3, Date = "4/25"  },
            new Data { Qty = 1, Price = 2, Date = "4/25"  },
        };

        var weighted = data.GroupBy(x => x.Date)
                           .Select(group => new Data {
                               Date = group.Key,
                               Qty = group.Sum(i => i.Qty),
                               Price = group.Sum(i => i.Price * i.Qty) / group.Sum(i => i.Qty)
                       });
    }

Answer: I would do something like this:
var results = ToCalc.AsEnumerable()
    .GroupBy(r => r.Field("trade_date"))
    .Select(grp =>
            {
                var quantity = grp.Sum(r => r.Field("EXEC_QTY"));
                var avg = grp.Sum(r => r.Field("EXEC_QTY") * r.Field("price")) / quantity;
                return new {
                               TradeDate = grp.Key,
                               Quantity = quantity,
                               WeightedAverage = avg
                           };
            });

results would then be an enumerable of anonymous objects containing the information you want, it much more accessible structure.
Answer: You could perform all grouping inside one method by using this Enumerable.GroupByoverload:
var groups = ToCalc.AsEnumerable()
    .GroupBy(r => r.date, (k, g) => new
    {
        date = k,
        qty = g.Sum(i => i.qty),
        price = g.Sum(i => i.qty * i.price) / g.Sum(i => i.qty)
    });

This will give you something like:
{ date = "1/25", qty = 11, price = 1.4545454545454546 }
{ date = "4/25", qty = 9, price = 2.8888888888888888 }


How to get reference to a pop up window and load a javascript file in it?

Question: In SharePoint 2010, there is a button to open a popup window (its for alerts). However it doesn't use the conventional way to open a popup window like window.open, it calls a SharePoint function, which results in a pop up window opening. Now is there a way I can load a JavaScript file (.js file using a script tag basically) in it? I figure I would need to get a reference to that window somehow, and then append a script tag in it or something.
Note: I can't modify the actual file popup window page. I just want to dynamically insert the JavaScript in it programmatically.
Comment: can you post the `SharePoint` function?
Answer: It depends on how the SharePoint function opens the window.  Unless it opens it as an assignment to a variable you can access for reference, then there's no way to access it. Chances are you are going to need to modify the SharePoint function to do this and return that reference or else make it a globally scoped variable you can then reference. Also, the target window will have to be the same domain as the parent page.


Blazor Server error aspnetcore-browser-refresh.js:234 WebSocket connection to 'wss://localhost:56871/' failed

Question: Running a Blazor Server app is showing a partially rendered page with a browser console error of:
<code>aspnetcore-browser-refresh.js:234 WebSocket connection to 'wss://localhost:56871/' failed
</code>
It would appear that no recent changes have been made to the code. There doesn't seem to be any code issues, how can I go about isolating this issue?
Answer: EDIT:
This issue has now been fixed in v17.1.5. You would want to update to this version.
Reference to release notes: https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes#17.1.5
Original Answer to rollback install:
It appears that this is a bug in Visual Studio v17.1.1. If I revert back to v17.0 then the application launches successfully.
FIX:

Uninstall Visual Studio v17.1.1 (via VS Installer)
Install specific version v17.0.7 package from https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-history

Reference to the bug (a report indicates it is also present in 17.1.2):
https://developercommunity2.visualstudio.com/t/WebSocket-connection-to-wss:-fail/1670519?q=ERR_CONNECTION_RESET&ftype=problem&space=8&stateGroup=active&sort=newest
Answer: installing preview version 17.2 also solves this problem
Comment: Upgrading to Update version: 17.2.0 Preview 2.1 resolved the error for me. thx.


Angularjs, select option after getting object from server

Question: The short version of what I'm doing:
I'm getting some JSON from the server to try to recreate the state of my form. Everything loads fine except for one select box that uses a function to get its display. How can I accomplish this?
The longer version:
I have a select box that looks like this:
<select name="size" ng-model="form.options.size" ng-options="form.displaySize(size) for size in form.sizes">
    <option disabled value="">-- choose dimensions --</option>
</select>

This works fine with the user selecting the option, but I'm trying to figure out how to get the select box to select the right size when form.options.size is set programmatically (after receiving some json from an api call).
My "size" object looks like this: {width: (some width), length: (some length)}.
My "displaySize" function just returns a string width + "x" + length.
I understand I could manually loop through the options and select the right one, but I'm really trying to avoid that as much as possible. What are my options?
Edit:
Fiddle showing exactly what I'm doing here.
Answer: While assigning the value to the select model, the value assigned to the ng-model should have the reference in the json list given to the ng-options.
$scope.form.options.size = $scope.form.sizes[index];

http://jsfiddle.net/ptno0ew7/1/
OR
use track by option for the ng-options directive, updated the fiddle http://jsfiddle.net/fo1h1n53/1
Comment: Unfortunately, I won't know the index when I get the info back from the server. I've added a fiddle to my question showing more or less the exact circumstances.
Comment: use track by option for the ng-options directive, updated the fiddle http://jsfiddle.net/fo1h1n53/1/
Comment: Yes, track by did the trick! I used track by form.displaySize(size) and it worked!


How to retrieve the Id of the Last inserted data in to a "New Page" in php?

Question: I created a sign up page in PHP.
When the submit button is clicked, it should show the registration No. on a NEW PAGE,
(like "Your registration is successful and your registration No. is____").
I Know how to show the last inserted ID on the same page.
but how to display the same on a NEW PAGE using mysql_insert_id()?
Below is the SIGN UP PAGE.
include 'connect1.php';
if (isset($_POST['submit']))
{
    $name = $_POST['name'];
    $qual = $_POST['qual'];
    $dob = $_POST['dob'];
    $address = $_POST['address'];
    $number = $_POST['number'];
    $email = $_POST['email'];

    $sql="INSERT INTO registeredparticipants (Name, DateOfBirth, Address, PhoneNumber, EmailID, Qualification)" .
            "VALUES ( '$name','$dob', '$address', '$number', '$email', '$qual' )";
    $res=mysqli_query($con, $sql);
    if($res)
    {
        header('location: welcome.php');
    }
    else
    {
        die ("Query Failed !!" . mysqli_error($con));
    }
}

When submit button is clicked, "welcome" page will be loaded.
and I would like to display the ID of the last inserted data in "welcome" page.
ID of the above table is "Reg_no." How to display it on "welcome" page?
Comment: Also show some code so we can help you better way.. what you tried till now ?
Comment: @Thaslam many people have replied try that.
Comment: i tried everything... Nothing working.. Could you please provide the code for the next page? How to use session  on the above page?
Answer: You can put into the url you are using to redirect like header("location:new_page.php?id=".$last_insert_id) and get from $_GET['id'] on new_page.php
Hope it helps
Answer: You can do it by either get | post | COOKIE | SESSION

header("location:new_page.php?id=".$last_inserted_id) and get from $_GET['id'] on new_page.php
In html form hidden format " and get it from $_POST['id'] on new_page.php
COOKIE
SESSION
Answer: There are two ways for this answer using $_GET and $_SESSION, get will show id in url if you dont want that use session for that.
$sql = "INSERT INTO ......";

if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    $_SESSION['registration_no']=$last_id;
    header("Location:newpage.php");
} else {
    echo "Error: " . $sql . "
" . mysqli_error($conn);
}

in newpage.php
<?php session_start(); ?>

Your registration is successful and ur registration No. is <?php echo $_SESSION['registration_no']; ?>

i hope it will help
Answer: you can use session to store such value and retrieve it on any page you want like-
session_start();

//your code....
$_SESSION['reg_no'] = $last_insert_id;

than on any page you can retrieve it -
session_start();

$reg_no = $_SESSION['reg_no'];
echo "Your registration is successful and ur registration No. is ".$reg_no;


Regex for matching multilingual numbers not detecting Chinese numbers

Question: I have a method which detects whether a String is a number:
public static boolean isNumber(String num)
{
    return num.matches("(\\p{N})+");
}

The above method is successfully matching English, Hindi, Arabic numbers but fails to match Chinese numbers:
三十萬零二百五十 etc.
Is it possible to create a regex which can match a number from any language(or major languages)?
edit: the number won't be a decimal, it will be used to validate a phone number.
Comment: If that is only a Chinese issue, you can use the approach I suggested. Also, here is [a nice resource on Chinese numbers](http://www.mandarintools.com/numbers.html). Acc. to that page, the Chinese numbers can be matched with `[\\p{N}零一二三四五六七八九十百千萬億万亿壹貳叄肆伍陸柒捌玖拾佰仟贰叁陆]`.
Comment: I don't know anything on chinese characters, but are you sure these characters `三十萬零二百五十` are numbers and not literals like `one two three ...`
Comment: These look like belonging to `\p{Lo}` category.
Comment: @stribizhev it's working, but the definition of \p{Lo} from http://www.regular-expressions.info/unicode.html seems to be saying that it might match characters other than numbers?
Comment: Is there any (easily automatable) way to tell if this characters are used as digits? Can they be used as non-numeric part of words/text?
Comment: No idea, the only solution that I can think of is just add them all into the character class. Like `"(?U)[\\p{N}一二三四五六七八九十百千万萬億亿兆零]+"`.
Comment: @stribizhev but this solution would only be able to help support Chinese, how will i be able to do this for all the unsupported languages?
do you know of any character which falls under \\p{Lo} but isn't a number?
Comment: No, I am afraid that is something I cannot be sure of.
Comment: @stribizhev ok, thank you very much for your support :)
Comment: @Toto i also don't know Chinese :), but i referred dozens of links, some of them being:

http://www.mandarintools.com/numbers.html
https://en.wikibooks.org/wiki/Chinese_%28Mandarin%29/Numbers
Comment: I've just tried google traduction from english to chinese, for `1` it gives `1`, for `one` it gives `一` same for `3` => `3` and `three` => `三`
Comment: @Toto yes i have already tried that too, google can't always be right ;)
Comment: Sure :) ; waiting for a chinese people that can answer.
Comment: @SarthakMittal can you give more examples? I have written solution below and I want to text it
Comment: Since when Chinese use Chinese characters for there phone numbers instead of typing arabic numbers? Did you ever write **your** phone number as a word like "onemilliontwohundredthirtyfourthousandfivehundredsixtyseven"? Doesn't make sense at all. Why should Chinese do so?
Comment: `三十萬零二百五十` is normally written as `三十萬零二百五`. By the way: `二百五` (250) means "idiot" in Chinese language.
Answer: If you try with javascript it will work with This regex Pattern

const stringNumber = "三十萬零二百五十12";
const regex = /\d+/g;

const numbers = stringNumber.match(regex);

console.log(numbers);
Comment: This is returning ['12'] for me and not including the Chinese numbers.
Answer: as some have already pointed out in the comments, these are the words used for numbers, i.e. "one", "two", "three" etc.
China introduced the indo-arabic numbers in the 19th century, so \p{N} should also match Chinese numbers. If you also want the literals, you should include them, as stribizhev suggested.


How to force CipherSpec to specific value connecting to IBM MQ from RHEL using .net core. Get rid of CompCode: 2 Reason: 2059

Question: We are trying to connect to IBM MQ Server v 9.1.0.x. from RHEL 8.3 using .net core 3.1 and IBMMQDotnetClient 126.96.36.199 standard library from nuget.
We are stuck on getting CompCode: 2 Reason: 2059 error.
We know what is the reason: during ssl negotiation cipher spec is set to TLS_RSA_WITH_AES_128_CBC_SHA256 but the channel has it set to TLS_RSA_WITH_AES_256_CBC_SHA256.
ERR*.TRC

CommentInsert2(TLS_RSA_WITH_AES_256_CBC_SHA256)
CommentInsert3(TLS_RSA_WITH_AES_128_CBC_SHA256)
AMQ9631E: The CipherSpec negotiated during the SSL handshake does not match the
required CipherSpec for channel

We had the same issue on Windows but doing
Disable-TlsCipherSuite -Name TLS_RSA_WITH_AES_128_CBC_SHA256 has resolved the issue.
What we've done already:

We are specifying SSL_CIPHER_SPEC_PROPERTY as TLS_RSA_WITH_AES_256_CBC_SHA256.

Unfortunately it is ignored, as we are using managed client (MQC.TRANSPORT_MQSERIES_MANAGED) it's the only valid option for managed library. All security calls are transferred to internal security providers (Schanel/SslStreams on Windows and OpenSsl on Linux).
We know that we should alter cipher policy on Linux, do you have any idea how to:

Disable TLS_RSA_WITH_AES_128_CBC_SHA256 on RHEL?

UPDATE
Disable-TlsCipherSuite -Name TLS_RSA_WITH_AES_128_CBC_SHA256 is a Powershell cmd.
UPDATE 1
On Linux (RHEL8.3) During handshake my frame looks like:
    Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02c)
    Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030)
    Cipher Suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (0x009f)
    Cipher Suite: TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca9)
    Cipher Suite: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca8)
    Cipher Suite: TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xccaa)
    Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02b)
    Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f)
    Cipher Suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (0x009e)
    Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 (0xc024)
    Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (0xc028)
    Cipher Suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 (0x006b)
    Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (0xc023)
    Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (0xc027)
    Cipher Suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 (0x0067)
    Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (0xc00a)
    Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014)
    Cipher Suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA (0x0039)
    Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (0xc009)
    Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013)
    Cipher Suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA (0x0033)
    Cipher Suite: TLS_RSA_WITH_AES_256_GCM_SHA384 (0x009d)
    Cipher Suite: TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c)
    **Cipher Suite: TLS_RSA_WITH_AES_256_CBC_SHA256 (0x003d)**
    **Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA256 (0x003c)**
    Cipher Suite: TLS_RSA_WITH_AES_256_CBC_SHA (0x0035)
    Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA (0x002f)
    Cipher Suite: TLS_EMPTY_RENEGOTIATION_INFO_SCSV (0x00ff)

UPDATE 2
We managed to force cipher used during negotiation and then during MakeSecuredConnection.  Unfortunately it's only doable on .NET5.0 and hack in MakeSecureConnection is needed.
I tried the same approach using .net core 3.1 but failed probably because of use of AuthenticateAsClientAsync.
Here is .NET5.0 IBM MQ Client 188.8.131.52 hack

Decompile the code of IBMMQClient (amqmdnetstd.dll)
Mark .csproj as .NET5.0 <TargetFramework>net5.0</TargetFramework>
Edit MakeSecureConnection method in class MQEncryptedSocket as follows

only .NET5.0
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    stream.AuthenticateAsClient("*", x509Certificate2Collection, sslProtocol, sslCertRevocationCheck);
                }
                else
                {
                    //stream.AuthenticateAsClient("*", x509Certificate2Collection, sslProtocol, sslCertRevocationCheck);
                    var sslClientOptions = new SslClientAuthenticationOptions()
                    {
                        CertificateRevocationCheckMode = sslCertRevocationCheck ? X509RevocationMode.Offline   : X509RevocationMode.NoCheck,
                        ClientCertificates = x509Certificate2Collection,
                        EnabledSslProtocols = sslProtocol,
                        TargetHost = "*",
                        RemoteCertificateValidationCallback =ClientValidatingServerCertificate,
                        LocalCertificateSelectionCallback = FixClientCertificate,
                        CipherSuitesPolicy = new CipherSuitesPolicy(new List<TlsCipherSuite>() { Enum.Parse<TlsCipherSuite>(cipherSpec) })
                    };
                    TrText(method, $"Setting Cipher for AuthenticateAsClient {string.Join(':',sslClientOptions.CipherSuitesPolicy.AllowedCipherSuites)}");
                    stream.AuthenticateAsClient(sslClientOptions);
                }

for .net core 3.1 you have to call
    stream.AuthenticateAsClientAsync(sslClientOptions);

Since there is no method AuthenticateAsClient overload accepting SslClientAuthenticationOptions parameter.
.net standard 2.0 and 2.1 don't have CipherSuitesPolicy  parameter in class SslClientAuthenticationOptions that's why I had to move the library from .net standard 2.0 to .net5.0 (with success) and .net core 3.1 without.
Do you have any clue how is it possible to make it work on .net core 3.1?
Comment: https://github.com/dotnet/runtime/issues/23818 gives some details on why the IBM MQ managed .NET client is not able to harrow down the the specific cipher like it does in the other clients, it only uses the cipher to figure out what version to use (TLS1.2 for example), the negotiation is then against all the client allows not a single cipher unless you modify the policy on windows. If the windows server was on 9.2 they could eliminate the AES_128 cipher from the last that is presented by the server and this would force he negotiation to use a different value.
Comment: Yes you are correct, the client sends the full list and the server will pick backed on which one is first in its own list (I had thought this list was also sent back to the client).  on MQ v9.1 the server side order is with TLS1.0 disabled (by default) is `TLS_RSA_WITH_AES_128_CBC_SHA256 TLS_RSA_WITH_AES_256_CBC_SHA256 TLS_RSA_WITH_AES_128_GCM_SHA256 TLS_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`.
Comment: Based on that output and your client side list you are receiving the expected negotiation.  At MQ v9.2, this list by default was re-ordered from what I recall and the AES_128 is no longer first on the list, also at 9.2 the admin can change the order and allowed ciphers.
Comment: Correct, at 9.1 server the result you see is expected, at 9.2 you would likely see a different result.  My only other suggestion is to it may be possible to recompile the openssl that the MQ libraries on Linux is using so that the `TLS_RSA_WITH_AES_128_CBC_SHA256` is not offered.  Or as I mentioned put a MQIPT instance between your client and the MQ server to control what ciphers are allowed from your client to MQIPT and from MQIPT to the MQ server.
Comment: The client specifies the TLS version and TLS version has to be compatible with the encryption mode (https://en.wikipedia.org/wiki/Transport_Layer_Security).  So if c# does not specify the TLS version the default version is used in windows (which may not be correct).  So then you need to add in c# client the TLS version : System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Comment: As part of TLS the server sends a certificate block with the names of the certificates the server accepts.  Then client checks which certificate are in the certificate stores to find a matching certificate.  So the certificate has to be in both the client and server.  In Windows the certificate has to be in both the machine certificate store and the user certificate store.
Comment: Thank you for the answer. We are using tls12, we are using Linux.
Comment: You can use a sniffer like wireshark or fiddler and look at the TLS messages from server to client and find the certificate block with names of the certificate.  Something is wrong with the certificates loaded on server and/or client.  There must be a matching certificate on server and client that meets the TLS 1.2 requirements.
Comment: May be certificate is expired.  Here is an interesting article : https://learn.microsoft.com/en-us/security/sdl/cryptographic-recommendations
Comment: Certificate is correct. We can run integration tests on Windows with pass and they fail on Linux. As I wrote above, we were facing the same behavior on Windows, but we managed to disable the cipher
Comment: Is the certificate bad?  The encryption mode is determine from the certificate.  If the certificate has the wrong mode for the key you are using then you will fail.  Disabling the cipher mode is just a work-around for a bad certificate.  Using a sniffer you should verify the TLS version is correct and you are not trying TLS 1.0/1.1.
Comment: TLSv1.2 Record Layer: Handshake Protocol: Client Hello Handshake Type Client Hello (1) Version: TLS 1.2 (0x0303)
Comment: Hi Tom, I don't know how to fix it on Linux, but could you edit and provide more context around how you use `Disable-TlsCipherSuite -Name TLS_RSA_WITH_AES_128_CBC_SHA256` on windows to obtain the result, this could help me on some windows setups.
Comment: JoshMc sorry but I don't understand. What do you mean by provide more context? I would love to do it but I have no idea what should I write about. This powershell command disables cipher suite from the list that I found in group policy.
Comment: Did it remove it Server wide or can it be limited to a specific user or process?  Knowing that it is a powershell command provides the context I was looking for.
Comment: Did you see in sniffer the names of the certificate?  One of the TLS messages contains the list of certificates.
Comment: Another option would be to setup a local MQIPT instance as a proxy, this instance could advertise to your client ONLY the cipher you want, and then be configured to re-encrypt with the same when sending on to the MQ server.
Comment: Is the list you added from the client or server?  Can you add the other list of ciphers?
Comment: The list is from the client side. Server side has Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA256 (0x003c) but I understand that this is for creating secure communication between client and QM.   When we connect to QM -> CHANNEL which has different cipher set.
Comment: I was interested in the full list and order that is presented from the server.
Comment: There was just one cipher during server hello Handshake Protocol: Server Hello
    Handshake Type: Server Hello (2)
    Length: 91
    Version: TLS 1.2 (0x0303)
    Random: Y…
    Session ID Length: 32
    Session ID: X…
    Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA256 (0x003c)
    Compression Method: null (0)
    Extensions Length: 19
    Extension: ec_point_formats (len=2)
    Extension: encrypt_then_mac (len=0)
    Extension: extended_master_secret (len=0)
    Extension: renegotiation_info (len=1)  this is how Server Hello frame works as RFC5246 it has only selected cipher
Comment: Do you mean MQ Server 9.2 by saying MQ v9.2 or client? Server is 22.214.171.124, client is 184.108.40.206
Comment: JoshMc can you tell me where the ordered list of ciphers on server side is located?
Comment: For MQ 9.1, you can find the list here: https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.1.0/com.ibm.mq.dev.doc/q113220_.htm
Comment: Only at 9.2 did IBM add the ability to influence the server side cipher order and list. If you want to see what order is returned then try http://testssl.sh, it is a simple shell script that uses openssl to run tests against any ip and port, one result from the script is the server's cipher list and preference order. I noted the IBM 9.2 knowledge center page [CipherSpec order in TLS handshake](https://www.ibm.com/support/knowledgecenter/SSFKSJ_9.2.0/com.ibm.mq.sec.doc/q134760_.htm) also lists the pre-9.2 order.  Please @ tag if you want me to get notified of your reply.
Answer: I had the same issue when connecting with .NET MQ client to a channel using TLS_RSA_WITH_AES_256_CBC_SHA256 cipher.
In the MQ server logs I saw that my client tried to connect with TLS_RSA_WITH_AES_256_GCM_SHA384 even if I was setting the cipher spec to TLS_RSA_WITH_AES_256_CBC_SHA256 in my code.
cf.SetStringProperty(XMSC.WMQ_SSL_CIPHER_SPEC, "TLS_RSA_WITH_AES_256_CBC_SHA256");

To solve it I had to set the system default cipher in the file /etc/ssl/openssl.cnf to AES256-SHA256.
[system_default_sect]
…
CipherString = AES256-SHA256

My application is built on .NET 6.


Changing to NVIDIA driver causes Ubuntu 21.04 to freeze on startup

Question: I am very new to linux, so bear with me here. I recently installed Ubuntu 21.04 onto my Dell G5 5090 computer. The installation runs perfectly fine. However, after trying to switch to the NVIDIA proprietary drivers (specifically version 460) and rebooting, the installation gets frozen on the Dell logo. I have tried going into tty, using crtl+alt+f1-12, and using the nomodeset fix, but none of them work. PC specs: GPU: GeForce 1660ti, CPU: Intel I5-9400 (6 cores) @4.1GHz, and 8GB ram. My kernel is 5.11.0-18-generic.
Comment: Another piece of information: I tried to install Ubuntu 20.04.2.0 LTS beforehand, but it had the same exact problem without even installing the nvidia drivers.
Answer: it's fixed, I realized all I had to do was switch to the HDMI port instead of using DP.


Is there a way to recover Pokeballs that miss?

Question: Can you recover Pokeballs that miss when trying to catch Pokemon?
Comment: The lost pokeballs usually roll all the way to one of the nearest pokestops. ;)
Comment: NOTE: Lots of downvoted answers on my post...please site sources that may be able to back up your answers. A lot of people are saying that this is possible but not providing any proof. Thanks.
Comment: @ChaseC [sources](http://au.ign.com/wikis/pokemon-go/How_to_Throw_a_Poke_Ball) don't prove anything. I just wish people would actually try something that they heard about before spreading it.
Comment: Also see this related question: [Why can't you just pick up your balls?](http://gaming.stackexchange.com/questions/281360/why-cant-you-just-pick-up-your-balls), which is looking for a canonic explanation for this behavior.
Answer: No, every throw regardless of if it misses, hits and breaks out, or hits and captures will use 1 of which ever Pokeball you're using.
Answer: Every time you throw a Pokeball, it is subtracted from your inventory and you will not get it back, no matter what.
Tapping a Pokeball does not recover it. Instead, it just despawns it and allows the next throw to happen quicker.
Pokeballs are common enough that losing a few won't harm you at all, fortunately.
Answer: I have not seen any mention of any way to do so. I presume they expect you to continually restock PokéBalls by visiting PokéStops and spinning the picture - I've collected a lot of Pokémon (thus have thrown a lot of PokéBalls) and have never gone below 100 PokéBalls available (you often get 3 when interacting with a PokéStop).
Comment: It depends on how active you are + how many PokeStops are in your area. For example, there is exactly one PokeStop between my work and my home, so I get a max of 6 PokeBalls a day if I stop there before and after work. I'm just a casual player so I don't care that much, but if I really wanted to I could go downtown and collect a lot more every day as well.
Answer: It works for me on great balls but I haven't tried it on anything else. I also had the ar off.  If you recover it, the ball glows and disappears from the battle field.  I believe there was also an animation at the bottom of the screen but I only caught it out of the corner of my eye so I didn't see what it was.  I know it worked because I encountered a Pokemon having only 2 great ball left.  My first throw missed; I taped it as it was rolling and it glowed and vanished.  I caught the Pokemon with the second great ball.  When I finished I checked my bag again and low and behold I still had 1 great ball.  So I know for sure that it works with great balls.
Comment: Nope, this still doesn't work


Java HttpURLConnection command works perfectly through command line but not through web UI

Question: I have a java file to execute an HttpURLConnection command, which when I execute through command line, works perfectly to fetch data from the URL.
I have mapped a URL to this activity in my web application and when I invoke this activity through the web UI this code works fine except the HttpURLConnection command now returns empty results.
public static String getData()
 {
    String str = "";
    try{
    TrustManager[] trustAllCerts = new TrustManager[]
    {
       new X509TrustManager()
        {
          public java.security.cert.X509Certificate[] getAcceptedIssuers()
          {
            return null;
          }
          public void checkClientTrusted(X509Certificate[] certs, String authType) {  }
          public void checkServerTrusted(X509Certificate[] certs, String authType) {  }
        }
     };
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
         HostnameVerifier allHostsValid = new HostnameVerifier()
         {
            public boolean verify(String hostname, SSLSession session)
             {
                           return true;
             }
         };
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    URL url = new URL("My URL");
    URLConnection con = url.openConnection();
    Reader reader = new InputStreamReader(con.getInputStream());
    while (true)
    {
       int ch = reader.read();
       if (ch==-1) {
           break;
       }
       str += (char)ch;
    }   }catch(Exception e){}
    return str;

I can't understand what is causing this behavior please help me fix this.
Answer: This reason for this is web browsers have a security in place to protected websites from unwanted queries. This is the CORS policy.
If a domain does not want incoming requests from outside world this policy provides this security. It is upto the domain to turn this policy off. So as a client, you really can't do anything.


How do users benefit from having a browsing history?

Question: I'm putting together a music based website where users can explore artists and albums. One pattern I've noticed amongst content heavy sites like IMDB and YouTube is that they go the extra mile as far as providing browsing history for registered users.
Are there studies, articles, or discussions that key-in on why having a browser history available to a user is/isn't beneficial? As a webmaster I can imagine that it would result in a higher click-through rate but this question in particular is geared towards the user than anything.
Comment: just a hunch, but I'm pretty sure the history serves the retailer more than the user "Oh yea, I forgot to buy that yesterday. I guess I'll buy it today!"
Comment: with music especially I'm going to bands more than once. Its not just handy to have a history, I *need* a history
Comment: That's an interesting speculation. Thanks for sharing. I wonder how it effects non-retail sites.
Comment: @colmcq What's the reason for why you would visit a band multiple times if you don't mind me asking?
Comment: @CarlEdwards listen to a song you like again, show a friend, explore the next song/album you didn't get to (if they have a 10 album discography I'm not looking at all in one sitting), open it on a different device (if I find it at work I may want to see it again at home when I am able to look, or if I find it on my phone and it's too small I may want to see it on my desktop), check if they came out with anything new a month after I last visited, forgot what I read previously
Comment: If it  is not considered obtrusive or privacy sensitive content, it can't harm the user experience. So if you know how it will be received you can always experiment with it to see if people find it useful.
Answer: Of course there are many reasons for this. First and most important one: to act as reminders of your previous activity. Let's say you watch a video on YouTube, then you continue watching or close your session or whatever. A couple days later, you remember that video WHICH YOU DIDN'T BOOKMARK and... browsing history to the rescue.
Basically, browsing history acts as a set of dynamically created bookmarks you can relate at a later time. This is specially useful on apps where you don't have a bookmarks tab  as you have in your browser, so you really need a way to provide this feature to your users.
As for more reasoning and articles, you might be interested in the following:

UI design pattern tips: recently viewed
Breaking Web Design Conventions = Breaking the User Experience (examples and explanation on how to work with browsing history in different ways)
HTML5 History API (W3's guide and recommendations)
Why Johnny Can't Browse in Peace: On the Uniqueness of Web
Browsing History Patterns (considerations to keep in mind)
Answer: This is beneficial in two reasons:
Security/ Backup:
If you have logged on an account on a website, let's say you happen to visit a particular webpage through your account. Now you logout of the particular website. Tomorrow, a coworker will decide to diabolically peek into your browser history. He sees something on this very specific website. He clicks on it, but BAM! You need to be logged in to access that content!
Since the content is only available to access through your account, the browser history proves useless and might as well save you tomorrow in the case you clear your browser history or want to access that item through a different computer.
Second Thought:
You visit the item, wish to purchase it but change your mind. Now the website gets hold of what you wanted to purchase and recommends you similar items or the same item, saying you left it "incomplete". It leverages you into a second thought to purchase that product.
Comment: @SwapnilBorkar I agree with LS97, the first point seems like more of a case for a login than for browsing history. If the website didn't have a built in browsing history the same situation you described could occur.
Comment: I agree on the second point, but if anything, any type of history decreases "security" because it stores all of your past actions.
Comment: Only if you're logged in. If you aren't it'll simply ask you to login first. Also, backup is an important point I should have made into a separate one because if you were to be logged on to a different computer and wanted to access your history, it would need you to login into the browser. Instead this simplifies it by only having you login into the website.
Comment: I'm still not totally on board with the security thing (simply because it _adds_ more history than a regular browser history, and not _replaces_ it). But +1 for the rest and I think backup does deserve its own point.


Action of functors between functor categories

Question: I cannot understand if there is a way to understand the action of a functor between two functor categories, "abstractly".
I mean this: let $\mathcal{C}$, $\mathcal{D}$, $\mathcal{C}$', $\mathcal{D}$' be categories and consider the functor categories $Fnct(\mathcal{C},\mathcal{D})$ and $Fnct(\mathcal{C}',\mathcal{D}')$. Let $H : Fnct(\mathcal{C},\mathcal{D}) \longrightarrow Fnct(\mathcal{C}',\mathcal{D}')$ be a functor. How can I understand the action of the functor $H$ on objects and morphisms without any information about what categories $\mathcal{C}$, $\mathcal{D}$, $\mathcal{C}$', $\mathcal{D}$' actually are?
I found this question Functors Between Functor Categories, but it does not exactly answer to mine.
Thank you
Comment: Well, there is not much to understand with no additional information provided, $H$ just sends functors to functors and natural transformations to natural transformations such that identity transformation and composition of natural transformations is preserved. It might be good to figure out what such functors would be in concrete examples, such as if you take all categories to be sets or posets, grupoids, etc.
Comment: I agree that there's nothing to understand. There's nothing structural that distinguishes a functor category from an arbitrary category-indeed every category is isomorphic to a functor category.
Comment: Ennar speaks truth. Looking back at my question I can only agree with his suggestion. Looking forward to representable functors, the yoneda lemma, and formalizing limits with representability, you become comfortable with these kinds of functors, especially those of the type mentioned in the comments at the link.
Comment: Pardon the revival of an old thread, but aren't functor categories structurally different due to size issues? Categories of functors between locally small categories can be large, and as such we may be unable to prove their existence.
Answer: There is an important special case.
Let $\mathcal{C}$, $\mathcal{D}$, $\mathcal{C}'$, $\mathcal{D'}$ be categories, $T\colon\mathcal{C}'\to\mathcal{C}$ and $S\colon\mathcal{D}\to\mathcal{D'}$ be functors. Then we can define the functor $S^T\colon\mathcal{D}^{\mathcal{C}}\to\mathcal{D}'^{\mathcal{C}'}$ in the following way: $S^T(R)=S\circ T\circ R$ and $S^T(\alpha)(c)=S(\alpha(T(c)))$ for every functor $R\colon \mathcal{C}\to\mathcal{D}$, natural transformation $\alpha\in Arr(\mathcal{D}^{\mathcal{C}})$ and every object $c\in\mathcal{C}$. You can define this functor for every four categories and two functors between them.
For example, let $\mathcal{A}$, $\mathcal{B}$ and $\mathcal{C}$ be categories, $T\colon\mathcal{A}\to\mathcal{B}$ be a functor. Then $T^{I_C}\colon\mathcal{A}^{\mathcal{C}}\to\mathcal{B}^{\mathcal{C}}$ is called a direct image functor and is denoted by $T_*$. Also, the functor
$I_C^T\colon\mathcal{C}^{\mathcal{B}}\to\mathcal{C}^{\mathcal{A}}$ is called an inverse image functor and is denoted by $T^*$.
But, it should be pointed out, that it is of course not true, that every functor $F\colon\mathcal{D}^{\mathcal{C}}\to\mathcal{D}'^{\mathcal{C}'}$ may be presented as $F=S^T$ for some $T\colon\mathcal{C}'\to\mathcal{C}$ and $S\colon\mathcal{D}\to\mathcal{D'}$ (it is not true even for sets), so the functor $(-)^{(-)}\colon\mathbf{Cat}^{op}\times\mathbf{Cat}\to\mathbf{Cat}$ is not full.
A one more special case. Let the first power is trivial, i.e. we consider functors of the form $\mathcal{A}\to\mathcal{C}^{\mathcal{B}}$. Then we may equivalently consider them as bifunctors $\mathcal{A}\times\mathcal{B}\to\mathcal{C}$, because of the exponential isomorphism $(\mathcal{C}^{\mathcal{B}})^{\mathcal{A}}\to\mathcal{C}^{\mathcal{A}\times\mathcal{B}}$.
So, as we can see, there is no (or I don't know) good ways to represent all functors between functor categories, but there are many interesting special cases when such ways exist.
Edit. After some thought, I decided to include the following presentation of all functors between functor categories (in spirit of the second special case): functor $\mathcal{D}^{\mathcal{C}}\to\mathcal{D}'^{\mathcal{C}'}$ is a functor $\mathcal{C}'\times \mathcal{D}^{\mathcal{C}}\to\mathcal{D}'$. But it's hard to call it a simplification.


Proof of formula for area enclosed by parametric curve

Question: Suppose that $\theta \in [0,2\pi]$ and $(x(\theta), y(\theta))$ define a closed parametric curve. There is a formula that says the area enclosed by this curve is equal to $\frac{1}{2} \int\limits_0^{2\pi} (x\frac{dy}{d\theta}-y\frac{dx}{d\theta}) d\theta$.
I know that this is a simple consequence of Green's Theorem however I would like to know if there is a proof of this statement that does not rely on it.
All the proofs I can find online assume that we can actually parametrise our curve by $x$ as well as $\theta$ but this is not the case for many curves defined parametrically so is there a way of getting around that?
Answer: Suppose we express the $2$-vector
$\mathbf r(\theta) = (x(\theta), y(\theta)) \tag 1$
in polar coordinates, thus:
$\mathbf r(\theta) = (x(\theta), y(\theta)) = (r(\theta)\cos \theta, r(\theta)\sin \theta) = r(\theta)(\cos \theta, \sin \theta) =r(\theta)\mathbf n(\theta), \tag 2$
where
$\mathbf n(\theta) = (\cos \theta, \sin \theta) \tag 3$
is a unit vector:
$\mathbf n(\theta) \cdot \mathbf n(\theta) = \cos^2 \theta + \sin^2 \theta = 1, \tag 4$
and
$r(\theta) = \Vert \mathbf r(\theta) \Vert, \tag 5$
as is easily seen from (2) and (4):
$\Vert \mathbf r(\theta) \Vert = \sqrt{r(\theta)\mathbf n(\theta) \cdot r(\theta)\mathbf n(\theta)}$
$= \sqrt{r^2(\theta)(\mathbf n(\theta) \cdot \mathbf n(\theta))} = \sqrt{r^2(\theta)} = r(\theta). \tag 6$
Using the "dot" notation for derivatives with respect to theta, so that
$\dot x(\theta) = \dfrac{dx(\theta)}{d\theta}, \; \dot y(\theta) = \dfrac{dy(\theta)}{d\theta}, \; \dot{\mathbf r}(\theta) = \dfrac{d\mathbf r(\theta)}{d\theta}, \tag 7$
and so forth, we have
$\dot {\mathbf r}(\theta) = \dfrac{d(r(\theta)\mathbf n(\theta))}{d\theta} =  \dot r(\theta)\mathbf n(\theta) + r(\theta)\dot{\mathbf n}(\theta). \tag 8$
We next observe that $x(\theta) \dot y(\theta) - y(\theta) \dot x(\theta)$ is simply the (scalar) $2$-dimansional vector cross product
$x(\theta) \dot y(\theta) - y(\theta) \dot x(\theta) = (x(\theta), y(\theta)) \times (\dot x(\theta), \dot y(\theta)) = \mathbf r(\theta) \times \dot{\mathbf r}(\theta); \tag 9$
thus, using (2) and (8), we compute
$\mathbf r(\theta) \times \dot{\mathbf r}(\theta) = r(\theta)\mathbf n(\theta) \times (\dot r(\theta)\mathbf n(\theta) + r(\theta)\dot{\mathbf n}(\theta))$
$= r(\theta) \dot r(\theta)\mathbf n(\theta) \times \mathbf n(\theta) + r^2(\theta))\mathbf n(\theta) \times \dot{\mathbf n}(\theta); \tag{10}$
since
$\mathbf n(\theta) \times \mathbf n(\theta) = 0  \tag{11}$
and
$\mathbf n(\theta) \times \dot{\mathbf n}(\theta) =  (\cos \theta, \sin \theta) \times (-\sin \theta, \cos \theta) = \cos^2 \theta + \sin^2 \theta = 1, \tag{12}$
we obtain
$\mathbf r(\theta) \times \dot{\mathbf r}(\theta) = r^2(\theta); \tag{13}$
combining (9) and (13) we arrive at
$\dfrac{1}{2} \displaystyle \int_0^{2\pi} (x(\theta) \dot y(\theta) - y(\theta) \dot x(\theta))d\theta = \dfrac{1}{2} \int_0^{2\pi} (\mathbf r(\theta) \times \dot{\mathbf r}(\theta)d\theta = \dfrac{1}{2} \int_0^{2\pi} r^2(\theta) d\theta; \tag{14}$
the rightmost integral in (14) is in fact the area swept out by the vector $\mathbf r(\theta)$ as $0 \rightarrow \theta \rightarrow 2\pi$; see this for a further explanation.
We can in fact easily show that
$\dfrac{1}{2} \displaystyle \int_0^{2\pi} r^2(\theta)d\theta \tag{15}$
is the requisite area directly from first principles if we accept the fact that
$rdrd\theta = dxdy \tag{16}$
is the area element in polar coordinates, a fact which may easily be checked by performing the coordinate transformation $(x, y) \to (r, \theta)$ using $x = r\cos \theta$ and $y = \sin \theta$; I leave the details to the sufficiently engaged reader.  From (16), the area $A$ swept out by $\mathbf r(\theta)$ as $\theta_1 \rightarrow \theta \rightarrow \theta_2$ will be
$A = \displaystyle \int_{\theta_1}^{\theta_2} \int_0^{r(\theta)} r dr d\theta = \int_{\theta_1}^{\theta_2} (\dfrac{1}{2} r^2(\theta))d\theta = \dfrac{1}{2}\int_{\theta_1}^{\theta_2}r^2(\theta)d\theta; \tag{17}$
if $0 \rightarrow \theta \rightarrow 2\pi$, then (17) yields
$A = \dfrac{1}{2} \displaystyle \int_0^{2\pi} r^2(\theta)d\theta, \tag{18}$
in accord with (14).


Simple JQuery .fadeIn event not working correctly on my browser

Question: I'm new to JQuery and trying out some basic events.
I used the fadeIn event on my website under construction page (my website
The code I'm using is as follows, applying only to the three present selectors:
$(document).ready(function(){

$('#logo').fadeIn(3000);
$('#heading').delay(2000).fadeIn(3000);
$('#tagline').delay(1000).fadeIn(3000);

});

While my boyfriend says it works in his Chrome browser every single time he refreshes, it doesn't always work in mine. Sometimes the image appears, sometimes it doesnt. Sometimes it works perfectly, sometimes it doesn't.
Could this be my internet connection? Or is it my code?
I'm new to this so any help would be greatly appreciated!! Thanks in advance.
Juliana
Comment: Does it work consistently if you refresh with ctrl+F5 vs just F5? I'm thinking the image isn't loading fast enough or at all randomly. I would expect jsut refreshing with F5 to work fine after the first load. If this is the case, use `$(window).load()` instead of `$(document).ready()`
Comment: _it works in his Chrome browser every single time he refreshes, it doesn't always work in mine_... what is yours? IE, Firefox etc?
Comment: I have the same exact version of Chrome that he does and sometimes it will load out of order, sometimes the image won't load, sometimes it will all work...it happens randomly which is what confuses me...
Comment: @juliana It's also happening randomly for me.. some reason it seems like the logo div isn't fading in
Comment: I am in Chrome 23 on OSX and I haven't seen any issues. The large image shows and then the other text below it loads after. It's possible that the logo isn't downloaded until after the page html has loaded and rendered and the animation has started, which would cause it to not show until the page was refreshed.
Comment: side note: You are loading a ton of fonts that you aren't using.
`

`
Comment: @Kevin B it looks like the $(window).load() has fixed the problem but I'm not sure it's so in other browsers, I'll have to check it out but thanks! As for the refresh with ctrl F5, my mac doesn't seem to do anything when I try it. Anyway, thanks!!
Comment: @pferdefleisch true...noted ;) guess I'm a font hoarder oops!
Answer: I'll keep this answer here, but the more obvious and much easier non-overkill method would likely be what @Kevin B suggested in the comments above and using $(window).load() which waits for all page content to be loaded as well instead of $(document).ready() which waits only for the HTML DOM to be loaded.

What you probably want to do is ensure that the image has been loaded before you try and fade it in. If it's not loaded when the page is finished being rendered and your JS runs, it will not show up. Then you will refresh the browser and it will work that time.
Try this:
$(document).ready(function(){

    $("#logo img").bind("load", function () {
        if(!$("#logo").is(":visible")) {
             $('#logo').fadeIn(3000);
        }
    });

    $('#logo').fadeIn(3000);
    $('#heading').delay(2000).fadeIn(3000);
    $('#tagline').delay(1000).fadeIn(3000);

});

What you're doing is first saying that as soon as the image has finished loading, and if it hasn't already been made visible, fade it in. But the problem with that is if the image has already been downloaded before, this won't ever actually fire. So you need to have the normal fadein() below it that always runs as well.
The main problem with this is your timing will be off unless (possibly only by < 1 second) unless you want to halt all animations until the image has been loaded for sure.
Here's a fiddle to play around with
Comment: Thanks, that's a really helpful tip. But it looks like just switching my call from $(document).ready() to $(window).load() made all the difference. Would this be more of a safety net though? Just in case that doesn't hold up in other browsers?
Comment: I updated my answer, I think Kevin's answer about using .load() is the better solution and my answer is a bit overkill. I'd stick with using that. But it never hurts to learn more stuff :)
Comment: Thanks for taking the time anyway! Much appreciated
Answer: Most likely the images aren't done loading or simply don't load in some cases, which causes them to just appear rather than fading in because they were not visible when the fadeIn occurred. To avoid this, make sure they are first loaded by using the window load event.
$(window).load(function(){
  // do stuff
});


Answer for Battleships Lieutenant Level 16

Question: Does anyone know the answer for Lieutenant Level 16 of the Battleships puzzle game for the iPhone? I'm stuck. I got all the other levels and I can't advance without figuring out this one.
Comment: I don't have an iPhone - is it similar to [this game](http://jayisgames.com/archives/2011/01/classic_battleships_light.php)? If so, you may want to just show us the level - that way, it would still be possible to provide an answer.
Answer: I think this does the trick:

o----o-2 Line 1
-------0 Line 2
-----o-1 Line 3
-----o-1 Line 4
-------0 Line 5
--ooo-o4 Line 6
o-----02 Line 7
2011132


Do TRIAC dimmers "wear out"?

Question: I have a 3-bulb fixture on a 3yo dimmer.  It seems -- and this is really impossible to prove -- that the buzzing/singing of the dimmed bulbs has gotten worse over time.  It doesn't really make sense to me that the circuitry would get worse over time though I suppose the heat dissipated by the power components could make them operate more poorly.  Before I replace the dimmer just to see if a new one makes the bulbs sing less, I thought I'd ask if any one could support or refute the idea that old dimmers make bulbs noisier.
Comment: I'm assuming we are talking about conventional dimmers and incandescent bulbs here. Have you tried changing bulbs? Heavy duty or "long life" bulbs have slightly heavier filaments and supports, they tend to make less noise. I'd believe filaments get louder before I'd believe the dimmer is causing the bulbs to be louder, though I'm not totally discounting the latter. But I'd expect the dimmer cause to take much longer than 3 years.
Answer: TRIACs do tend to wear out.  As they age, the waveform becomes more jagged.  Here is what a good TRIAC should do to the waveform when 50% dimmed:

Here is what a failing TRIAC might look like:

(That is actually the current of a CFL:  I couldn't find a failing TRIAC waveform.)
If it is failing, TRIACs seem to fail pretty quickly and enter an intermediate poorly-performing state for only a few hours or days.
You could unscrew one or two bulbs in the fixture and see if that improves the situation to isolate whether it is the bulbs or the dimmer.
For more details about dimmers, see this.

Do TRIAC dimmers "wear out"?


What is craft unloading and how should it be handled?

Question: What is craft "unloading" due to being farther that the "physics distance" from the "main craft"? What is the best way to deal with it? Can it be avoided?
I only find very sparse information on these subjects. "Unloading" is mentioned in this answer and is this Scott Manley video.
My problem is this: I have a craft with two probe command modules, one for the rocket and one for a rover. I sent it into orbit around a moon (Laythe). I sent the rover down to the surface. I switched to the space center. I switched to the tracking station. To my horror the rover is nowhere to be found, it has disappeared without a trace!
How can I switch away from my rover without it disappearing?
KSP version 0.90.0, Windows 8, career mode.
Comment: Those are talking about what happens when a craft is unloaded while moving in atmosphere. The game assumes that anything moving in-atmosphere that you're not controlling is going to crash, so it just destroys it immediately when its physics is unloaded. It's not relevant to a **stationary** rover, even on Laythe in atmosphere. That's why I asked if you had already landed it. Was it moving when you switched to the Space Centre? Did you leave it on a slope of any amount without the brakes on?
Comment: Oh, silly me. I had hid rovers by clicking at the icon in the tool bar at the top of the tracking station view. Thanks for you help. Anyway it would really be useful with some information about unloading around somewhere.
Comment: Did you *land* the rover before switching away from it?
Comment: @SevenSidedDie: Yeah. It was standing on the surface. I also made a quick save, luckily. I could load the quick save and continue exploring with the rover but I would prefer it if it didn't disappear at all.
Comment: It shouldn't be disappearing then—craft unload only has to do with part physics and graphics rendering, leaving the craft there but not simulated. So, if the rover is disappearing, there is something else wrong happening…
Comment: @SevenSidedDie: Scott Manley as well as other sources seem to disagree with you there.
Comment: @SevenSidedDie: Oh, I see. I don't know if it was moving. I'll just have make sure the rover is stationary and try it again I guess. Thank you for your help!
Comment: There is some information about unloaded craft in atmosphere in the [KSP wiki](http://wiki.kerbalspaceprogram.com/wiki/Atmosphere#On-rails_physics). But in general it's not complex enough to be detailed anywhere: if something is near, it's physics-simulated and rendered; if it's not, it's put "on rails" in its orbit and ignored except for orbital position updates.
Answer: Things outside of physics range (2350 meters, or thereabout) is unloaded.
This means that the physics engine isn't handling it anymore. Let's pretend that the tracking station takes control of it instead. Now, if it's in a situation where it would crash, such as in the atmosphere under 30000 meters, it would disappear and any onboard personnel would be listed as Missing.
However, I read in the devblog yersterday that they are tuning this up to 20km for stuff in the atmosphere in 1.0 (which is now in experimental).
To avoid unloading of the rover, you can:
a) Don't switch away from it when it's in an atmosphere or heading there
 b) Wait until your rover is landed and standing still
 c) Keep nearby
Update: As of 1.0.2, the physics range has indeed been increased to 20km when in atmosphere.


how to get twitter analytics using twitter gem rails?

Question: I want to get twitter analytics for tweets I posted using twitter gem in my ruby on rails application. Is there any possibility to achieve this ? I want to show tweet impression on my application,please let me know if there is any possible way .
Answer: You can pull engagement data for your account as a whole. On a per-tweet basis you can pull in a favorites count as well as a retweet count. Here is an example the latter:
First define your client like so:
client = Twitter::REST::Client.new do |config|
    config.consumer_key        = Devise.omniauth_configs[:twitter].strategy.consumer_key
    config.consumer_secret     = Devise.omniauth_configs[:twitter].strategy.consumer_secret
    config.access_token        = self.identities.find_by(provider: :twitter).token
    config.access_token_secret = self.identities.find_by(provider: :twitter).token_secret
end

Now define the API endpoint you want to pull data from along with an array of tweet ids you want to get data on:
path = "1.1/statuses/lookup.json"
ids = ['1234567890','56324931407']

Now call the API and do something with the response:
response = Twitter::REST::Request.new(client, 'get', path, {id: ids, map: true}).perform

The result you get back will be a JSON hash where the keys are the post ids. Calling map: true in the options hash tells the API to include missing post keys with a null value, rather than excluding them from the response. You can read more in the docs on the Twitter::REST::Request class.
Note that with the Twitter::REST::Request class you can specify any path and/or method from the API.
If you want to calculate engagement data for your account, you will have to pull in a large batch of tweets (say 100) and then parse the response and calculate the rate yourself, as Twitter doesn't offer that data through the API in a prepackaged way. This Quora post goes into more detail on how you can calculate the engagement rate yourself.
As for pulling impression data, that is not currently possible through the public API. See this discussion for more details.


Push partial file changes in git

Question: I am trying to figure out how to push partial file changes from my local git repo to a tfs git project.
For some background, I have a project that uses an external wsdl. I have a local dev instance of the wsdl on my machine, and the production application will run on a production version of the wsdl hosted on a different server. I have the project in my local git repository pointed to my local dev wsdl, and the production project in tfs pointed to the remotely hosted wsdl.
My issue is that when I push code changes from my local dev repo to the tfs repo, I don't want my connections to the dev wsdl being pushed with the changes. My end goal is to be able to make code changes, bug fixes, etc, and push those to the tfs repo without changing any of the production configurations.
I may be going about this incorrectly, but figuring out the best way to tackle this is why I'm here. Are there specific procedures developers usually use to handle this kind of situation?
Comment: Does this answer your question? [Commit only part of a file in Git](https://stackoverflow.com/questions/1085162/commit-only-part-of-a-file-in-git)
Comment: @mkrieger1 I had not seen that yet but I'll take a look and give it a try. Thanks
Comment: @mkrieger1 this isn't exactly what I was looking for. I should have been more precise...when I want to move changes to the tfs project, I would first merge them from the dev branch to the prod branch in my local repo. After that, I would push the prod branch to the tfs repo. The merge is where I'm having issues. I found something on "cherry picking" commits, but it doesn't seem to be a widely recommended practice
Answer: Since you have different configuration file between branches, when you perform merge, you would get conflicts. For this scenario, you could check Merge Strategies.

You can also use Git attributes to tell Git to use different merge
strategies for specific files in your project. One very useful option
is to tell Git to not try to merge specific files when they have
conflicts, but rather to use your side of the merge over someone
else's.
This is helpful if a branch in your project has diverged or is
specialized, but you want to be able to merge changes back in from it,
and you want to ignore certain files. Say you have a database settings
file called database.xml that is different in two branches, and you
want to merge in your other branch without messing up the database
file. You can set up an attribute like this:
database.xml merge=ours

And then define a dummy ours merge strategy with:
$ git config --global merge.ours.driver true

If you merge in the other branch, instead of having merge conflicts
with the database.xml file, you see something like this:
$ git merge topic
Auto-merging database.xml
Merge made by recursive.

In this case, database.xml stays at whatever version you originally
had.

.gitattributes - is a root level file of your repository that defines the attributes for a subdirectory or subset of files.
Comment: Have you checked my reply? Is it helpful?
Answer: Here some suggestions maybe you can have a try:

Try using .gitignore for your repository to ignore the files you do not want to push.
If the files you want to push is not too many, generally only several files, you can use the git add command to add these files as the pushed files.

For example:
git add path/to/file1 path/to/file2 path/to/file3
git commit -m "commit message"
git push

In this example, only the files path/to/file1, path/to/file2 and path/to/file3 will be pushed to remote repository.

If there are many changed files you need to push, you can try as the following steps.

Make sure the local repository has been up to date with the remote repository. If not, use git pull or git fetch command to update local repository.
Copy the local repository to a temporary folder in another directory that outside of the repository directory.
Do changes of the code in the temporary folder.
Use some the tools, such as Beyond Compare, to extract the changed files you want to push.
Copy the extracted files to the local repository to overwrite the original files.
Commit and push the changed files.

Push partial file changes in git


First time hiring contractor

Question: Hiring a contractor for the first time to replace carpet with wood floors. They are a local company with a great reputation. A couple questions. Any advice appreciated!

They've offered a pretty significant discount if I pay in cash. I'm considering it because of the savings, but worried about having no proof of payment if I do that. Is this a bad idea? Any way to protect myself?
They are asking for a 50% deposit. I have the money to pay it, but just wondering if this amount is normal? I thought I'd read online that more like 10-25% was the norm. If the deposit were lower I'd probably be less worried about the cash payment.
Comment: you have a better business bureau?  does the company have good reviews?
Answer: If you are hiring only a company to do flooring, a larger deposit is customary.  The 10 to 25% is for hiring a general contractor to construct a home or do major whole home renovations.
With a cash payment you should still insist on a written contract outlining what is to be done and for how much and how long it is expected to take.
Comment: Some sort of quality standard in the contract documents is wise also. Simply invoking material supplier instructions can be helpful in arriving at a shared set of expectations. "Unless waived in writing by customer" is helpful language to maintain formality around necessary workarounds that frequently arise.
Comment: Also, request a written receipt on their letterhead, from their receipt book, whatever, even if it's just a piece of paper hand written by your contractor and signed by him. Also, consider that he's got to shell out a _lot_ of money to pick up the flooring material, so he needs some funds up front for that.
Comment: When you pay cash, you should expect a receipt, and if a receipt is not provided, the cash should not be, either.

First time hiring contractor


C++11 chained construction compliance in g++

Question: I was just wondering if g++ actually complies with the C++11 standard of chained constructors (or whatever it's called).
example:
class MyClass
{
  MyClass(int x, int y = 0);
  MyClass(int y = 0) : MyClass(8, y) {}
};

I keep getting this error even though I've included the -std=c++0x (or -std=gnu++0x) parameter (there is no -std=c++11)

error: type 'MyClass' is not a direct base of 'MyClass'

I don't want to jump to conclusions and I've looked around the net but can't seem to find any information about it.
By the way, I'm using g++ (Debian 4.6.2-4) 4.6.2
Answer: It's not yet supported (look for delegating constructors).
Other than that, don't you think your design is highly ambiguous? What should MyClass(1) call?
Comment: good catch on the ambiguity.  i was just making an example.  my real code uses two (very) different types, so i dont have that problem.
Comment: See also http://stackoverflow.com/questions/10417314/c-init-member-variables-with-multiple-constructors#comment13441709_10417381