Why would I split captured monster parts, and which parts should I split?

Question: Sometimes when killing a monster, you get a part of that monster, which you can split into other items, or keep.  Since I have no idea what they're for and splitting can't be undone, I've just been choosing to keep them.
What are they for?  Should I be splitting them instead?
Answer: Splitting captured monsters
Splitting captured monsters will result in components which can be used to upgrade existing weapons and shields and also craft new weapons, shields and accessories using recipes.
Keeping captured monsters
Not splitting monster parts means that you can sell the captured monster to different shops which will result in more money than splitting them would. Selling captured monsters will also unlock new items for purchase over time.
What should I do then?
With no components you can't upgrade your equipment, so its generally a good idea to split captured monsters until you have at least around 10 of the associated components before you start to sell them instead.
Also, some components can be rare which is also a reason to initially prefer splitting.
As stated above, besides money there is another reason to sell captured monsters. By selling captured monsters, you will cause new items to appear in shops over time. Each monster is associated with different categories and when sold, points are added to these categories.
By accumulating enough points in a category, new items are unlocked, called trade goods.
For a list of unlockable trade goods, please see this wiki page.
To summarize, splitting should be preferred initially for crafting and upgrading reasons, but selling the captured monsters will net you more money and the availability of new items in shops.
Comment: Are you 100% sure that selling captured monsters will cause new items to appear in shops? I really haven't noticed selling captured monsters have any effect on the change of items shops are selling when i was playing this game ages back.
Comment: @ChisHateZ Yes, while it doesn't happen immediately, selling captured monsters does cause new items to appear. Basically, each sold monster contributes by adding points to different categories and when a certain amount of monsters have been sold, new items are unlocked. This link explains how it works pretty well: http://lastremnant.wikia.com/wiki/Trade_Goods
Comment: Does it matter which shop I sell the monsters to *(will the new items only be available in that shop, or all shops?  Also, I thought I remember hearing some shops pay significantly more for certain monsters - how do I know which shop?)*?  Are there any specific monsters I should keep or split, because, say, they are needed for a certain weapon/upgrade and I never get a second chance of capturing them?
Comment: Yes, it's shop specific. It's been quite some time for me, but as far as I remember some will show them as out-of-stock or "invisible" at first. You don't need monsters for upgrades, just their components, so feel free to split if you're still missing some item (it's what I always did and never had an issue with this).
Comment: As far as I understand, which shop you sell the monsters to doesn't matter. However, it is indeed true that different shops will sell different items. I could be wrong though.


How to level up your World in Borderlands 2

Question: I leveled up my Mechromancer in Borderlands 2 with Gibbed Borderlands 2 Save Editor, but I only see Level 36 enemies that drop Level 36 items. How I can change the World Level with the program?
Comment: The first playthrough has enemies from level 1 to 30-something. The second one has from said 30-something all the way to 50. The THIRD playthrough - Ultimate Vault Hunter Mode - is the one that has enemies who scale to your leve.
Comment: I thought enemies levelled based on the player, perhaps you're in an area where the enemy level cap is low?
Comment: Have you tried leveling up normally for 1 level to see if it updates the enemies?  Not sure if this is the answer, but just curious if you have tried.
Comment: Are you playing the game for the second time? I think the first playthrough is capped. So you might need to defeat jack, and start a second playthrough (that one has a special name, I can't recall it atm).
Answer: While I'm not familiar with this tool that you've used, I assume you were in your first playthrough. During the first playthrough, enemies only get up to around level 35. Once you've finished that playthrough by

 killing The Warrior

You will unlock the next playthrough, True Vault Hunter Mode. During this playthrough, enemies start at approximately level 34 and go all the way up to level 50. Once the playthrough is completed, all enemies will be level 50. The Borderlands Wiki highlights other ways enemies are different besides level (summarised by me):

Increased Enemy Health
More Badasses
New Enemies
Better Loot
More XP from missions

In both of these modes, enemy level is based on the zone that you're in.
Once you complete this mode (in the same manner as the first), you will unlock a third playthrough: Ultimate Vault Hunter Mode. In this playthrough, enemies just scale to the highest level in the party (during solo this will be your level). The enemies always scale to the level of the highest party member, regardless of area that you are in (unlike the other two modes).
The reason you are only seeing enemies up to level 36 is because you are probably in the first playthrough still. You will need to play through the main story, and complete this playthrough to unlock subsequent playthroughs where enemies and loot will be higher.


How can I read the User properties saved in the File/Project properties menu?

Question: In the Google Apps Script editor, I can set a user property by opening the File > Project properties menu, and then selecting the "User properties" tab. However, it seems that the PropertiesService is unable to access the values set in this menu. Is there a way I can access the values set through this menu in my script?

Set {"propertyA", "valueA"} in "User Properties" tab (pictured
below)

Run PropertiesService.getUserProperties().getProperties()

Output: {}

If I were to then run PropertiesService.getUserProperties().setProperty("propertyB", "valueB"); and then getProperties() again, the output would update to show only {propertyB=valueB}.
Similarly, as my searches all direct me to the PropertiesService, where can I find documentation about these menu properties? (Specifically, I'd like to know when I should use the menu option versus setting the values programatically.)
Comment: Is this thread helpful for you? https://stackoverflow.com/questions/24908799/var-userproperties-propertiesservice-getuserproperties-is-not-working-prope
Comment: @Tanaike It was, thank you. I haven't tested it, but it seems the UI is accessed via a deprecated method. Reading through that thread also inspired me to look through Google's issue tracker and, indeed, the bug was reported a few years ago and seems to have been assigned in early 2017. https://issuetracker.google.com/issues/36762534
Comment: Thank you for the additional information.
Answer: No. The GUI for accessing user properties was never updated when the UserProperties class was deprecated in 2014. The issue was finally resolved with the redesigned Apps Script IDE in 2020, which removed the GUI for accessing properties altogether.
Although it is possible to access the legacy IDE and modify script properties via the menu, the only way to access user properties is programmatically with PropertiesServices.getUserProperties(). Google has also published a guide to the Properties service.


How to set a cell editable in jqGrid after the setcell method is called and values set in jqGrid cells?

Question: I have a unique requirement in jqGrid. I'm using a jqGrid with data from a backend SQL Server. Everything is working fine. My problem is that I'm was using the setCell method in JQGrid to set some values in cells.
grid.jqGrid('setCell', rowId, finalJsonColumnName, value);
It's working and setting values correctly. My problem is that after setting the values in jqGrid, the particular cell became uneditable.
I don't need the cells to be uneditable after setCell. I want them to remain editable. I was trying to call another method to make the cells editable:
grid.jqGrid('setCell', rowId, 'precPsProg', '', 'editable-cell');
But it's not working. Please can anyone help me out?
Comment: There are only class `"not-editable-cell"` and no `"editable-cell"` which jqGrid use. You should describe more clear what you do, why you need to use `setCell`. You don't wrote even which editing mode you use. Is it [cell editing mode](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:cell_editing)? Why you need to use `setCell` during the cell is editing. Moreover it could be that you use word "uneditable" for the cells which are **editing**? Be editable means that the cell can be editing after some additional action like click on the cell. It's not the same as be editing.
Comment: Kindly post your code for more clearance
Answer: Despite of this is an old thread, I had the same problem when setting the value of a cell  using the setCell method in JQGrid (the cell became uneditable). After hours of searching, I found a solution, by using this:
document.getElementById(rowId + "_Column_Name").value = some_value;

This sets the value of the specific (row, column) cell, and it remains editable (being submitted to the server when saving the row).


I am getting following error when I create a django project in pycharm for Mac OS

Question: I have been installed django using following command in terminal:
sudo pip3 install django

and I got this response:
kinredondeMacBook-Air:~ kinredon$ sudo pip3 install jiango
The directory '/Users/kinredon/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/kinredon/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: jiango in /usr/local/lib/python3.6/site-packages
Requirement already satisfied: django<1.5,>=1.4 in /usr/local/lib/python3.6/site-packages (from jiango)

then I create a django project in Pycharm and I get this following error:
Error:Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/bin/django-admin.py", line 2, in <module>
from django.core import management
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 54
except ImportError,e:
^
SyntaxError: invalid syntax

Anyone can help me? Thanks!
Comment: I suggest you use a supported version of django, this project `jiango` is using a very old version of django.
Comment: Thanks for your comment. I have solved this problem.
Answer: The error message indicates that the folder is not owned by current user. So you need to change the owner by the following command:
sudo chown kinredon -R /Users/kinredon/Library/Caches/pip

Learn more about chown here.
Comment: I have executed this command:
`sudo chown kinredon:kinredon -R /Users/kinredon/Library/Caches/pip/http`
but it return this result:
`chown: -R: No such file or directory`
but I `ls /Users/kinredon/Library/Caches/pip/http`, this directory exists.
Comment: I have a try and get same results.
Comment: and I have successfully execute this command:
`pip3 install django`
and get a right result:
Requirement already satisfied: django in /usr/local/lib/python3.6/site-packages
but when I create a django project I have get this error:Error:Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/bin/django-admin.py", line 2, in from django.core import management File "/usr/local/lib/python3.6/site-packages/django/core/management/init.py", line 54 except ImportError,e: ^ SyntaxError: invalid syntax
Comment: Run `pip3 install Django`


Changing check attribute of jquery dom items in a variable array

Question: Ok, So I have a list of checkboxes in a pop up. I grab two lists of jquery dom elements, a list of the checkboxes and a list of the checkboxes that are checked. The idea is that the user can change the checkboxes then if they want to, press a cancel button and it will revert to the original.
I get the two lists...
var allDropDownCheckboxes = $(this).next().find(".dropDownCheckbox");
var selectedCheckboxes = $(this).next().find(".dropDownCheckbox:checked");

On the cancel button being pressed I revert the checkboxes to their original state...
allDropDownCheckboxes.attr('checked', false);
selectedCheckboxes.attr('checked', true);

It unchecks them all but doesn't check the ones that were originally checked again...
Why?!
Thanks
Answer: try to use .prop() instead of .attr()
allDropDownCheckboxes.prop('checked', false);
selectedCheckboxes.prop('checked', true);

Answer: Try to use .prop() instead of .attr() to set the checked state of form elements, from the docs:

As of jQuery 1.6, the .attr() method returns undefined for attributes
  that have not been set. To retrieve and change DOM properties such as
  the checked, selected, or disabled state of form elements, use the
  .prop() method.

allDropDownCheckboxes.prop('checked', false);
selectedCheckboxes.prop('checked', true);


What does a segmented health bar mean on a hostile NPC?

Question: Starfield, PC via Steam.
Most 'normal' hostiles have a health bar that looks like a single bar which decreases as you hurt them:

The screenshot above is from an animal on this planet I'm exploring. There is a single white bar underneath the creature's name which indicates its health.
However there are some more difficult hostiles which have two health bars: the white one, and then below it a segmented red health bar.

What happens when you fight one of these creatures, is that the white health bar will decrease as normal when you deal damage. However, once it is fully emptied, one of the red segments then disappears and the white health bar is refilled.
When fighting human enemies like space pirates, these stronger NPCs were more likely to be carrying rare, epic, or legendary loot. And, as humans, I had been assuming that they were using med packs or something and the red segments indicated how many health buffs they had remaining.
But the above screenshot is from a creature, so my theory doesn't pan out. What's the logic of this segmented health bar mechanic? Is it just some convenient way of showing your puny damage against a large amount of enemy hitpoints?
Or, considering this is also a Bethesda game -- is this Starfield's equivalent of Fallout 4's "legendary" enemies, where once you drain their HP they'd regenerate and you'd have to do it all over again? If that's the case, is there an equivalent of Fallout 4's one-hit mechanic -- eg if you can 'kill' the legendary in a single hit it doesn't do the regeneration?
Comment: I imagine it's "some convenient way of showing your puny damage against a large amount of enemy hitpoints". Plenty of other games do this as well, it's not unique to Starfield.
Comment: This reminds me Dragonball: Final Bout, it's a classic fighting game but your opponents used to have more than one different-colored HP bar, instead of the standard 2.
Answer: Those multiple bars indicates an Elite Enemy, Starfield's equivalent of Fallout 4 Legendary enemies, like you said--it's their way of showing that an enemy has multiple health bars.
Once you zero out the white health bar of an enemy with these extra red bars, one of the red bars goes away and their white health bar fills up to 100% again.
You can view how many Elite enemies you have killed over time by pressing the B key and selecting Combat. The types and respective numbers of each combat related accolade you have achieved are shown on the right.


Prove that there there are two $a,b$ so $f''(a)=f''(b)=0$

Question: I'm trying to prove the following theorem:
Let $f$ be a function that can be derived twice. We know that $f$ is even function and has local minimum at $x=2$. Prove that there there are two $a,b$ so $f''(a)=f''(b)=0$.
I think that I need to use the Rolle's theorem here but after trying for one hour, I can't seem to figure out how to do it.
Answer: Hint: $f$ has a local minimum at $-2$ also. Any even differentiable functions satisfies $f'(0)=0$. Thus $f'(-2)=f'(0)=f'(2)=0$. Can you finish?
I am assuming that the domain of your function is $\mathbb R$.
Answer: This is not necessarily true. Let:
$$f(x)=\begin{cases}
(x+2)^2 \ \ \text{if} \ \ x\in(-2-\frac12,-2+\frac12) \\
(x-2)^2 \ \ \text{if} \ \ x\in(2-\frac12,2+\frac12)
\end{cases}
$$
Where:
$f:(-2-\frac12,-2+\frac12) \cup (2-\frac12,2+\frac12) \to \mathbb{R}$


Subalgebra of free associative commutative algebra which is not free

Question: I'm trying to provide a counterexample for analogue of Nielsen–Schreier theorem for the variety of associative commutative algebras (not necessary with unity) over a filed $F$.
A counterexample for noncommutative case is well known: ideal generated by commutators in a free algebra on 2 variables $F<x,y>$ is not itself a free algebra.
In commutative case the above construction obviously does not work, but I'm sure that there is a subalgebra of free commutative algebra which is not free.
I think that ideal generated by $x^2$ (or $F[x^2,x^3],$ it's the same subalgebra) in $F[x]$( $F[x]$ here means commutative polynomial algebra over $F$ without unity) is not a free commutative algebra.
Is my hypothesis correct? If yes, how do I prove it?
Firstly, I think that every free proper subalgebra $A$ of $F[x]$ which is also an ideal of $F[x]$ must be generated (in sense of free algebras) by single element:
Let's consider two nonequal generators $f$ and $g$ of $A$. $F[x]$ is an unique factorization domain implies that $f\cdot h_1 = g\cdot h_2,$ where $h_1 \neq g,$ $h_2\neq f$ because $gcd(f,g)\neq 1$ (It's well known that $F[x]$ is also a Principal ideal domain).
Next, multiplying on any $i \in A$ (in our case we can take $i=x^2$), we get $f\cdot (h_1\cdot i) = g\cdot (h_2\cdot i),$ and $h_1\cdot i, h_2\cdot i \in A$ implies that they can be expressed as terms in generators of $A$, so we have a nontrivial relation in $A$ and $A$ is not free (However, I'm not sure that this relation is a nontrivial one).
Is this correct? If it is, it can be applied to the case above, and it should be then easy to prove that $F[x^2,x^3]$ can't be freely generated by one element.
If not, it still seems to be true that every free subalgebra of $F[x]$ which satisfies the above conditions must be 1-generated in free sense.
So, can you help me with this?
Pardon my poor English and LaTeX skills.
Thank you in advance.
EDIT:
It appears that I was correct with my assumption. P. M. Cohn in his article Subalgebras of
free associative algebras provides exactly $F[x^2,x^3]$ as an example of subalgebra of $F[x]$ which is not free. A theorem in article states that subalgebra of $F[x]$ is free if and only if it's integrally closed, and $F[x^2,x^3]$ is not integrally closed.
Also, proving necessity, he states that that every free subalgebra $R$ of $F[x]$ is either $F$ (in this article only algebras with unity are considered) or $F[y]$ for some $y$ transcendental over $F$, and in each case $R$ is integrally closed.
It's stated as obvious that the number of free generators of $R$ is 1.
So, is my proof correct?
Comment: Your proof is not correct. $F[x^2, x^3]$ is not an ideal. The ideal generated by $x^2$ doesn't contain the identity.
Comment: Well, judjing by your answer it seems we have a definition conflict or something. $F[x^2,x^3]$ is definetly a subalgebra; multiplying any poylynomial on polynomial like $a_2 x^2+\dots +a_n x^n$ (which is a typical member of $F[x^2,x^3]$) we still get a polynomial of that type. Maybe I haven't made clear that I'm considering the variety of *all* associative commutative algebras, not only unital ones. Of course $F[x^2,x^3]$ is a non-unital algebra, just as $F[x]$. Maybe I need to note this somehow?
Comment: For me $F[x^2, x^3]$ denotes the _unital_ subalgebra generated by $x^2$ and $x^3$. I think it is not standard for this notation to refer to $(x^2)$. What do you mean by $F[x]$?
Comment: Okay, I will emphasize mentioned above in my question, thank you.
Comment: Yes, it was my fault. By $F[x]$ i mean free associative commutative algebra on one generator, i.e commutative polynomial algebra over F without unity.
Answer: The only nonzero ideal of $F[x]$ which is also a subalgebra is $F[x]$, since any such ideal needs to contain a nonzero idempotent and the only one in $F[x]$ is the identity. You are correct that $F[x^2, x^3]$ is not a polynomial algebra; this should be clear from degree considerations (a generator must have degree exactly $2$ or else it can't generate $x^2$, but then the subalgebra it generates consists of polynomials of even degree so can't contain $x^3$).
Geometrically $\text{Spec } F[x^2, x^3]$ is the singular curve $u^2 = v^3$, so cannot be isomorphic to the affine line which is nonsingular. To convert this into an algebraic proof we consider the dimension of the space of derivations $D : F[x^2, x^3] \to F$ satisfying
$$D(ab) = D(a) \phi(b) + \phi(a) D(b)$$
where $\phi : F[x^2, x^3] \to F$ sends $x$ to $0$. This space can be identified with the Zariski tangent space at the origin and is $2$-dimensional, which is not true of the corresponding tangent space at any point of the affine line.
Comment: What would be the trascendence degree if it were a free algebra on *more* that one generator?
Comment: $F[x^2,x^3]$ is noetherian, so if its free it is free on finitely many generators. But it is not integrally closed, so it is not free.
Comment: @Yury: its fraction field has transcendence degree $1$.
Comment: Yes, it's obvious that $F[x^2,x^3]$ can't be one-generated freely. But why should there be only one generator? For example (maybe not so appropriate, but still) free group on two generators contains a free subgroup of countable rank. According to article mentioned above, it is true, but I don't know if my proof is correct.
Comment: @Mariano: yes, the number of generators must be finite because $F[x^2,x^3]$ is noetherian, it's helpful note. But I'm trying to understand why should it be exactly one?
And yet another question (it can be dumb, but I've never worked with integral extensions): is commutative polynomial algebra over $F$ *without unity* still an integral domain? It seems that Euclidean algorithm still holds in that algebra, am I correct?
Comment: (Please do not ask new questions in comments to answers to different questions!) Qiaochu has given a perfectly nice reason why there could only be one generator. I gave you a reason why it cannot be a polynomial ring in *any* number of variables.
Comment: @Qiaochu: Sorry, but I can't understand your answer completely. Fraction field of $F[x^2,x^3]$ is $F(x)$ — the fraction field of all $F[x]$, and it's clear that its transcendence degree over $F$ is 1. But I don't get how it corresponds with the number of free generators of $F[x^2,x^3]$?
Comment: Well yes, I forgot that the generators must be algebraically independent, and they will be not in $F(x)$, then in $F[x]$ too, and that means the algebra will satisfy a nontrivial relation. Yes, it was quite simple. Thank you guys, you made it clear to me. (Though I still would like to know if my proof is correct)


C# test project Wipe database before the tests are run

Question: I have a ASP.NET MVC3 application, where i need to test a database wrapper class. This is up and running. But i need to recreate the database, when the test starts. I need to wipe all data in database. The database is a test double.
I have the SQL script creating the database. For now im running this manualy in "SQL Server Manager" and it works. But I would like to have the script run before a new test run.
Anyone know how to do this?
Answer: EDIT - Replacing with a decent answer.
Create a C# class that looks like this -
<code>using System;
using NUnit.Framework;

namespace NUnit.Tests
{
  [SetUpFixture]
  public class MySetUpClass
  {
    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
      // Set up my database with SQL scripts run via SqlCommand
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
      // tear down my database  with SQL scripts run via SqlCommand
    }
  }
}
</code>
That should run setup once only before any tests, and then teardown once only after all tests have completed.
I realize I'm raising this one from the dead but I felt it was time it got a decent answer.
In any case, there is a much better way.  Mock your datalayer and test that.  Then make certain everything done with SQL Server is in the form of Stored Procedures and Functions.  Then use Visual Studio to create unit tests for those sprocs and functions.
If you have logic in your repositories, I recommend grabbing Insight.Database and making use of its AutoInterface feature.  That way, your repository layer is merely an interface, which you can easily mock and move on.
Comment: I already have this scripts. I drops all tables, then recrates them. But I can't figure out, how to to run this script before my test run.

The database im testing aginst is deployed on my local SQLExpress server.
Comment: Well, I guess you could do it from code and use the content of your script as the SqlCommand.Text property.
Answer: Place this code within your unit test class.  You should do all your database creation here. The TestInitialize runs before any tests begin.  This will happen once, ever time a unit test is started.
<code>    [TestInitialize]
    public void TestInitialize()
    {
        -
    }
</code>
Comment: But im not looking for a action to run before each test.
I just need to recreate the DB, with a .sql file, when ever i start the test run.


Allow only the EXACT user of the post to edit it

Question: Supposed that I have a posts table like this:
post_id       topic_id       user_id     content         date
 1               7            12         bla bla         7/15/2014
 2               16           70         bla bla         7/16/2014
 3               7            14         bloa bla        7/20/2014

In which the user_id is the foreign key of the users table.
Assume that I could record the user session by using $_SESSION['user_id'] after he signs into his account to perform the EDIT action (via the edit.php page). And assume that I can get ($_GET) the post_id into the hyperlink edit.php?id=1 for editing.
As you can see, each user_id has got a certain post_id, and unique logged-in session. My problem is that, for example, when Mr.Eric (user_id #12) browses his own post (post_id#1) does a trick by manually changes edit.php?id=1 to edit.php?id=2, then he edits the post_id #2 whose user_id is actually user_id#70, which is NOT ALLOWED logically.
I did try the following query, but i failed to check the correct user session as i wished:
$q="SELECT user_id, post_id, content
        FROM posts
        WHERE user_id = {$_SESSION['user_id']}
        ";

$r = mysqli_query ($dbc, $q);

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$uid = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : -1;
$current_user = $row['user_id'];
}

if(!$uid && $uid != $current_user){
   echo 'sorry, but this is not your own post for editing!';
}

Can you help, please? Thank you!
Comment: var_dump() your $uid and $current_user, compare it.
Comment: You check if the variable is defined in your loop. You don't check for that in your SQL. You last if statement says if its false (which it never will be, because you either assign it to the user id of the logged in user, or -1 (neither are false unless your user ID is zero - falsy).
Comment: @crowler: I define it in the `while loop`, but still failed. Not sure if it's correct or not? The code is `if (!defined('edit') ) { if (!$uid && $uid != $current_user) { ... }  define('edit', TRUE);}` **Can you help with the actually one as an answer?** I am really stuck!
Comment: @HendraLim: After doing the `var_dump()` and compare them, it shows like this `string(1) "1" string(2) "70" string(2) "70" string(1) "1"`. *Can you help my with the correct conditional*, please?
Comment: do u put var_dump() inside while loop?
Comment: @HendraLim: Yes, I put the `var_dump($current_user)` inside the `WHILE` loop only, because I think that the variable `current_user` was just created for the loop result checking. Sorry, but am I correct?
Answer: It looks like the && in if(!$uid && $uid != $current_user){ should be ||.
The line looks like its saying in pseudocode, if $uid doesn't exist AND $uid does not equal $current user do something, otherwise, do nothing.  $uid DOES exist in your example so it'll return FALSE and skip your whole if.
That means the $uid doesn't have to match $current_user, it just has to exist and it can edit anything.
Comment: I try this, but fail!


GFCI Outlet or Breaker

Question: As a part of my renovation of a 1900's cottage I'm completely rebuilding the kitchen.
I'm planning on running 2 20A circuits shared between the countertop outlets, fridge & dishwasher.
Is there any objective reason (or code requirement - GA, USA) to choose to do either:
1. A GFCI outlet as the first outlet in the chain (or at the 1st location in the chain where a GFCI is required like near the sink)
2. A GFCI breaker in the panel for each circuit
What leads me to ask this question is that in the country where I am originally from, it is standard practice for all outlets in a house to be protected by a single large 'Earth-Leakage Circuit Breaker' in the electrical panel, so having individual sockets protected seems unusual to me.
Comment: GFCI breakers and outlets have trouble with motor loads, I have replaced dozens if not hundreds on Garbage disposals, Freezers, dishwashers & Refrigerators. I believe this is the reason Oregon exempts these devices from GFCI Protection.  You still can daisy chain feeding the Fridge first then install a GFCI outlet for 1 of the required circuits. I recommend a dedicated Fridge circuit and a dedicated dishwasher / garbage disposal circuit.
Comment: Since you are completely rebuilding, that counts as a remodel and you must come into full compliance with current code.  There isn't any wobble on this, no grandfathering.
Answer: You can run the fridge but not the dishwasher as shown in exhibit 210.28. It also depends on where you live local code may have exemptions or tougher requirements. I usually run a dedicated circuit for the fridge. There is an exception that allows a gas stove igniter and a clock outlet on the 2 small appliance circuit.
The wording is counter top a dishwasher, Garbage disposal, trash compactor and in some cases a built in microwave require additional circuits. It really depends on local requirements. But Exhibit 210.28 clearly shows the fridge not gfci protected and on 1 of the 2 small appliance circuits. (The Exhibit is 2 drawings of methods that can be used for the required 2ea 20 Amp small appliance circuits in the 2014 NEC hand book).
Comment: I prefer a dedicated breaker for the fridge.  Reason is, if someone trips the breaker with a coffee maker, they may not (know how to) reset it right away and may not see it as urgent, being unaware the fridge is also on it.  NEC authors are out to stop house fire and electrocutions, spoiled food is not on their radar. Worst case, someone resets the breaker after a time, fridge re-chills, and someone eats spoiled food unaware.
Comment: "Exhibit"? What's that?
Comment: A picture in the 2014 NEC handbook pg 82. showing different wiring options.
Comment: Thanks. Might be worth clarifying that in your answer. DIY site, after all. :)

GFCI Outlet or Breaker


What does Frostbite do?

Question: I recently acquired the Irithyll Straight Sword and see that it does Frost damage. When fighting a boss, I noticed that eventually gave me Frostbite, though I have no idea what Frostbite actually does. Checking the wikis has been inconclusive, mentioning that maybe it hinders stamina regen.
What does Frostbite do? If it only slows Stamina regen, does it even matter in PVE?
Comment: I may have imagined it, but my movement seemed slower while frostbitten in the boss fight.
Answer: What frostbite does is it fills up a bar. Once that bar is full, it does significantly damage to health, and stamina regen will decrease
Comment: @twobugs most likely the same unless they have an immunity to it such as frost creatures such as the frost knight or vordt
Comment: This when the status effect is inflicted on a player, right? Do you have any information about how it works on non-player enemies?
Answer: It works similar to bleed, but instead of doing an insane amount of HP damage, it splits between HP and Stamina damage, reduces your stamina regen and slows your movement. Vordt has an AoE Frostbite 'aura' and the smaller Irithyll knights you find through the game also deal frostbite damage with the weapons you receive by defeating them. It's also good to note that like bleed, some bosses have a higher resistance (and those like Vordt) or complete resistance to Frostbite.

What does Frostbite do?


Application navigation when there are multiple main navigation possibilities?

Question: What's the best way to present main navigation for a site where you login and have access to two products, that have some different navigation.
3 navigations:
1) External page, about us, products etc..
-- Login In ----
2) Product 1 navigation... clients, service, product-1 specific link 1, P1-SL 2
3) Product 2 navigation... clients, service, product-2 specific link 1, P2-SL 2
Some users may only have access to product 1, some only product 2, some both 1 & 2.
Separate sub-dashboards or views? two rows? I think blending all the navigation for product 1 and 2 (and eventually 3,4) will get too long.
Solution should be mobile/responsive friendly.
Answer: The Google Chrome Developers site is one great example of this. This site is for developers who want to create apps or extensions for devices using Google Chrome. It has a top navigation with all the different major APIs available (Chrome Apps, Chrome Extensions, etc.), and a left sided nav that acts as the main nav for the currently selected product.


DateTime.UtcNow gives different value in different server

Question: I have a dll that logs datetime in UTC using this code i.e. `DateTime.UtcNow() I am running a console application which uses this dll in two different servers. One server is in 'Easter Timezone' and the other is in 'Pacific Timezone'. Now when i launch the console application, i keep getting two different times.
e.g.
In Easter  Timezone: 11/18/2014 10:14:40 PM
In Pacific Timezone: 11/18/2014 10:13:26 PM
Difference: 1:14
I launched the console application in the server that was running in EST first. And the time difference between launching two console applications in two servers was just couple seconds. Does anyone know why there is so much difference in timezone (UTC) while running the same code in two different servers?
Thanks.
Sanjeev
Comment: 1 minute 14 seconds?  Sounds like one of your servers isn't getting a properly synced time.  `UtcNow()` uses the local clock and timezone settings, so make sure the local clock is set correctly
Comment: Sounds like you want to sync both servers to the Naval Observatory time clock, and then run your application.
Answer: The system clock on both servers could be slightly different.
From the spec (emphasis added):

Gets a DateTime object that is set to the current date and time on this
computer, expressed as the Coordinated Universal Time (UTC).

http://msdn.microsoft.com/en-us/library/system.datetime.utcnow(v=vs.110).aspx
Comment: is there anyway to get utctime computer independent?
Comment: @sanjeev40084: You can ask a single server somewhere, and hope that it doesn't lie and that the network is fast.  This is a hard problem; read about distributed systems development.
Comment: Windows should be able to sync with a time server.  What version of windows are you running?
Comment: depending on the server security policy, it could be that the time sync functionality is blocked or disabled - in which case you might need to sync the servers yourself.
Comment: It's running on Windows 2003 server.  I think running the UTC code in third server and getting the timezone calling from that server on other two servers might be the better options.
Comment: @sanjeev40084 could latency affect that? The time taken for the request to be received and the response received by the application? What is the tolerance for latency?
Comment: @sanjeev40084 This could be useful to you: http://serverfault.com/questions/13253/how-to-synchronize-the-clock-of-a-windows-server-2003-domain-server
Comment: You guys were right. The server that was running in EST was 1 min couple seconds ahead than actual EST. I fixed the time and that took care of it :) Thanks to you all.
Comment: @sanjeev40084 if it was the cause, please mark as answer.


PHP PDO error with params

Question: I want that admins can update rights for users, because admins can also add more rights I need to  get the row from a $_GET and put it in the query;
        if(isset($_GET['flip'], $_GET['userid'],$_GET['newval'])) {
            switch($_GET['newval']) {
               case 1:
                    $upd = $db->prepare("
                        UPDATE premissions
                        SET ? = '1'
                        WHERE userId = ?
                    ");
                    break;
               case 0:
               default:
                     $upd = $db->prepare("
                        UPDATE premissions
                        SET ? = '0'
                        WHERE userId = ?
                    ");
                    break;
            }

            $upd->execute(array($_GET['flip'], $_GET['userid']));
        }

But now I get this error message:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near '? = '1' WHERE
  userId = ?' at line 2'

I understand that something is wrong with the syntax but I don`t know how to fix it.
Answer: You cannot use ? to bind column names (or table names) with PDO. The ? is reseved for binding to variables in the right side of the assignment.
UPDATE premissions SET ? = '0'

Is therefore not possible. You could do something like this:
if(isset($_GET['flip'], $_GET['userid'],$_GET['newval']))
{
  switch($_GET['flip'])
  {
     case 'column1': $column = 'column1';        break;
     case default  : $column = 'default_column'; break;
  }
  $upd = $db->prepare("UPDATE premissions
                       SET {$column} = ?
                       WHERE userId = ?");
  $upd->execute(array($_GET['newval'],
                      $_GET['userid']));
}

What is important here is that the value of $column can never be something else than what is specified, namely either 'column1' or 'default_column', no matter what the input is. So you're not vulnerable to SQL injection. I would advice to check the other URL parameters as well, if only to prevent unexpected errors. You could for instance add:
is_numeric($_GET['userid'])

as a test before you accept the value of $_GET['userid'].
Comment: you should give OP the alternative possiblitly
Comment: @meda, you're right, I will, one moment please.
Answer: You can only use the '?' for values not column or table names. What you can do in this case is create an array of columns for that table and then use the in_array() function to validate a column name then enter in the query directly
Example:
$columnNames = array('id', 'username', 'name', 'address', 'zipcode');
if (!in_array($_GET['flip'], $columnNames))
{
    // Not a valid column don't bother preparing a statement
}
else
{
    $column = $_GET['flip'];
    $upd = $db->prepare("
                    UPDATE premissions
                    SET {$column} = '1'
                    WHERE userId = ?
}

PHP PDO error with params


How many outlets can a 20amp breaker have?

Question: Using 12-2 and installing all new outlets, wire, and breaker.
Comment: What are the outlets for?  Can only use up to 20 amps, so possible to use 100 outlets for low power LED lights.  A single double outlet is  pushing it if plugging in a kettle and toaster at the same time.
Answer: Generally speaking, no limit in the NEC, though other restrictions may come into play. For example, bathroom circuits are limited to bathrooms and kitchen circuits are limited to kitchens (and certain related areas). But for general purpose circuits (living room, bedrooms, etc.) there is no set limit.
However, there are some jurisdictions with specific limits. For example, Canada has a limit of 16 or 20 - see this article for details.


Pinterest like ajax loading

Question: I am working on a website with Wordpress where posts are to be loaded with AJAX while changing the url to the actual permalink of the post. Like how pinterest works. The AJAX loaded content is displayed in a modal box. I use
window.history.pushState(stateObj, title, url) to change the url of the browser to the post's permalink. Now my problem is:
When the modal box closes, I want to go to the previous url without reloading the page.
e.g. I am on the homepage (http://example.com), then i click a post, modal box opens with the post content fetch through AJAX and the url become (http://example.com/post1). When the modal box closes, I would like the url to go back to (http://example.com) without actual page reload. So basically only to the previous state.
Answer: So use same way of changing url like on open but trigger it on close event of modal window.
EDIT: To go to the root url you can do window.history.pushState('', '', '/')
Comment: Tried this way, (on close event):

window.history.pushState('', '', '');

since i want to go to http://example.com from http://example.com/post1

But that does not affect the url since it only means there is nothing to concatenate to the url.
Comment: If I want to go to http://example.com/post1 from http://example.com/someotherpage, how can i achieve that?
Comment: window.history.pushState('', '', '/post1') generally from where you are going doesn't matter

Pinterest like ajax loading


lxappearance changes not sticking

Question: Just installed 13.04, in xmonad, want to change my gtk theme. Run lxappearance, click on ambiance, everything changes in lxapperance, it all looks good. Hit apply. No change to any other app. Close lxappearance and reopen it -- theme reverted back to Raleigh. >.<
Answer: Try a small program called gtk-chtheme from synaptic or software centre, I use this on all desktops to quickly change my gtk theme and font...
Comment: That worked for changing the theme to Ambiance, but it doesn't seem to be able to modify the icon set like lxapperance? Is there a way to do that with some other program or manually?
Comment: Nvm, got it. Just added `gtk-icon-theme-name = "unity-icon-theme"` to my `~/.gtkrc-2.0`.

lxappearance changes not sticking


How clock synchronization affects the performance of YugabyteDB

Question: [Question posted by a user on YugabyteDB Community Slack]
I would like to examine how the accuracy of clock synchronization affects the performance of YugabyteDB. How do you usually test such things internally?
Answer: To answer your question, we use Jepsen tests to verify correctness, which introduces clock skew issues (as a part of a larger set of failures it introduces).
This report is old, but it explains the point: https://blog.yugabyte.com/yugabyte-db-1-2-passes-jepsen-testing/ (see "Pushing the boundary on tolerating clock skew")

YugabyteDB uses a combination of the monotonic and the HLC to make
sure it is much more resilient to clock skew. Note that the
—max_clock_skew_usec config flag controls the maximum clock skew
allowed between any two nodes in the cluster and has a default value
of 50ms. Kyle calls this out in his report (emphasis is mine in these
quotes): YugabyteDB uses Raft, which ensures linearizability for all
(write) operations which go through Raft's log. For performance
reasons, YugabyteDB reads return the local state from any Raft leader
immediately, using leader leases to ensure safety. Using
CLOCK_MONOTONIC for leases (instead of CLOCK_REALTIME) insulates
YugabyteDB from some classes of clock error, such as leap seconds.
Between shards, YugabyteDB uses a complex scheme involving Hybrid
Logical Clocks (HLCs). Yugabyte couples those clocks to the Raft log,
writing HLC timestamps to log entries, and using those timestamps to
advance the HLC on new leaders. This technique eliminates several
places where poorly synchronized clocks could allow consistency
violations.


How to stop Steam from installing itself to other users?

Question: I installed Steam and I want it to be installed only on my account. Everytime when someone else logs in, Steam tries to update itself to complete the installation for that user. I don't want to do that for every user becouse the update is really big and I have limited HDD space, so is it possible to stop Steam doing that?
Comment: Could you add more information to the question? Some simple things like your Cron, Startup, Steam install details, etc.?
Comment: I've installed on a vanilla Ubuntu 14.10 the normal Steam from the page and the problem has appeared on a second user (the popup looks similar to the dropbox install-one, I can send a screenshot if it helps)
Answer: When a user logs in, Steam should not automatically open. It's likely that Steam is still set to open in their Startup Applications. Disabling it there should prevent it from starting when a user logs in.
Comment: It's not listed in the startup apps (any obvious places) and this still happens. It appears as though Steam has some kind global hook for login.
Comment: Well this is strange because I have steam installed and this never happens. 14.10. Could I get more details on the question?


zsh configuration in tmux

Question: I am using tmux and zsh.
When I am outside tmux, zsh is customized with some Manjaro settings, as per the .zshrc
# Use powerline
USE_POWERLINE="true"
# Source manjaro-zsh-configuration
if [[ -e /usr/share/zsh/manjaro-zsh-config ]]; then
  source /usr/share/zsh/manjaro-zsh-config
fi
# Use manjaro zsh prompt
if [[ -e /usr/share/zsh/manjaro-zsh-prompt ]]; then
  source /usr/share/zsh/manjaro-zsh-prompt
fi

# Use ssh-agent
if [[ -e /home/marcosh/ssh-agent.zsh ]]; then
  source /home/marcosh/ssh-agent.zsh
fi

source /usr/share/nvm/init-nvm.sh

When I am inside tmux though, the customizations are missing, eventhough it is using zsh. This is my .tmux.conf
set-option -g history-limit 50000

# sane scrolling
set-option -g mouse on
set -ga terminal-overrides ',xterm*:smcup@:rmcup@'

# new pane on same folder
bind '"' split-window    -c "#{pane_current_path}"
bind %   split-window -h -c "#{pane_current_path}"

# use zsh instead of bash
set -g default-command /usr/bin/zsh

What should I do to get the same zsh configuration both when inside and outside tmux?
Answer: The problem is tmux is not rendering the UTF-8 characters from the manjaro config properly.
To solve this use:
tmux -u
From the tmux manpage:
-u            Write UTF-8 output to the terminal even if the first
              environment variable of LC_ALL, LC_CTYPE, or LANG that
              is set does not contain "UTF-8" or "UTF8".  This is
              equivalent to -T UTF-8.

Comment: Lifesaver. Works for me.

zsh configuration in tmux


Disable xscreensaver when watching Kodi video?

Question: Is there any way of disabling xscreensaver when a video is being played back in Kodi (17.6). I'm running Ubuntu 17.10.
I've seen proposed workarounds for Flash or Youtube video playback, but nothing for Kodi
???
Comment: GNOME? Then see [this](https://askubuntu.com/questions/969398/prevent-lock-is-not-working-in-ubuntu-17-10-while-watching-youtube-videos).
Comment: Thanks for the link. It looks as if the Gnome Tweak Tool and Caffeine offer some options for disabling the screensaver, but neither is smart enough to detect whether you are watching a video and disable the screensaver if you are (as Windows does, for example). Caffeine can spot whether you're running a full-screen app (e.g. Kodi), but not whether a video is playing. It seems that you can set rules for when to disable the screensaver, but they're not smart enough to work out when you're actually watching a video.
Answer: kodi-prevent-xscreensaver
keeps XScreenSaver from coming on when Kodi is active. This bash script is infinitely more lightweight than some alternatives such as caffeine.
git clone https://github.com/graysky2/kodi-prevent-xscreensaver
sudo make
sudo make install

kodi-prevent-xscreensaver

and add it to ~/.config/autostart to add it to start-up application list
but this prevents it any time Kodi is running, not only when it is at full screen.
Comment: `sudo` should be generally not needed when calling `make` without parameters.


Need help with the proof of the following theorem

Question: Theorem: If $ord_{m}a=t$, then $ord_{m}a^n=t/(n,t)$
Proof: Let $(n,t)=d$. Then since $a^t \equiv 1(mod\text{ } m)$, we have
$$(a^t)^{n/d}=(a^n)^{t/d} \equiv 1(mod\text{ } m)$$,
so that if $ord_{m}a^n = t'$, then $$t'|t/d$$
But from the congruence  $$(a^n)^t{'} \equiv 1(mod \text{ } m)$$
We have $t|nt'$ by theorem 4-3, or
$$t/d|{n/d}t'$$
Since
$$(t/d,n/d)=1$$
we obtain $$t/d|t'$$
Combining $t'|t/d$ and $t/d|t'$ we have $t'=t/d$
why do we need n/d in the first statement and how does that show $t'|t/d$
Comment: See http://archive.org/details/NumberTheory_862  @Page#95. See also : http://math.stackexchange.com/questions/1815832/find-all-the-primitive-roots-of-13
Answer: The argument is essentiallyas follows (reorganized and presented bidirectionally)
$$ a^{nk}\equiv 1\iff t\mid nk\iff t\mid nk,tk\iff t\mid(nk,tk)=(n,t)k\iff t/(n,t)\mid k$$
The first $\iff$ follows because $\,t = {\rm\ ord}\, a,\,$ and the third follows by the definition/universal property of the gcd and the gcd distributive law. You could also use lcm instead of gcd, i.e.
$\quad\ \ a^{nk}\equiv 1\iff t\mid nk\iff n,t\mid nk\iff [n,t]\mid nk\iff [n,t]/n\mid k$
Both are equivalent since $\ [n,t]/n = t/(n,t),\ $ i.e. $\ [n,t](n,t) = nt$.
Remark $\ $ Note that the first equivalence chain implies that $\,a^n\,$ has order $\,t/(n,t)\,$ since, generally, if $\  b^k = 1\iff j\mid k\ $ then this implies that $\,b\,$ has order $\,j.\,$ Indeed, setting $\,k=j\,$ implies $\,b^j=1\,$ and $\,j\,$ is the least postive $\,k\,$ with $\,b^k=1\,$ since $\,j\,$ divides all other such $\,k.\ $
Comment: Hi Bill Dubuque, I don't know why, but most of the times, it's so hard for me to follow your arguments. I still lack a lot of math background. I am just wondering why the $gcd(t/d,n/d)=1$
Comment: If $\,c>1\,$ and  $\,c\mid t/d,n/d\,$ then $\,cd\mid t,n,\,$ contra $\,d = (t,n)=\,$ *greatest* common divisor of $\,t,n.\, $ See [this answer.](http://math.stackexchange.com/a/1213466/242)You are quite welcome to ask questions about things you find hard to follow.
Comment: Thanks, I think you are using new notation because in mine $ord_m{a^n}=t'$. In yours, it is t. what is $t|nk,tk$?, are u saying that $t$ divides $nk$ and$ tk$?
Comment: No, same notation. The proof above shows that $\,a^{n\,k}=1\iff t_1\mid k,\,$ for $\,t_1 = t/(n,k).\,$ This implies $\,t_1 = {\rm ord}\, a^{n}\, (=: t')$ since for $\,k=t'$ it implies $\,t_1\mid t'.\,$ Conversely for $\,k=t_1\,$ it implies $\,(a^n)^{t_1} = 1\,$ so $\,t'\mid t_1.\,$ Thus $\,t_1\mid t'\mid t_1\,$ so $\,t' = t_1.\ $ That $\iff$ is a very handy characterization of "order".
Comment: @TheMathNoob Some of your difficulties may be from proceeding too fast. Be sure you have properly understood things before moving forward.


Shallow & Deep Binding - What would this program print?

Question: I'm not sure how to do this...
<code>function f1()
{
    var x = 10;
    function f2(fx)
    {
        var x;
        x = 6;
        fx();
    };

    function f3()
    {
        print x;
    };

    f2(f3);
};
</code>
For each of the following two binding methods, what would the program print?
A)  Shallow Binding
B)  Deep Binding
Thanks for the help!
Comment: see [here](http://stackoverflow.com/questions/1753186/dynamic-scoping-deep-binding-vs-shallow-binding).

in a nutshell: deep binding prints `10` as the binding of `x` takes place when `f2` is called, shallow binding prints `6` as `x` is bound when `f3` (being a procedure parameter to `f2`) is called from `f2`.
Answer: Deep/shallow binding makes sense only when a procedure can be passed as an argument to a function.

Deep binding binds the environment at the time a procedure is passed
as an argument.
Shallow binding binds the environment at the time a
procedure is actually called.

Deep binding.
Here f3() gets the environment of f1() and prints the value of x as 10 which is local variable of f1().
Shallow binding.
f3() is called in f2() and hence gets the environment of f2() and prints the value of x as 6 which is local to f2()
Answer: • The environment of the call statement that enacts the passed subprogram
(shallow binding)
• The environment of the definition of the passed subprogram (deep
binding).
In some cases, the subprogram that declares a subprogram also passes that
subprogram as a parameter. In those cases, deep binding and ad hoc binding
are the same.
Answer: Shallow binding : the environment of call statement that enacts the passed subprogram
Deep binding : the environment of the definition of the passed subprogram
Ad hoc binding : the environment of call statement that passed the subproblem as an actual parameter


How can I extract the Fonts used in a PDF file via PDFSharp?

Question: I am trying to extract the fonts used in a PDF document via PDFSharp (http://www.pdfsharp.net/).
Unfortunately I am not able to do so since I keep on getting strange results and I don't know how to interpret them. In the assembly I have seen classes like PdfFontTable etc, but they are all internal. When decompiling the PdfResources class again everything related to Fonts is internal.

I have tried to access the Resources to get the fonts as:
var reader = Reader.Open(stream, PdfDocumentOpenMode.InformationOnly);
foreach (var page in reader.Pages)
{
    var resources = page.Resources;
    var fonts = resources.Elements.GetValue("/Font");
}

But that gives me an incomprehensible response:

Is there a way to extract the list of fonts used just like I see them in Adobe Acrobat Reader?
Answer: There is no direct API way to query the fonts. But it is possible to query the internal document data structures. The following code works and returns a list with fonts.
List<string> fonts = new List<string>();
PdfDocument pdfDoc = PdfReader.Open("YourFileName.pdf");
foreach (PdfObject obj in pdfDoc.Internals.GetAllObjects())
{
    if ("dictionary" == obj.Internals.TypeID)
    {
        for (int i = 0; i < ((PdfDictionary)obj).Elements.Count; ++i)
        {
            if (((PdfDictionary)obj).Elements.ContainsKey("/BaseFont"))
            {
                PdfItem item = ((PdfDictionary)obj).Elements.GetValue("/BaseFont");
                string fontname = item.ToString();
                int idx = fontname.IndexOf('+');
                if (idx > 0)
                {
                    fontname = fontname.Substring(idx + 1).Trim();
                    if (!fonts.Contains(fontname))
                        fonts.Add(fontname);
                }
            }
        }
    }
}

Answer: Eventually I managed to get it to work by registering an IEventListener and handling the TextRenderInfo.
public class FontReader : IEventListener
{
    private ICollection<FontData> _fonts;

    ///
    ///     Gets all fonts used in a PdfDocument.
    ///
    public ICollection<FontData> GetFonts(PdfDocument document)
    {
        _fonts = new List<FontData>();
        var processor = new PdfCanvasProcessor(this);
        for (var i = 1; i <= document.GetNumberOfPages(); i++)
        {
            var page = document.GetPage(i);
            processor.ProcessPageContent(page);
        }

        return _fonts;
    }

    public void EventOccurred(IEventData data, EventType type)
    {
       if (!(data is TextRenderInfo)) return;

       var font = ((TextRenderInfo)data).GetFont();
       var name = font.GetFontProgram().GetFontNames().GetFontName();
       var type = font.GetPdfObject().GetAsName(PdfName.Subtype).GetValue();
       ...
       _fonts.Add(...);
    }
}


Speech Kit limits: how do I know that I've reached them?

Question: I'm using speech recognition in my app. It's guite important for user experience, so I want it to be good (and free or cheap).
Right now, I'm using Speech Kit from Apple, and it works like a charm but it's not very reliable because there are some limits per app and per device, and I don't know these limits.
Another option is to use OpenEars. It's not nearly as good as Speech Kit for me, so I'm thinking about switching from Speech Kit to OpenEars silently if Speech Kit is not working (and back,when Speech Kit is alive and well).
But is there a way to know that Speech Kit is not working right now before ever using it?
The only way I know of is to try to recognise some audiofile before every user session, but it needs time (at least, several seconds will be spent, and several seconds is a lot), and it's not very good solution in terms of using the service — it seems too costly to recognise audio just to check if Speech Kit is working or not. Also, I don't know how to debug this, because obviously I don't have any problems with limits in my app right now.
What is the best way to solve this?
Answer: I also thought about this question not long ago. Here's an answer from the Apple Q & A. "The current rate limit for the number of SFSpeechRecognitionRequest calls a device can make is 1000 requests per hour." There is also an example of the error being received upon reached limit, so you can prepare yourself for that :)
Here's the link: Apple Q & A


How to redirect traffic that comes from certain domains, to a new url

Question: I need to redirect traffic for all the visitors coming from a bunch of domains, but they all have the same page.
So all referrers like this:
hxxp://domain1.com/search.php
hxxp://domain2.com/search.php
hxxp://domain3.com/search.php

So when these visitors come to my page, they will be redirected through another url, however all other referring visitors will go to the site.
Ideas?
Answer: In your .htaccess file, assuming YourNewDestination.com is the desired destination:
RewriteEngine on
RewriteCond %{HTTP_REFERER} /search\.php$ [NC]
RewriteRule ^(.*)$ http://YourNewDestination.com

Comment: Lovely bud!  QUESTION--> Is there a way to simply redirect any domain that has the page "search.php" ?  All referring domains that I want directed actually have that same page.  (:
Comment: so wed be redirecting funny.com/search.php , dogs.com/search.php,
Comment: See edited answer. Now it just looks to see that the referrer is a string that ends in "/search.php". Please accept answer if it is correct. Thanks.
Comment: hm, no.  I place the code in htaccess on this site http://bit.ly/1YODqaM and  placed a different url in the "yournewdestination.com".  Then I sent traffic.  No traffic was redirected to the "newdestination.com".  So then I created a link to test, on another domain.com/search.php, it takes me to the main site, but since its referring from search.php, it should be taking me to the "newdestination.com".  Ideas?
Comment: You should look at http://httpd.apache.org/docs/current/mod/mod_rewrite.html for the full discussion of this.


boot very slowly after upgrade ubuntu 18.04

Question: from dmesg log, it seems that XFS loading takes much time. but I do not know where is the problem and how to fix it.
[    1.595606] usb 1-12: New USB device found, idVendor=03f0, idProduct=334a
[    1.595607] usb 1-12: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[    1.595608] usb 1-12: Product: HP Business Slim Keyboard
[    1.595609] usb 1-12: Manufacturer: Chicony
[    1.639808] nvidia 0000:65:00.0: enabling device (0140 -> 0143)
[    1.639870] nvidia 0000:65:00.0: vgaarb: changed VGA decodes: olddecodes=io+mem,decodes=none:owns=none
[    1.739597] NVRM: loading NVIDIA UNIX x86_64 Kernel Module  410.79  Thu Nov 15 10:41:04 CST 2018 (using threaded interrupts)
[    1.760998] hidraw: raw HID events driver (C) Jiri Kosina
[    1.761668] nvidia-modeset: Loading NVIDIA Kernel Mode Setting Driver for UNIX platforms  410.79  Thu Nov 15 10:39:32 CST 2018
[    1.762317] [drm] [nvidia-drm] [GPU ID 0x00001700] Loading driver
[    1.762319] [drm] Initialized nvidia-drm 0.0.0 20160202 for 0000:17:00.0 on minor 0
[    1.762396] [drm] [nvidia-drm] [GPU ID 0x00006500] Loading driver
[    1.762397] [drm] Initialized nvidia-drm 0.0.0 20160202 for 0000:65:00.0 on minor 1
[    1.772657] scsi host0: ahci
[    1.772738] scsi host1: ahci
[    1.772806] scsi host2: ahci
[    1.772869] scsi host3: ahci
[    1.773630] scsi host4: ahci
[    1.773707] scsi host5: ahci
[    1.773771] scsi host6: ahci
[    1.773830] scsi host7: ahci
[    1.773849] ata1: DUMMY
[    1.773849] ata2: DUMMY
[    1.773852] ata3: SATA max UDMA/133 abar m2048@0x9e226000 port 0x9e226200 irq 39
[    1.773856] ata4: SATA max UDMA/133 abar m2048@0x9e226000 port 0x9e226280 irq 39
[    1.773861] ata5: SATA max UDMA/133 abar m2048@0x9e226000 port 0x9e226300 irq 39
[    1.773865] ata6: SATA max UDMA/133 abar m2048@0x9e226000 port 0x9e226380 irq 39
[    1.773866] ata7: SATA max UDMA/133 abar m2048@0x9e226000 port 0x9e226400 irq 39
[    1.773868] ata8: SATA max UDMA/133 abar m2048@0x9e226000 port 0x9e226480 irq 39
[    1.774063] i801_smbus 0000:00:1f.4: SPD Write Disable is set
[    1.774106] i801_smbus 0000:00:1f.4: SMBus using PCI interrupt
[    1.776114] usbcore: registered new interface driver usbhid
[    1.776114] usbhid: USB HID core driver
[    1.777066] e1000e 0000:00:1f.6: Interrupt Throttling Rate (ints/sec) set to dynamic conservative mode
[    1.778169] logitech-djreceiver 0003:046D:C52B.0003: hiddev0,hidraw0: USB HID v1.11 Device [Logitech USB Receiver] on usb-0000:00:14.0-5/input2
[    1.778249] input: Chicony HP Business Slim Keyboard as /devices/pci0000:00/0000:00:14.0/usb1/1-12/1-12:1.0/0003:03F0:334A.0004/input/input3
[    1.788126] tsc: Refined TSC clocksource calibration: 3599.999 MHz
[    1.788133] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x33e4525366a, max_idle_ns: 440795257657 ns
[    1.836302] hid-generic 0003:03F0:334A.0004: input,hidraw1: USB HID v1.10 Keyboard [Chicony HP Business Slim Keyboard] on usb-0000:00:14.0-12/input0
[    1.836592] input: Chicony HP Business Slim Keyboard as /devices/pci0000:00/0000:00:14.0/usb1/1-12/1-12:1.1/0003:03F0:334A.0005/input/input4
[    1.852367] e1000e 0000:00:1f.6 0000:00:1f.6 (uninitialized): registered PHC clock
[    1.896249] hid-generic 0003:03F0:334A.0005: input,hiddev1,hidraw2: USB HID v1.10 Device [Chicony HP Business Slim Keyboard] on usb-0000:00:14.0-12/input1
[    1.917322] e1000e 0000:00:1f.6 eth0: (PCI Express:2.5GT/s:Width x1) 0c:c4:7a:e7:cd:b7
[    1.917324] e1000e 0000:00:1f.6 eth0: Intel(R) PRO/1000 Network Connection
[    1.917425] e1000e 0000:00:1f.6 eth0: MAC: 12, PHY: 12, PBA No: 0100FF-0FF
[    1.918020] e1000e 0000:00:1f.6 rename3: renamed from eth0
[    2.086668] ata5: SATA link down (SStatus 0 SControl 300)
[    2.086783] ata3: SATA link up 6.0 Gbps (SStatus 133 SControl 300)
[    2.087535] ata3.00: supports DRM functions and may not be fully accessible
[    2.087559] ata3.00: ATA-10: CT500MX500SSD1, M3CR010, max UDMA/133
[    2.087560] ata3.00: 976773168 sectors, multi 1: LBA48 NCQ (depth 31/32), AA
[    2.087885] ata4: SATA link up 6.0 Gbps (SStatus 133 SControl 300)
[    2.087963] ata6: SATA link down (SStatus 0 SControl 300)
[    2.088156] ata3.00: supports DRM functions and may not be fully accessible
[    2.088665] ata3.00: configured for UDMA/133
[    2.088892] scsi 2:0:0:0: Direct-Access     ATA      CT500MX500SSD1   010  PQ: 0 ANSI: 5
[    2.089103] sd 2:0:0:0: Attached scsi generic sg0 type 0
[    2.089119] sd 2:0:0:0: [sda] 976773168 512-byte logical blocks: (500 GB/466 GiB)
[    2.089120] sd 2:0:0:0: [sda] 4096-byte physical blocks
[    2.089124] sd 2:0:0:0: [sda] Write Protect is off
[    2.089125] sd 2:0:0:0: [sda] Mode Sense: 00 3a 00 00
[    2.089131] sd 2:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[    2.089366]  sda: sda1
[    2.089746] sd 2:0:0:0: [sda] supports TCG Opal
[    2.089747] sd 2:0:0:0: [sda] Attached SCSI disk
[    2.090808] ata8: SATA link up 1.5 Gbps (SStatus 113 SControl 300)
[    2.091866] ata7: SATA link down (SStatus 0 SControl 300)
[    2.094081] ata8.00: ATAPI: ATAPI   iHAS324   F, CL8N, max UDMA/133
[    2.094977] ata8.00: configured for UDMA/133
[    2.231563] ata4.00: ATA-8: TOSHIBA MG04ACA400E, FP3B, max UDMA/100
[    2.231564] ata4.00: 7814037168 sectors, multi 16: LBA48 NCQ (depth 31/32), AA
[    2.232837] ata4.00: configured for UDMA/100
[    2.233159] scsi 3:0:0:0: Direct-Access     ATA      TOSHIBA MG04ACA4 FP3B PQ: 0 ANSI: 5
[    2.233368] sd 3:0:0:0: [sdb] 7814037168 512-byte logical blocks: (4.00 TB/3.64 TiB)
[    2.233369] sd 3:0:0:0: [sdb] 4096-byte physical blocks
[    2.233375] sd 3:0:0:0: [sdb] Write Protect is off
[    2.233376] sd 3:0:0:0: [sdb] Mode Sense: 00 3a 00 00
[    2.233384] sd 3:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[    2.233389] sd 3:0:0:0: Attached scsi generic sg1 type 0
[    2.238240] scsi 7:0:0:0: CD-ROM            ATAPI    iHAS324   F      CL8N PQ: 0 ANSI: 5
[    2.309568] sr 7:0:0:0: [sr0] scsi3-mmc drive: 48x/48x writer cd/rw xa/form2 cdda tray
[    2.309569] cdrom: Uniform CD-ROM driver Revision: 3.20
[    2.309699] sr 7:0:0:0: Attached scsi CD-ROM sr0
[    2.309769] sr 7:0:0:0: Attached scsi generic sg2 type 5
[    2.476687]  sdb: sdb1
[    2.476946] sd 3:0:0:0: [sdb] Attached SCSI disk
[    2.614163] random: fast init done
[    2.812310] clocksource: Switched to clocksource tsc
[    2.909946] input: Logitech Wireless Mouse as /devices/pci0000:00/0000:00:14.0/usb1/1-5/1-5:1.2/0003:046D:C52B.0003/0003:046D:4055.0006/input/input5
[    2.910022] random: systemd-udevd: uninitialized urandom read (16 bytes read)
[    2.910047] random: systemd-udevd: uninitialized urandom read (16 bytes read)
[    2.910061] random: systemd-udevd: uninitialized urandom read (16 bytes read)
[    2.910094] logitech-hidpp-device 0003:046D:4055.0006: input,hidraw3: USB HID v1.11 Mouse [Logitech Wireless Mouse] on usb-0000:00:14.0-5:1
[   92.285063] SGI XFS with ACLs, security attributes, realtime, no debug enabled
[   92.286703] XFS (sda1): Mounting V5 Filesystem
[   92.299585] XFS (sda1): Ending clean mount
[   92.385512] ip_tables: (C) 2000-2006 Netfilter Core Team
[   92.392141] systemd[1]: systemd 237 running in system mode. (+PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD -IDN2 +IDN -PCRE2 default-hierarchy=hybrid)
[   92.412734] systemd[1]: Detected architecture x86-64.
[   92.415357] systemd[1]: Set hostname to <so3>.
[   92.483938] systemd[1]: Created slice System Slice.
[   92.484019] systemd[1]: Listening on udev Control Socket.
[   92.484114] systemd[1]: Listening on Journal Audit Socket.
[   92.484153] systemd[1]: Listening on Journal Socket (/dev/log).
[   92.484288] systemd[1]: Set up automount Arbitrary Executable File Formats File System Automount Point.
[   92.484314] systemd[1]: Listening on /dev/initctl Compatibility Named Pipe.
[   92.484353] systemd[1]: Listening on Journal Socket.
[   92.498239] lp: driver loaded but no devices found
[   92.510111] ppdev: user-space parallel port driver
[   92.540172] systemd-journald[311]: Received request to flush runtime journal from PID 1
[   92.634326] Adding 2097148k swap on /swapfile.  Priority:-2 extents:1 across:2097148k SSFS
[   92.640386] nvidia-uvm: Loaded the UVM driver in 8 mode, major device number 236
[   92.640445] dca service started, version 1.12.1
[   92.643402] ioatdma: Intel(R) QuickData Technology Driver 4.00
[   92.684016] intel-lpss 0000:00:15.0: enabling device (0000 -> 0002)
[   92.717857] idma64 idma64.0: Found Intel integrated DMA 64-bit
[   92.740020] intel-lpss 0000:00:15.1: enabling device (0000 -> 0002)
[   92.740306] idma64 idma64.1: Found Intel integrated DMA 64-bit
[   92.744333] mei_me 0000:00:16.0: enabling device (0000 -> 0002)
[   92.842132] RAPL PMU: API unit is 2^-32 Joules, 3 fixed counters, 655360 ms ovfl timer
[   92.842133] RAPL PMU: hw unit of domain pp0-core 2^-14 Joules
[   92.842134] RAPL PMU: hw unit of domain package 2^-14 Joules
[   92.842134] RAPL PMU: hw unit of domain dram 2^-16 Joules
[   92.844806] shpchp: Standard Hot Plug PCI Controller Driver version: 0.4
[   92.855172] snd_hda_intel 0000:17:00.1: Disabling MSI
[   92.855192] snd_hda_intel 0000:17:00.1: Handle vga_switcheroo audio client
[   92.865199] snd_hda_intel 0000:65:00.1: Disabling MSI
[   92.865234] snd_hda_intel 0000:65:00.1: Handle vga_switcheroo audio client
[   92.878666] snd_hda_codec_realtek hdaudioC0D0: autoconfig for ALC1220: line_outs=3 (0x14/0x15/0x16/0x0/0x0) type:line
[   92.878668] snd_hda_codec_realtek hdaudioC0D0:    speaker_outs=0 (0x0/0x0/0x0/0x0/0x0)
[   92.878669] snd_hda_codec_realtek hdaudioC0D0:    hp_outs=1 (0x1b/0x0/0x0/0x0/0x0)
[   92.878670] snd_hda_codec_realtek hdaudioC0D0:    mono: mono_out=0x0
[   92.878671] snd_hda_codec_realtek hdaudioC0D0:    dig-out=0x1e/0x0
[   92.878671] snd_hda_codec_realtek hdaudioC0D0:    inputs:
[   92.878672] snd_hda_codec_realtek hdaudioC0D0:      Front Mic=0x19
[   92.878673] snd_hda_codec_realtek hdaudioC0D0:      Rear Mic=0x18
[   92.878674] snd_hda_codec_realtek hdaudioC0D0:      Line=0x1a
[   92.889995] input: HDA Intel PCH Front Mic as /devices/pci0000:00/0000:00:1f.3/sound/card0/input6
[   92.890037] input: HDA Intel PCH Rear Mic as /devices/pci0000:00/0000:00:1f.3/sound/card0/input7
[   92.890074] input: HDA Intel PCH Line as /devices/pci0000:00/0000:00:1f.3/sound/card0/input8
[   92.890110] input: HDA Intel PCH Line Out Front as /devices/pci0000:00/0000:00:1f.3/sound/card0/input9
[   92.890145] input: HDA Intel PCH Line Out Surround as /devices/pci0000:00/0000:00:1f.3/sound/card0/input10
[   92.890181] input: HDA Intel PCH Line Out CLFE as /devices/pci0000:00/0000:00:1f.3/sound/card0/input11
[   92.890217] input: HDA Intel PCH Front Headphone as /devices/pci0000:00/0000:00:1f.3/sound/card0/input12
[   92.937118] random: crng init done
[   92.937119] random: 7 urandom warning(s) missed due to ratelimiting
[   93.023399] AVX2 version of gcm_enc/dec engaged.
[   93.023400] AES CTR mode by8 optimization enabled
[   93.155686] resource sanity check: requesting [mem 0x000c0000-0x000fffff], which spans more than PCI Bus 0000:00 [mem 0x000c4000-0x000c7fff window]
[   93.155820] caller os_map_kernel_space.part.7+0xda/0x120 [nvidia] mapping multiple BARs
[   93.156719] EDAC MC0: Giving out device to module skx_edac controller Skylake Socket#0 IMC#0: DEV 0000:64:0a.0 (INTERRUPT)
[   93.157204] EDAC MC1: Giving out device to module skx_edac controller Skylake Socket#0 IMC#1: DEV 0000:64:0c.0 (INTERRUPT)
[   93.158757] intel_rapl: Found RAPL domain package
[   93.158760] intel_rapl: Found RAPL domain dram
[   93.158761] intel_rapl: DRAM domain energy unit 15300pj
[   93.339909] XFS (sdb1): Mounting V5 Filesystem
[   93.459949] XFS (sdb1): Ending clean mount

Postscript 1
I found the 90s delay seems to be happening at random step. following is another dmesg log after reboot.
[    2.129405] ata3.00: ATA-10: CT500MX500SSD1, M3CR010, max UDMA/133
[    2.129408] ata3.00: 976773168 sectors, multi 1: LBA48 NCQ (depth 31/32), AA
[    2.130038] ata3.00: supports DRM functions and may not be fully accessible
[    2.130560] ata3.00: configured for UDMA/133
[    2.130873] scsi 2:0:0:0: Direct-Access     ATA      CT500MX500SSD1   010  PQ: 0 ANSI: 5
[    2.131069] sd 2:0:0:0: Attached scsi generic sg0 type 0
[    2.131097] sd 2:0:0:0: [sda] 976773168 512-byte logical blocks: (500 GB/466 GiB)
[    2.131098] sd 2:0:0:0: [sda] 4096-byte physical blocks
[    2.131102] sd 2:0:0:0: [sda] Write Protect is off
[    2.131103] sd 2:0:0:0: [sda] Mode Sense: 00 3a 00 00
[    2.131109] sd 2:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[    2.131355]  sda: sda1
[    2.131703] sd 2:0:0:0: [sda] supports TCG Opal
[    2.131704] sd 2:0:0:0: [sda] Attached SCSI disk
[    2.131879] ata8.00: ATAPI: ATAPI   iHAS324   F, CL8N, max UDMA/133
[    2.132767] ata8.00: configured for UDMA/133
[    2.270514] ata4.00: ATA-8: TOSHIBA MG04ACA400E, FP3B, max UDMA/100
[    2.270517] ata4.00: 7814037168 sectors, multi 16: LBA48 NCQ (depth 31/32), AA
[    2.271786] ata4.00: configured for UDMA/100
[    2.272080] scsi 3:0:0:0: Direct-Access     ATA      TOSHIBA MG04ACA4 FP3B PQ: 0 ANSI: 5
[    2.272292] sd 3:0:0:0: [sdb] 7814037168 512-byte logical blocks: (4.00 TB/3.64 TiB)
[    2.272293] sd 3:0:0:0: [sdb] 4096-byte physical blocks
[    2.272298] sd 3:0:0:0: [sdb] Write Protect is off
[    2.272299] sd 3:0:0:0: [sdb] Mode Sense: 00 3a 00 00
[    2.272306] sd 3:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[    2.272307] sd 3:0:0:0: Attached scsi generic sg1 type 0
[    2.276699] scsi 7:0:0:0: CD-ROM            ATAPI    iHAS324   F      CL8N PQ: 0 ANSI: 5
[    2.341578] sr 7:0:0:0: [sr0] scsi3-mmc drive: 48x/48x writer cd/rw xa/form2 cdda tray
[    2.341580] cdrom: Uniform CD-ROM driver Revision: 3.20
[    2.341813] sr 7:0:0:0: Attached scsi CD-ROM sr0
[    2.341882] sr 7:0:0:0: Attached scsi generic sg2 type 5
[    2.515745]  sdb: sdb1
[    2.516041] sd 3:0:0:0: [sdb] Attached SCSI disk
[    2.622700] random: fast init done
[    2.812315] clocksource: Switched to clocksource tsc
[   92.283820] random: systemd-udevd: uninitialized urandom read (16 bytes read)
[   92.283827] random: systemd-udevd: uninitialized urandom read (16 bytes read)
[   92.284013] random: systemd-udevd: uninitialized urandom read (16 bytes read)
[   92.312310] SGI XFS with ACLs, security attributes, realtime, no debug enabled
[   92.313724] XFS (sda1): Mounting V5 Filesystem
[   92.327122] XFS (sda1): Ending clean mount
[   92.412761] ip_tables: (C) 2000-2006 Netfilter Core Team
[   92.419405] systemd[1]: systemd 237 running in system mode. (+PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD -IDN2 +IDN -PCRE2 default-hierarchy=hybrid)
[   92.436552] systemd[1]: Detected architecture x86-64.
[   92.439092] systemd[1]: Set hostname to <so3>.
[   92.525609] systemd[1]: Reached target User and Group Name Lookups.
[   92.525669] systemd[1]: Started Forward Password Requests to Wall Directory Watch.
[   92.525771] systemd[1]: Created slice System Slice.
[   92.525851] systemd[1]: Listening on Journal Audit Socket.
[   92.525856] systemd[1]: Reached target Remote File Systems.
[   92.525883] systemd[1]: Listening on /dev/initctl Compatibility Named Pipe.
[   92.525926] systemd[1]: Listening on Journal Socket (/dev/log).
[   92.543157] lp: driver loaded but no devices found
[   92.545006] ppdev: user-space parallel port driver
[   92.607847] systemd-journald[318]: Received request to flush runtime journal from PID 1
[   92.641108] nvidia-uvm: Loaded the UVM driver in 8 mode, major device number 236
[   92.673815] dca service started, version 1.12.1
[   92.674554] shpchp: Standard Hot Plug PCI Controller Driver version: 0.4
[   92.677204] ioatdma: Intel(R) QuickData Technology Driver 4.00
[   92.679547] Adding 2097148k swap on /swapfile.  Priority:-2 extents:1 across:2097148k SSFS
[   92.696021] intel-lpss 0000:00:15.0: enabling device (0000 -> 0002)
[   92.869945] idma64 idma64.0: Found Intel integrated DMA 64-bit
[   92.896030] intel-lpss 0000:00:15.1: enabling device (0000 -> 0002)
[   92.896295] idma64 idma64.1: Found Intel integrated DMA 64-bit
[   92.918134] mei_me 0000:00:16.0: enabling device (0000 -> 0002)
[   92.928247] snd_hda_intel 0000:17:00.1: Disabling MSI
[   92.928268] snd_hda_intel 0000:17:00.1: Handle vga_switcheroo audio client
[   92.928379] snd_hda_intel 0000:65:00.1: Disabling MSI
[   92.928393] snd_hda_intel 0000:65:00.1: Handle vga_switcheroo audio client
Comment: I have tried that one, but it does not help.
Comment: You should include the output of `systemd analyse-blame`. that will more that the dmesg one.
Comment: 90 second boot delay pointed me here : https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1685794 , could you please verify in your fstab that the swap file/partition is existing?
Answer: Not knowing much of your problem, this could be some bugs in ubuntu startup.
You could try:

Add some entropy
Install haveged package and see if this change anything during the boot. This package provide better entropy (random things) to the kernel during boot. You could even try this without installing the package but by just moving your mouse during the boot.

Disable video output
You could add video=SVIDEO-1:d to GRUB_CMDLINE_LINUX_DEFAULT variable in /etc/defautl/grub
Then run sudo update-grub and reboot to see if it changes something.
This just explicitly disable the composite output; You could even try with VGA or HDMI if you don't use them, one never know
Comment: I have tried install rng-tools, haveged, add video=SVIDEO-1:d to grub, but none of them works. I just tried update my motherboard BIOS and reset BIOS configure as the last hope. miraculously, it solve the problem. but I still do not know the reason.
Comment: for reference, my motherboard is SuperMicro X11SRA and I update the BIOS from 1.0 to 1.2


Background color from UIView is not changing

Question: I am working on a iOS swift app.
In a view Controller I am declaring a UIView :
@IBOutlet weak var task_color_view: UIView!

From another view controller I am getting a value for the variable color_cat:
I am checking the value for the variable and it is 9:
println ("COLOR CAT===")
println (color_cat)

Here is the console output:
COLOR CAT===
9

Then I try to change the background color from the UIView depending on the value of color_cat:
...
else if color_cat == "9" {
             self.task_color_view.backgroundColor == UIColor.cyanColor()
                                    println("ESTOY EN CAT_COLOR =9")
        }
...

The console is showing that the app detects that color_cat == "9" (then the output is shown as follows)
ESTOY EN CAT_COLOR =9

But the background color of the UIView  doesn't change to cyan.
Any help is welcome. What is wrong there....
Answer: self.task_color_view.backgroundColor == UIColor.cyanColor()
This line has two equal signs in it; comparing equality. Change it to one equal sign so it will assign the value.
self.task_color_view.backgroundColor = UIColor.cyanColor()


How do I update the status of an asset in VersionOne using the REST API

Question: How can I update the status of an asset in V1 using the Rest API?
I would assume I could do something like this using the Python SDK:
from v1pysdk import V1Meta

v1 = V1Meta()

for s in (v1.PrimaryWorkitem
          .filter("Number='D-01240'")):
  s.StoryStatus = v1.StoryStatus(134)

v1.commit()

This is at least how I understand the Python SDK examples here:
https://github.com/versionone/VersionOne.SDK.Python
However this does not change anything, even though I have the rights to change the status.
Answer: Try using:
s.Status = v1.StoryStatus(134)

According to ~/meta.v1?xsl=api.xsl#PrimaryWorkitem The attribute on PrimaryWorkitem of type StoryStatus is named Status, so I think it's just a mistaken attribute name.
What's probably happening is that you're setting a new attribute on that python object, but since StoryStatus is not one of the setters that the SDK created from the instance schema metadata, it doesn't attempt to add it to the uncommitted data collection, and thus the commit is a no-op and yields neither error nor any action.
It might be possible to fence off arbitrary attribute access on those objects so that misspelled names raise errors. I'll investigate adding that.
Answer: Try doing:
s.set(Status = v1.StoryStatus(134))


android development with scala

Question: The first thing described in the howto (http://www.assembla.com/wiki/show/scala-ide/Developing_for_Android) is this:
Step 1:  Create the ant files for your project:
<code> cd <project dir>
 android update project --target 1 --path .
</code>
which yields 'command not found'. I'm in the 'workspace/name_of_my_app/' folder.
How do I get to have the 'android' command?
Answer: You need to setup the environmental variables for andriod sdk properly.  Here is documentation for the andriod command you are trying to execute:
http://developer.android.com/guide/developing/tools/othertools.html#android
Comment: Hm.

I wrote:

javac -version

and was told i had to install openjdk-6-jdk, since sun-java6-jdk did not have javac. So I did.

After that, the android command magically just worked. I'm not much less confused than before.
Comment: I had this problem. I just had to specify the full path to the tools folder within the android sdk and the command worked fine.

android development with scala


django signal wont work after adding a save function

Question: I have a simple model like this:
class ScientificInfo(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True)
    info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True)
    info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True)
    is_interviewed = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if self.info1:
            self.is_interviewed = 'True'
            super(ScientificInfo, self).save(*args, **kwargs)

Every time a user is added to the app, a ScientificInfo object will be created for it using this signal:
@receiver(post_save, sender=User, dispatch_uid='save_new_user_survey')
def survey_create(sender, instance, created, **kwargs):
    user = instance
    if created:
        survey = ScientificInfo(user=user)
        survey.save()

everything worked fine until I added that save method inside my model. the method works but the signal is disabled. Can you guys help me? thanks
Comment: You only save `ScientificInfo` instances when `info1` is not blank
Comment: Move `super(ScientificInfo, self).save(*args, **kwargs)` one tab to the left.
Answer: I'm well sure that the following couldn't work at all:
        survey = ScientificInfo(user=user)
        survey.save()

Fields info1, info2, info3 haven't default values and they aren't null=True as well. Thus survey with these blank fields couldn't be saved to DB unless you fill them.
I'm not sure whether is it your problem, but if you need to fix it (I believe you do), you should add null=True to those 3 fields.


How to separate a string using separator

Question: I want to separate this string using _ as the separators
<code>{[Data1]_[Data2]_[Data3]}_{[Val1]_[Val2]}_{[ID1]_[ID2]_[ID3]}
</code>
where underscore should not be considered inside the {   }  brackets.
so when we separate the strings we should have three new data items
<code> {[Data1]_[Data2]_[Data3]}
 {[Val1]_[Val2]}
 {[ID1]_[ID2]_[ID3]}
</code>
currently I was separating using boost
<code>        std::vector<std::string> commandSplitSemiColon;
        boost::split(commandSplitSemiColon, stdstrCommand, boost::is_any_of("_"),
        boost::token_compress_on);
</code>
but how can we ignore the underscore inside the { } brackets and only consider underscore which are not inside the brackets.
Comment: If it's guaranteed that there are at most 1 nesting layer of braces some regex can. Otherwise just do it manually
Comment: Split at `}_{` instead of the underscore
Answer: A manual solution: iterate through the string and use a variable to check whether it's in the bracket or not:
<code>std::vector<std::string> strings;
std::string s = "{[Data1]_[Data2]_[Data3]}_{[Val1]_[Val2]}_{[ID1]_[ID2]_[ID3]}";
std::string token = "";
bool inBracket = false;
for (char c : s) {
    if (c == '{') {
        inBracket = true;
        token += c;
    }
    else if (c == '}') {
        inBracket = false;
        token += c;
    }
    else if (c == '_' && !inBracket) {
        strings.push_back(token);
        token = "";
    }
    else {
        token += c;
    }
}

if (!token.empty()) {
    strings.push_back(token);
}
</code>
Comment: If you change `bool inBracket` to `int inHowManyBrackets` you can handle nested brackets.
Answer: If you note the similarity between your format and conventional CSV (comma-separated value), you can search for existing solutions.
For example, on this forum: How can I read and parse CSV files in C++?. Specifically, using Boost Tokenizer with escaped_list_separator


If text is editable, how important is to show it (appearance wise) inside a text box?

Question: A new approach we adopted for one of our applications is that all our editable text such as name, a description that was once filled out to be border-less. To edit the text the users simply click on top of the text again and it becomes editable.
The border shows in these instances.

Border shows on roll over
Border shows while editing the text

My question is, will this make sense to users? Should I keep this method? Is there anything else I can do to improve this?
Comment: Just curious...why do you want to do this? It's a significant departure from convention.
Comment: @Josh Why we thought of using this approach is to reduce the amount of vertical lines. We want the interface to have a sort of word-document feel to it.
Answer: A possible solution would be to do it like JIRA does.
Normal:

While hovering over it:

When clicked on it:
Comment: Just as long as you understand this wouldn't be at all clear on a tablet since there's no "hover" to hint that it's editable. Nobody mentioned if this is HTML or not.
Comment: @Blindy for tablet, there would have to be the textbox border always visible, or the pencil, or `Edit` hint text.
Comment: Yeah, something. Again though, not sure if he's talking about tablets or not, the OP I mean.
Comment: You could keep the pencil icon there even on normal state. Then if a user clicks the icon or hovers over the area (on desktop) they would see the editable area.
Comment: This is for desktop use.
Answer: Does the user have to fill these fields before by using a classic form or is it  only an edition method? In the first case, users have a clue to understand that the completion of these field are belong to them
You can also write an explicit placeholder like
"Description :
Add a new description..."
Or, instead a border, slightly change the background color of the editable area to indicate there is something different. Interaction on roll over is still a good idea.
Comment: At the very beginning yeah a placeholder as you said will be there. But afterwards they will only see the text they added. Our assumption is that they will know that area is editable since they edited the text once before at the beginning.
Answer:
I find text fields which show no clear hint that they are editable (different static text color or font is not clear hint IMO), very annoying.
I find text fields which show edit hint when hovered moderately annoying.
I find text fields which have some pen icon or something as hint slightly annoying.
I find text fields which have some "fresh-looking" but clear hint such as underline or different solid background without border just fine.
I find text fields which traditional border slightly boring but still just fine.

I think the answer depends on what is the most common use case? If it is looking, then optimize for looking, and 2 or even 1 might be fine. If it is for a data entry, then 4 or 5 seem solid approach. If it's page which is both for looking and "integrated" updating, then 2 or 3 or some discreet version of 4 would work.
Above does not consider case where field is empty. Right placeholder text might make even option 1 bearable. But the important situation is, when user wants to edit already filled field, if that is possible.
Answer: The user needs to know if text is editable or not. He will look for interactive elements and if he can not find any, he will not use it.
If this is an application used by users a lot of time, sometimes it might be useful to introduce a new concept to increase usability. In this case: borders for editable text are a really well-established UI behaviour and I ask you, what is the trade-off for the user in terms of usability, user experience and design?
I would advice, stick with the borders or find a good alternative, which is clear to the user.


Java multidimensional array for android app

Question: I am currently doing an app that will have many exercises (for working out) which each contain 5 different strings. They are linked to workouts that are basically arrays of exercises (but more than one workout can have the same exercise and I don't want to waste memory), and then workouts are displayed in different categories (weight loss, body building, etc..).
If I was doing this in C (which is the language I usually program in) I would have the exercises to be an array of a structure called exercise, then the workout would be linked lists with each link being a pointer to the exercise, with an int for reps and an int for sets. And the workouts would be organized in an array of pointer pointing to the first element of the linked list (so a workout can be in multiple categories). Is there a way to implement something like that in java?
Answer: Working backwards from your method in c, why not have something like:
<code>class Exercise {
 private String exName;
 private int reps;
 private int sets;
</code>
And making a constructor:
<code> public Exercise(String newName, int newReps, int newSets) {
  exName = newName;
  reps = newReps;
  sets = newSeats;
</code>
That's really the only part that is different from c.
Here, all you're doing is making an Exercise object which contains the necessary information, reps and sets.
The constructor makes a new instance of the object.
Then you can just use a regular arraylist for the list of exercises and a list of workouts.
So you end up with something that you can visualize like:
<code>[[Exercise1, Exercise2, ...][Exercise1, Exercise2, ....]...]
</code>
So the outermost list is your arraylist of workouts, the inner list is your arraylist of exercises for each workout, and each exercise is a structure that contains an (optional) name, along with its list of reps and sets.
Comment: thanks for your response, is there a way to make the workout a class that has an array of Exercises? because the sets and reps have to be in the workout because it might change between workouts
Comment: In my solution, Workout would be a class.

Each instance of workout would make an arrayList of exercises, with each exercise being what I provided above.


Can't get Bootstrap-vue form validation working

Question: I am using Vue CLI and Bootstrap and am having trouble with the form validation currently when the page loads all the input fields load as invalid. I can see why this is happening because the input fields are getting a class of is-invalid. I have fixed this by passing the state prop a value of null when it is false. It does not seem like the default behavior should be to run the validation when the page loads but maybe it is. I believe I have everything set up correctly as far as structure and proper classes I followed the bootstrap-vue docs.
My Code

              Name
              <b-input
                id="form-input-name"
                class="form-inputs mb-2 mr-sm-2 mb-sm-0"
                v-model="name"
                placeholder="Name"
                required
                :state="isEmpty(this.name) ? true : null" <---- My problem is here
              >
              ...

My problem is I need 3 results from this ternary which obviously isn't possible. I need null on load to remove the error messages then false to display error on validation and true to display valid input. I have been struggling with this for days so any help with any aspect of this setup would be greatly appreciated if you want more code let me know. The submit button adds a class of was-validated which does display any error messages that are associated with empty inputs but doesn't validate the inputs.
Question
How do I validate inputs while still keeping form error messages hidden on load.
Answer: You aren't bound to just using a ternary statement in the :state prop - you can hook :state up to a computed property directly, which will achieve three things (this is similar to what is shown in the documentation):

We can have more than two conditions, breaking out of the limitations of the ternary statement.
The computed property will analyze user input on the fly, ensuring real-time validation of the form input.
Our template code will be cleaner and more readable (important).

I'm working loosely off of your example, but something like the following should solve your issue:

<template>

        Name

</template>

In the above, you would have a method that would check for your specific validation criteria (isValid, isEmpty, etc.).
Our new computed property, isNameStateEmpty, will use that method's return value, returning false for a validation failure (triggering BootstrapVue's failed validation state), true for a validation pass, or null in the event that this.name does not have a current value (examples being a fresh page load, or a user clearing the input field, making it blank).
See a working Codesandbox of this behavior here.
Because the input's v-model (v-bind:value and @change) is set to our "name" data property, every character change within the input field will reactively update our data property (this.name).
Because our isNameStateValid computed property has a dependency of this.name, it will reevaluate on every change of the this.name data property - ensuring real-time validation using BootstrapVue's validation state.
Hopefully that helps.
Comment: Thank you for your help I should have been able to figure this out but I am new to vue.js and bootstrap. I appreciate your help. I was on the wrong page on the bootstrap docs.


How to load external js in angular Universal load children

Question: I want to load an external js lib file when a specific module is loaded using loadChildren
<code> { path: 'abc',  loadChildren: () => import('./abc/abc.module').then(m => m.abcModule) },
</code>
I am using angular universal version 15
document.getElementsByTagName("script") can not be used because the document object is only available when platformBrowser is true.  This is unacceptable because this script should be loaded even when google crawler hits the site.
so how can I load this js file in the loadChildren function ?
Answer: Loading external JavaScript files in an Angular Universal application can be a bit tricky because you don't have access to the document object directly in the server-side rendering context. To load external scripts during the server-side rendering process, you need to use the TransferState service to pass data between the server and the client.
Here's an example of how you might achieve this:

In your module, create a service to handle the loading of the external script:

<code>// external-script.service.ts

import { Injectable } from '@angular/core';
import { TransferState, makeStateKey } from '@angular/platform-browser';

@Injectable({
  providedIn: 'root',
})
export class ExternalScriptService {
  private scriptLoadedKey = makeStateKey<boolean>('scriptLoaded');

  constructor(private transferState: TransferState) {}

  loadScript(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      // Check if the script is already loaded on the client side
      const scriptLoaded = this.transferState.get(this.scriptLoadedKey, false);

      if (scriptLoaded) {
        resolve();
        return;
      }

      // Load the script on the server side
      // You may need to adjust the script URL and attributes based on your needs
      const scriptElement = document.createElement('script');
      scriptElement.src = 'path/to/your/external-script.js';
      scriptElement.onload = () => {
        this.transferState.set(this.scriptLoadedKey, true);
        resolve();
      };
      scriptElement.onerror = (error: Event | string) => {
        reject(error);
      };

      document.head.appendChild(scriptElement);
    });
  }
}
</code>

In your module, use the ExternalScriptService to load the script before the module is loaded:

<code>// abc.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ExternalScriptService } from 'path-to-your/external-script.service';

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./abc/abc.module').then(m => m.AbcModule),
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  providers: [ExternalScriptService],
})
export class AbcRoutingModule {
  constructor(private externalScriptService: ExternalScriptService) {
    // Load the external script when the module is instantiated
    this.externalScriptService.loadScript().then(() => {
      console.log('External script loaded successfully');
    });
  }
}
</code>
Please note that the exact implementation might vary based on your specific requirements and the structure of your application. Make sure to adjust the script URL, attributes, and error handling according to your needs.