What is a good beginners strategy to learn the mechanics of Civilization 5?

Question: I am pretty new to Civilization 5, played no more than maybe 4 or 5 games. What is a solid strategy I can use against the AI that does not only help me to win the game but also teaches the mechanics a little? By that definition I want to avoid a strategy that says boost X to a ridiculous amount and you can overrun a single opponent before middle ages kick in. Even if it works, I guess it will not teach me anything really and misses the goal of this question.
The strategy must not be fine grained enough so that it could beat the game at highest difficulty. If it can win the game on "Prince" difficulty level I am already satisfied. If a certain setup (number of opponents, maps size, race, etc.) has proven to be especially beginners friendly, please mention that setup as well.
Edit: To clarify the question a little more I will describe my current play style. I choose a race in the beginning and say to myself - hey, I have a bonus in the area X, I should focus on X. The longer the game runs the more I realize that I have no idea how to focus on X and what areas I should ignore because they are not important. I end up clicking the options that are the most shiny, although they have no synergies with my other actions so far. This leaves me much weaker than I could be with proper planing.
That's why I am looking for a strategy that is clearly focused on a specific goal and shows which areas I should invest in to utilize this strategy.
Answer: Video Guide
I did a 4-part series walking my buddy EBongo through a sample game using the strategy I outline here.  If you'd like to see my strategy in action, check it out:

Early Game Strategy
Your starting location will probably have quite a bit of food, which will make it a good location to focus on population growth by building farms and other population increasing structures.  Then start to prioritize culture and science here.  Generally I focus on trying to get the relevant technologies to determine where Iron is located, because it's an important early-to-mid game strategic resource.
Scout with your initial unit, and try to find ruins, as well as determine how much land and what kinds of resources you have available.  If you've got close neighbors, war is likely in your future, so you may need to adopt the Honor cultural policies.  If you've got lots of land, focus on Liberty cultural policies.  If there's not a lot of land, and you've got no close neighbors, focus on Tradition.
Your second city should be built when your first city is at around population 3 - 5.  Build it in a hilly or forested region, but try also to incorporate nearby tiles that contain special resources.  Focus on building mines and production/military enhancing buildings.
When your military is weak, or new technology makes better units available,  start cranking out units until you have around 2 per border city, and then build at least 2-4 ranged or artillery units per border with another civ.  Your second city should focus almost exclusively on production, so if your military strength is good for your technology level and known nearby enemies, you may want to consider building a wonder or two.
After you get to at least about 3-5 population in both cities, found a third city.  This time, look for plains, grassland, and special resources.  Focus this city on economic and scientific output.
Beyond this point, my general strategy tends to diverge depending on what the state of the game is.  Ideally, by your third or fourth city, you've researched enough in order to be able to detect iron, and you should prioritize building a city near an iron deposit.  You can continue growing by founding new cities, so long as you keep an eye on your treasury, military, and happiness.
Mid-Game Strategy
At this point, it's time to stop and consider what the state of the game is.
WAR!  uh!  What is it good for?  Expanding your borders!
If you've got close neighbors, try to land grab between you to secure contested resources, and begin preparations for war. Your production city should have buildings that boost initial unit experience.  You may need to shift your capital to military production, or perhaps found your 4th or 5th city in a production-heavy area.
Focus your technology to research Catapults, and then build at least 2 or 3, but depending on how wide your shared borders are, you may require more.  You'll also want at least 3 or 4 of the strongest melee units you have available, and hopefully the Great General from the Honor policy tree.
When you've amassed your army, place a catapult in each of your border cities, with melee units in the hexes that face your enemy.  Then, declare war on your neighbor.  Now wait.  Do nothing until their army marches out to your territory - and then bombard them with your catapults.  They'll be damaged enough that you can pick them off with your melee units at your leisure.  When they start to beg for mercy, push into their territory and steamroll them.  Depending on how the war is going, (and your civ's happiness) you might opt for peace eventually, but in the general case you want to wipe them out and take their capital if you can.  I tend to puppet captured cities to avoid a major negative happiness hit.
Your technology focus should be primarily on better military units, but don't forget that as you conquer, you're going to need significant happiness improvement buildings.  Additionally, you can't neglect science or you'll be lost in the arms race.
Expansion - it just keeps getting bigger!
If you've got nothing but open space surrounding you, focus on expanding to take resources nearby while maintaining firm control of your happiness.  All these extra resources will give you major bonuses to production and science, but your required culture for next level will increase dramatically.  Continue to focus your cities depending on their location (either population, economy, or production), but be sure to prioritize happiness generating buildings so that you don't outgrow your ability to sustain your civilization.
Eventually, you should encounter neighbors, or your science output will dwarf your opponents and you'll be in a good position for a late game science victory.  Stay prepared for war by keeping your cities defended and your units up to date.  You can trade excess resources to your neighbors for money to fund your other projects during this phase as well.
Technology wise, prioritize techs that give you city improvements, especially bonuses to science.  You can take a small science lead and turn it into a much larger one if you spend your early science points wisely.
Camping - it's a Legitimate Strategy!
If you've got little land but no neighbors to speak of, you're probably on an island.  Prioritize becoming ocean-worthy with your technologies, and focus on Culture in the meantime.  The cultural bonuses are worth having, and you can use the fact that cultural policies are easier to gain with smaller civlizations to your advantage.  Snap up as many as you can!
If you're at a disadvantage (ie, you've got a small island whereas your opponents all have more land) - try to settle a larger island as soon as you can.  No amount of small-civ culture bonus will make up for the fact that more resources and more cities gives you a significant advantage.  If you're all on tiny islands, try to be strategic where you settle, so that you don't end up with cities that aren't really contributing anything but are draining your happiness.
Late Game Strategy
By this point, you should already have a pretty good idea about how you're planning to win.  If you've dominated several of your neighbors, continue down a military path and stomp anyone in your path.  If you've got several of the cultural trees locked down, focus on cultural victory.
If you've got a big landmass and enemies are too far away to wage war effectively, you've got some options.  Diplomacy works best if you've got a large amount of cash.  Build the United Nations, and then prior to the election, bribe all the city-states you can find.  If you can get them to be your allies, your election is a lock.  If this isn't an option, focus on science and build the spaceship.
Note that as you grow closer to victory, the AI is going to try to stop you by any means necessary.  Keep your military power up with the same mix of units - ranged siege units defended by melee units.  Be ready to fight wherever you have borders.
Conclusion
Hopefully this gives you a general strategic overview of the game.  This is not the only way to play, but I've found it to be successful not only in Civ 5, but also in several other games in the series previously.  I haven't said a single word about Wonders or Great People, for instance, but you should be able to figure out what to prioritize based on which of the strategy paths you are following.
Specialization of cities is the #1 thing I learned that took me from "intermediate" player to "advanced" player in the Civ series.  Don't build all the structures in all the cities, lest you bankrupt yourself.  Focus cities by choosing the correct tiles to found them on in order to maximize the utility of individual buildings within the city.  Also, be strategic about placing your cities so that they can benefit from resource tiles.
To maximize score, you should be aiming for a domination victory (secure all capitals), as it requires the fewest amount of tech to pull off, so you can do it relatively early in the game.  When you get good at waging war, you should be able to conquer a neighbor almost every time you hit a new technology level for your siege and melee units.
However, Civilization is a game where there's not one "right answer" - so play it the way you find the most fun!
Comment: +1: Amazing answer, thx a lot! I like how you describe what to look for and the deviations based on the surroundings. I will print it out and keep it close during my next games. I am sure that it will improve my game significantly =).
Comment: @Demento, I could go on for several more pages of the nuances of unit upgrades, city states and such, but I think this is a good starting point, at least :)
Answer: A strategy for a beginner playing on Prince, eh?  How about ye olde Cultural Victory?
It's straightforward enough... build 3 total cities.  Build enough military to defend them.  Build a bunch of wonders.  Litter the landscape with landmarks from great artists.
I recommend France for this (the bonuses are simple and not distracting).  Egypt (fast monuments) or Persia (rocking golden ages) also will work.
When things get rolling, you should get a new policy every 9 to 11 turns.  If your policies take 20 turns, you're not doing it right.
Commonly, I'll see ~500 culture from my capital and ~150 culture from my other cities.
To get landmarks, you need Great Artists.  To get Great Artists, you need artist points.  You get most of your artist points from assigning artists to work culture building slots.  You'll also get a few artist points from certain wonders.
Social Policies
Tradition
Initial pick

Bursty boost to culture (+3 in capital).  While technically less culture in the long run by itself than from Liberty (+1 per city and reduce policy costs) and Honor (+2 per city) - the capital can get multipliers to even this out.

Tier1

Aristocracy can wait until you are close to starting your first wonder.
Legalism - I typically pick this up as soon as I can to unlock the tier2 picks.  Some people like to wait so they can get free temples.  If you have fewer than 4 cities, don't worry... Monuments will be constructed automatically as you build new cities.
Oligarchy can wait until you have spare units to garrison and/or are under attack.

Tier2

Monarchy - more gold and less Unhappy.
Landed Elite - More food in capital.  This can wait if your happiness is low, or if you are about to build a settler in the capital.  Otherwise, pick it before Monarchy!

Final pick

More food everywhere!  Oligarchy normally isn't worth an early pick by itself, but this bonus makes it worth it.

Piety - it's a grab bag of picks, look it over. About half of them have culture bonuses.  Note: Free Religion gives you a free policy!!
Freedom - Wonders give more culture, double specialists from the point of view of food and happinesss.  But the real winner is the Final pick - 100% bonus culture from your Landmarks.  5 landmarks = 30 * 2 = 60 culture before city modifiers.
Going for a culture win, you need to pick two more trees and complete them.
Wonders
The Louvre is amazing.  Sistine Chapel is very very good.
Great Wall is a nice defensive bonus if you can get it.
Hanging Gardens, Notre Dame, Taj Mahal are good for happy and food bonuses.
StoneHenge and Oracle are ok - but they are so early that I have trouble beating the AI's to them.  Oracle has a free policy!!
Sydney Opera House and Cristo Redentor are nice, but come very late.  By the time they're researched, you should have almost all your policies.
Eiffel Tower will give you a ton of happy, but at that stage in the game it doesn't really matter.
Outside of the above wonders, the others are all ok (they give some culture).

Don't slack your military to the point where you lose cities.  You should feel safe at all times.
Don't slack on your basic culture buildings.
Build money buildings if you're earning less than ~10 gold per turn.
Don't slack on food, happy and science buildings. (if you do, you'll fall behind the science race with your small population and small city count)
With all those priorities out of the way - make wonders.

Science
There's the game before Civil Service and the game after...  Civil Service gives you:

Pikemen - very powerful infantry for those with no iron
+1 extra food for river farms (that's huge!)

You aren't trying to lead the tech race in terms of number of technologies.  You're usually trying to get the missing piece of the puzzle to build a wonder.  Generally, you want to push deep into the tech tree to get to the next wonder or military unit before the AI's.  If they don't have the tech to build a wonder yet - they can't steal that wonder away from you.
Sometimes you'll do remedial research to unlock basic capabilities.  Do you have iron? only one way to find out.
Military
At the start, your city is secure.  Go exploring with the warrior, but consider bringing him back if you build a worker before a second military unit.  Exploring is just for finding citystates (gold reward), ruins (random bonuses), and natural wonders (happy).
My main force consists of spearmen -> pikemen -> riflemen, with a couple musketeers -> riflemen.

You should always have 2 or 3 units per city.  More if the Germans are your neighbors.
There are few problems that three protected cannons/artillery can't solve.
5 units with good management can kill 50 units.
Learn the line of sight rules!
Build ships for fun and natural wonder hunting.
Since you aren't trying to conquer people, you don't have to worry about splitting your forces between attack and defense.

If you happen to take an AI's city - raze it or gift it to avoid the culture penalty.  Don't attack city-states or AI capitals - you can't raze those.  Do liberate city-states from the AI if you have time and inclination.
Diplomacy
Cultural victory is the fastest victory possible.  This means you only have two paths for defeat:

Someone took your cities! (don't let that happen).
Someone beat you to the cultural victory.

You can see from Diplomacy Overview -> Global Politics which leaders have which wonders and policy counts.  If someone is building your wonders, it might be tempting to go over there and put a stop to it.
There is another way - get some of the militeristic AI's to be friends with you, and get them to declare war on the upstart.
The rule to make friends is simple enough.  If you want the AI to like you, you make deals which are bad for you!  Give them open borders for nothing.  Give them spare luxury goods for nothing.  Give them whatever they ask for when they beg.
Don't be afraid to give an AI open borders - if the AI declares war on you, all of its units are moved out of your territory at that point.
If you have a bunch of surplus gold, start recruiting city-states.  Start with the cultural ones of course.
Research agreements can give you a nice science boost.  Make sure to avoid sharing that boost with an AI that is going to use it to steal your wonders!
Comment: @Demento I have used this on difficulty 5 (king). More civilizations = more competition for wonders. I almost always play on Pangaea... I think that with only three cities you may get hammer starved and would want the cities to be as much on land as possible. You also need a bunch of land for your landmarks. If you're going for the Syndey Opera House (I don't usually), you need at least 1 coastal city... I'm unable to answer the need for greater defense on higher difficulties.
Comment: It sounds like you have some experience with this strategy. Up to which difficulty level is this approach feasible? Am I wrong that a island map is especially good for this strategy because my territory is easier to defend or is this thinking flawed?
Comment: With Brave New World you have to adapt the Aesthetics policies instead of Piety.


Java: count occurrences in 2d array and output result in 1d array

Question: I'm start to learn Java programming language and  try to solve given task
I'm try to finish method to count occurrences in 2d array and output result in 1d
public static int[] histogram(int[][] a, int high) {
    // Please write your code after this line
    // init new array
    int numOfRows = a.length;
    int numOfCols = a[0].length;
    int[] retVal = {};
    //main loop
    for (int o = 0; o < high; o++){
        //System.out.println(o);
        // go trough rows
        for(int row = 0; row < numOfRows; row++ ){
            // check for colum values
            int count = 0;
            for(int col = 0; col < numOfCols; col++ ){

                if(a[row][col] = o ){
                    count++;
                }

            }
            retVal[o] = count; // Fixed typo

        }

    }

    return retVal;
}

this is my method
I'm using BlueJ IDE for compiling and when i compile i get error
"Incompatible types " for this line
if(a[row][col] = o )
i don't get it why i get error, in my opininon a[row][col] is int type ?
and o is int type too.
Thanks
Comment: Can I suggest that `o` is a not a good choice of variable name? It looks far too much like `0` at a glance (in certain fonts).
Comment: thanks for suggestion this is anyway all not finished i'll keep your suggestion on my mind for final code.
Answer: if(a[row][col] = o )

use == operator for checking equality, so finally it should be
if(a[row][col] == o )

Comment: uhm. i that is it, i constantly think about operators and i miss this :(
Comment: @SileCetoy : always remember that == results in boolean
Answer: if(a[row][col] = o ) // Assignment Operator

should be
if(a[row][col] == o ) // Equality evaluator

Operators JavaDoc


brand new L75D-A7280 battery reports 95% max when plugged in, 93% immediately after unplugged

Question: Whenever my brand new laptop's plugged in, it reports 95% max.  It never shows 100% or charged.
Also, even though I'm not running in low power mode but am in high-GPU Catalyst mode, should it drop to to 93% immediately after unplugging?
I've looked at the bug on launchpad, and The battery indicator& Power setting panel shows wrong battery state, but neither help.
How can this be resolved?
Answer: You can try charging it all the way up ( leave it charging at least an hour after it says it is full ), run it down to 5%, then charge it all the way up again.  If the battery is still relatively healthy but aged a bit, this should trigger it to learn its correct actual capacity and may help.  Otherwise, it's probably time to replace the battery.


How to convert Dictionary to Dictionary in c#

Question: I have below code in C#
Dictionary<string, object> dObject = new Dictionary<string, object>();

I want to convert dObject to Dictionary<string, string>.  How can I do this?
Answer: Use the ToDictionary method:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value.ToString());

Here you reuse the key from the original dictionary and you convert the values to strings using the ToString method.
If your dictionary can contain null values you should add a null check before performing the ToString:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value == null ? "" : k.Value.ToString());

The reason this works is that the Dictionary<string, object> is actually an IEnumerable<KeyValuePair<string,object>>. The above code example iterates through the enumerable and builds a new dictionary using the ToDictionary method.
Edit:
In .Net 2.0 you cannot use the ToDictionary method, but you can achieve the same using a good old-fashioned foreach:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
  sd.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}

Edit2:
If you are on .Net 2.0 and you can have null values in the dictionary the following should be safe:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
  sd.Add(keyValuePair.Key, keyValuePair.Value == null ? "" : keyValuePair.Value.ToString());
}

Comment: Might I suggest using `Convert.ToString()` instead.  So it will be a little easier to deal with `null` values.  `Convert.ToString(keyValuePair.Value)` or `Convert.ToString(keyValuePair.Value) ?? String.Empty`
Comment: I am using .NET 2.0, is possible in it. I am not getting "ToDictionary"
Comment: @Rune: Will `k.Value.ToString()` return always the same as `(string)k.Value`?
Comment: @Oscar: No. the (string)k.Value will fail if the value is a non-string object. The ToString() is safe for all non-null values.
Comment: @Rune: Yes, I know that. Let's suppose all elements are strings. Will `ToString()` and `(string)` return the same?
Comment: What if there is NULL values in the key in .NET 2.0 solution
Comment: @Oscar: Yes. If all values are strings then they will do the same. In that case I believe casting to a string will be slightly faster.
Comment: @MKS: Good point. You would have to do the same null check here as in the Linq-version.
Comment: @Jeff M: Yeah. Good point! Convert.ToString is nice since you don't have to do a null check then. Convert.ToString(keyValuePair.Value) will be enough since it returns an empty string for null values.
Comment: @Rune: Actually it will return `null` in the case the argument is `null`.  Which is why I did the coalescing there.  ;)
Comment: @Jeff: `Convert.ToString()` actually returns `String.Empty` when the provided `value` is `null`.
Comment: @Jaroslav: Ah, I stand corrected.  I was testing with the wrong overload.  `Convert.ToString(string)` returns `null`.
Comment: @Jeff. Yep, that one actually does nothing else than returning the provided `value`.
Answer: .NET 3.5:
Dictionary<string, string> result = dObject.ToDictionary(kvp => kvp.Key, kvp => Convert.ToString(kvp.Value));

.NET 2.0:
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> kvp in dObject) result.Add(kvp.Key, Convert.ToString(kvp.Value));

Answer: Since you are using .net 2.0:
Dictionary<string, string> dString = new Dictionary<string, string>();

foreach (KeyValuePair<string, object> item in dObject)
{
    dString.Add(item.Key, item.Value.ToString());
    //here item.Value.ToString() is an example
    //you should convert your item to string according to the requirement
}

Comment: @MKS: That's why I'm saying "convert your item to string according to the requirement", for example you can use `string.Empty` for null values, or the string "NULL" for null values...everything depends on the requirement.
Comment: What if there is NULL values in it?
Comment: Sometime there can be null values also in the key, please suggest how to convert it?
Answer: How about:
Dictionary<string, string> newDictionary = dObject.ToDictionary(k => k.Key, k => (string) k.Value);

Comment: Since you are using .NET 2.0, foreach will be your bestest buddy! GL
Comment: This will fail if the dictionary contains non-string values. You cannot convert an int to a string for instance.
Comment: First of all I am using .NET 2.0, is possible in it. I am not getting "ToDictionary" method.
Comment: Well, I suppose if he wants to do it is because the dictionary contains `strings`, but anyway, that's valid.
Comment: Yeah true.. But ToString does not always produce a nice string. It all depends on your Dictionary objects anyhow. :)
Answer: In .Net 2.0 probably your best friend is foreach loop:
Dictionary<string, object> dObject = new Dictionary<string, object>();
Dictionary<string, string> newObjects = new Dictionary<string, string>();

foreach (KeyValuePair<string, object> keyValuePair in dObject)
{
    newObjects.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}

Answer: Dictionary<string, string> dString = dObject.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString());

It's just idea. You can insert any verifications.


AWS lambda: Execute function on timeout

Question: I am developing a lambda function that migrates logs from an SFTP server to an S3 bucket.
Due to the size of the logs, the function sometimes is timing out - even though I have set the maximum timeout of 15 minutes.
try:
   logger.info(f'Migrating {log_name}... ')
   transfer_to_s3(log_name, sftp)
   logger.info(f'{log_name} was migrated succesfully ')

If transfer_to_s3() fails due to timeoutlogger.info(f'{log_name} was migrated succesfully') line won't be executed.
I want to ensure that in this scenario, I will somehow know that a log was not migrated due to timeout.
Is there a way to force lambda to perform an action, before exiting, in the case of a timeout?
Comment: "force lambda do something, before timing out?" what does it mean? You can program any logic you want.
Comment: @Dimitris you can increase the lambda function timeout in `Configuration --> General Setting`
Comment: @jebasuthan  My question was not phrased correctly. Will edit it. I have already set lambda timeout to 15 minutes which is the maximum allowed.
Comment: @Marcin Rephrased the question
Answer: Probably a better way would be to use SQS for that:
Logo info ---> SQS queue ---> Lambda function

If lambda successful moves the files, it removes the log info from SQS queue. If it fails, the log info persists in the SQS queue (or goes to DLQ for special handling), so the next lambda invocation can handle it.
Comment: @Dimitris it's not specified in your question how your server works. But if cannot interact with sqs directly, then you can add extra lambda as you described.
Comment: Just to understand, do you recommend something like:

`SFTP Server ---> Lambda Function ---> SQS queue ---> Lambda function`
?

I do not quite get it to be honest

AWS lambda: Execute function on timeout


How can I fix this chandelier socket?

Question: I have a nice chandelier that I'd like to keep, however the light sockets are deteriorating and the light bulbs don't always connect properly which causes flickering.

Any ideas on how to replace the socket?
Comment: it looks like oxidization deposit, see if you can scratch it of with some steel wool
Answer: This is a relatively easy DIY job.  The sockets are most of the time removable.  I can't tell exactly from your picture, but they are usually held in place by a screw below, the socket itself screws in, or the sockets sometimes have a thread on the top and a bolt holds it down.  Remove the reflector/glass and take a look to see if you can figure out how to remove it.  There will be two wires attached, usually with a screw terminal.  Unscrew the wires and remove the socket.  Go to Home Depot or your local hardware store and find an exact replacement (they are 99% of the time standard sockets).  Re-attach the wires (doesn't matter if they are reversed in this case), re-attach the socket and enjoy your handy work!

How can I fix this chandelier socket?


The requested URL /apk-download/ was not found on this server

Question: I have migrated one of my client's sites to Linode. Now the homepage is working and the rest of the pages shows "NOT Found" and "The requested URL /apk-download/ was not found on this server."
Apache/2.4.25 (Debian) Server at www.frpbypass.us Port 80
URL: [http://www.frpbypass.us][1]
I have tried to change:
<code><Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>
</code>
Also, added the WordPress default .httaccess.
<code>    # BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>
After making the changes, I have restarted the Apache web server as well as Server reboot.
Any idea of how to fix?
Thanks in advance.
Answer: Finally, I am able to fix the issue. If you're experiencing the same issue then first just saving the Permalink should fix the issue. If not then try .htaccess method and finally looking for apache2.conf file.
In my case, I made all the changes as above but enabling the apache2 rewrite mod fixed my issue.
Use this command:
<code> sudo a2enmod rewrite
</code>
Hope this helps anyone who faces the same issue. It took hours of research to finally fix the issue.
Answer: Simply go to setting -> permalink and change your default permalink setting twice.
It will change the default htaccess and your site will start working.
Comment: Also, I have noticed it cannot be changed from "Post Name" structure no matter what type of structure I choose and click on save changes it comes again to Post Name.
Comment: will you please send the url of home page and screenshot of admin panel's permalink page ?
Comment: Sure here you go:https://drive.google.com/file/d/1nw1-YTdeMxTR7yG3CMEET__mYL1a0spO/view?usp=drivesdk
Comment: Here is the configuration screenshot:

https://drive.google.com/file/d/1AXFsCMhsiEgkHdcggz7gdAqXNE-uZZ0-/view?usp=drivesdk

Site URL is already given in the post.
Comment: exactly what error its showing on your pages like 404 or 500 error.
Comment: Page Not Found 404
Comment: UPDATE: Now it's working under WordPress's default but when I changed it back to Post name the same error occurs! Any advice?


JavaFX 2.1 TableView that includes WebView cells

Question: I want to create a JavaFX table that, in the cells of one column, allows the user to edit XHTML text. I only need very basic formatting capabilities like bold, italic, striketrough.
I have already managed to implement this by using my own subclass of TableCell and using a WebView for each cell (HTMLEditor would of course have been another choice, but my guess is that for my requirements, WebView should be sufficient).
However, to make editing comfortable for the user, I need the following features:
1. The cell height needs to resize if the user enters multi-line text.
2. A context menu (or, if not possible, some other menu or button) should allow formatting parts of the text in a cell as described above (bold, italic..)
Has anybody been successful in implementing something similar ? I have seen suggestions on the web, but they rarely included code samples.
Answer: I have succedded doing something similar.
I figured I can share some of the basic clues that allowed me to achieve it.

Resize the whole WebView.  For that, the whole WebView must be an editable html page.  You achive that by setting contenteditable to true:
<body contenteditable='true' id='content'></body>
You can have a context menu over a webview.  But it is something tricky, as you must first disable the original context menu associated to it.
WebView editView;
...
EventDispatcher originalDispatcher = editView.getEventDispatcher();
    editView.setEventDispatcher(new WebmenuEventDispatcher(originalDispatcher));

And this is the event dispatcher class:
<code> public class WebmenuEventDispatcher implements EventDispatcher {

        private EventDispatcher originalDispatcher;

        public WebmenuEventDispatcher(EventDispatcher originalDispatcher) {
            this.originalDispatcher = originalDispatcher;
        }

        @Override
        public Event dispatchEvent(Event event, EventDispatchChain tail) {
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (MouseButton.SECONDARY == mouseEvent.getButton()) {
                    mouseEvent.consume();
                    // Show our own menu
                    cmEdit.show(editView.getScene().getWindow(), mouseEvent.getScreenX(), mouseEvent.getScreenY());
                }
            }
            return originalDispatcher.dispatchEvent(event, tail);
        }
    }
</code>
Now, for setting the font from within that menu, you need a bidirectional Java<->javascript bridge  and use some javascript in the webview side.
Comment: Hi betaman. Thank you very much for your comment, I will try your solution. I am still struggling with the "Java <-> javascript bridge" as you call. I know how to execute Javascript and how to access Java from it in principle. But I have still little ideas on how to access the size of the user input in the WebView and resize the WebView accordingly.
Comment: Maybe you can do that from javascript, using:
window.innerWidth  and  window.innerHeight
detect them on every keypress and send them over to your Java app to resize accordingly.   Not sure if it will work, but worth a try.
Comment: You may want to try also:  document.body.clientHeight  and
document.body.clientWidth.   Tell me if you make it work with any of these.


How does one fire short staples into hard wood?

Question: I find myself caught in the middle here.
My old electric staple gun will fire 1/4" staples but it's not capable of fully setting them because part of the target is some pretty hard wood.  The shortest staples I can find for my pneumatic gun are 1/2" and would go clear through and stick out the front.
Is there an answer or do I simply replace the tape the last guy to tackle this used?
Comment: Can you just hammer the staples after shooting them?
Comment: *"How often have I said to you that when you have eliminated the impossible, whatever remains, however improbable, must be the truth?"* - [The Sign of the Four (1890)](http://en.wikiquote.org/wiki/Sherlock_Holmes#The_Sign_of_the_Four_.281890.29)
Comment: What's the application?
Comment: @gregmac I'm trying to fasten a piece of cardboard backing to a wooden frame.
Comment: Could you glue it?
Comment: @Steven I probably could.  It just seems strange that I can't find a way of stapling it.
Answer: Use 1/4" Cut Tacks instead: (Amazon)
Comment: And a needle nose pliers to hold them in just the right place when you take the first whack at each with your hammer.


Is scrolling acceptable in dashboard design?

Question: I am designing a Business dashboard (Financial Product). All info is reachable in a single scroll and primary insights are visible without scroll.
As some information below the fold the customer wants to regig the dashboard so that there is no scroll. He cited that as a general UI/UX rule that dashboards should not have scroll. I countered showing him some really efficient dashboard which have a scroll.
But as in most UX scenarios It can be argued any which way. So I wanted to get a general perception on scrolling in dashboards.
Comment: If a scrolling doesn't introduce any negative UX to non-scrollers, then it is not any worse (but may be even better) than non scrollable page.
See http://bit.ly/TtK1p0 .There are also much of research on the subject if you google it. I personally, don't believe in fold-no-fold paradigm.
Comment: "should not scroll" is contrary to the basic premise of how most every web page works, so no, that's not a general UI/UX rule at all. If anything, it's a UI/UX myth (See: http://uxmyths.com/post/654047943/myth-people-dont-scroll )
Answer: The reason some dashboards need to be scroll-free is that it is important for them to present information with a mere glance.
The best example is perhaps the one that gave dashboards its name - the car driving dashboard. You can have the driver do any action before the relevant information is available, and it can be deciphered in a blink of an eye.
Back to your finance dashboard - is your dashboard going to be displayed on a status monitor in a high-performance commerce room? If yes, then a scroll is a killer - the user would want her information just by looking at it from across the room. Most of the time you wouldn't even know where to find the mouse under the huge LCD monitor.
If on the other hand, as I guess, your dashboard is intended for relaxed managers sitting comfortably at their computer (be it a desktop or tablet), then there is no problem with scrolling. These users can afford the extra second that it takes to see the extra information.
Hope you can bring this reasoning to your customer, and think together whether scrolling is tolerated.
Comment: Your example of the status monitor made me think of a situation where the screen is projected in a meeting - where people in an interest in the content aren't physically able to scroll. That makes fold breaking bad.
Comment: in deed, the dashboard would not be very suited for this task. The presenter of such a meeting should simply take screenshots of the dashboard, and put them on a Powerpoint slide...
Answer: There are two main things to consider when deciding if you should scroll:

Will scrolling hide information that is vital to see immediately when the page is loaded?
Will scrolling make it impossible to see two or more areas of the page at the same time that depend on being seen together to be useful? (forcing the user to scroll, memorize, then scroll back)

It sounds like factor 1 isn't an issue in this case, if factor 2 isn't either, then you should be fine with scrolling.
Other options to consider:

scroll inside sections of the page, independently of the page. That way if page area A must be visible at the same time as a long list of data in page area B, you can have only B scroll while A remains visible.
use pagination or tabs inside individual sections of the page to show more information.
use expanding UI elements, like hide/show or accordions, to show only a summary of the data in a lengthy section of the page, and allow the user to expand it when they want to see more detail.
Answer: My short answer is Yes. scrolling is acceptable.
The reason being Dashboard's are nothing but distilled set of information which are also known as Key Performance Indicators (KPI's). Now you place your KPI's on your dashboard in the order that is being most used and important. Idea here is to place (as you correctly said) these primary KPI's at a position where user don't have to scroll hence primary KPI's are quickly and effectively consumed.
However depending on the domain/product you may still have secondary KPI's which also need some place in your dashboard, which could be better served below the primary KPI's. And for that if scroll is necessary why not? Profile page on this site Profile page on this site is a great example.
Keep in mind dashboards can become unusable very quickly. So it's very important that you correctly identify and prioritize KPI's which serves the purpose while it won't overload the Dashboard with lot of content.
Answer: Provided the dashboard is being viewed on a device that can scroll (as opposed to say a kiosk without a UI) yes, scrolling is fine if you need it. Many studies have shown that users scroll just fine. The simplest argument is to just ask people if the use Amazon or Facebook or the like. ;)
Answer: Since you mention a financial application dashboard, I thought I would mention that I briefly spent some time in a small quantitative trading environment a couple of years ago. The traders  each had six to eight screens mounted in a grid-like setup (each trader had his own desk with dedicated screens). I got the impression that they would rather just add an extra screen with dedicated information, than have a single screen with tabs or scrolling. If they needed specific information, they knew which screen to look at. Notifications (both visual and audible) and information seeking speed were key in their day-to-day use of the system.
As to dashboards in general, I assume you are familiar with Stephen Few's work? I did a quick search, and noticed that he also advocates NOT scrolling for dashboards in his white paper: Common Pitfalls in Dashboard Design.
Answer: Yes People do scrolling, but you should make it hidden scrolling,by making the dashboard accordion style and open the first line by default, and in the title of each line show a small summary about it's section.
see the image to more understanding:


Fridge is cold after manual defrosting, but then warms

Question: I have a Westinghouse Mastermind refrigerator. The fridge compartment is not cold. If I switch the fridge off overnight, and turn it back on in the morning, it is cold again. After a couple of weeks, it stops being cold again.
Can you suggest what the problem might be?
Comment: Hello, and welcome to Home Improvement. Why do you think this isn't a problem with the defroster? And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know you'll know the details of contributing here.
Comment: Does water come out of it while it is switched off?
Comment: @DanielGriscom I actually think it is a problem with the defroster. If it is, I would like to know if it is worth repairing.
Comment: @AndrewMorton water collects in a collection bowl on top of the compressor. It is almost overflowing in the morning.
Comment: Did you ever get this resolved? If so, please give a check-mark to the answer or write up your own answer explaining what you did to get it fixed and give yourself a check mark. That will help others with this kind of problem know that this has a resolution and is a good place to look for their answer.
Answer: It sounds like you've already identified there's a problem with the automatic defrost function.
To dive deeper into that problem you could test whether the automatic control is working or you could test whether the defrost heating element is working. The latter is easier to test, and one might argue it is also more likely to fail.
Remove power from the appliance, expose the defrost heating element, and disconnect at least one of the two wires going into the element. Measure its resistance. I don't know anything specific about your appliance, but based on general experience, I'd expect a working defrost heater element to have a resistance under 100 ohms, and probably even less than 50 ohms. If you measure much over 100, and certainly if it measures open circuit, then the element itself has failed.


Query optimization, select calling function

Question: Consider a large table, which of the below would be faster?
Both queries will select rows where time is greater than the current time.
Calling NOW() within the WHERE clause:
SELECT          *
FROM            myTable
WHERE           time > NOW()

Wrapping the call to NOW() in a sub query:
SELECT          *
FROM            myTable
LEFT JOIN       (
                    SELECT NOW() AS currentTime
                ) AS currentTimeTable ON TRUE
WHERE           time > currentTime

Comment: Test it; let us know.
Answer:
"Both queries will select rows where time is no older than 10 days."

Sorry, but your query is incorrect. I tested it in MySQL and got this:
mysql> SELECT DATE(NOW() - 10);
+------------------+
| DATE(NOW() - 10) |
+------------------+
| 2013-11-21       |
+------------------+

21.11.2013 - is the current date and not now() minus 10 days.
You should use DATE_SUB function:
mysql> SELECT DATE_SUB( NOW(), INTERVAL 10 DAY );
+-------------------------------------+
| DATE_SUB( NOW() , INTERVAL 10 DAY ) |
+-------------------------------------+
| 2013-11-11 19:40:38                 |
+-------------------------------------+

Something like this:
SELECT *
FROM   `myTable`
WHERE  `time` > DATE_SUB(NOW(), INTERVAL 10 DAY );

Here is the analysis of both of your query types:
EXPLAIN
SELECT
    *
FROM
    users
WHERE
    created > now();

Test data
I tried users table from my Drupal installation.
mysql> EXPLAIN SELECT          *
FROM            users
WHERE           created < NOW();
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | users | range | created       | created | 4       | NULL |    1 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
1 row in set (0.00 sec)

EXPLAIN
SELECT
    *
FROM
    users
LEFT JOIN (
                    SELECT NOW() AS currentTime
          ) AS tbl ON TRUE
WHERE created < tbl.currentTime;

+----+-------------+------------+--------+---------------+---------+---------+------+------+----------------+
| id | select_type | table      | type   | possible_keys | key     | key_len | ref  | rows | Extra          |
+----+-------------+------------+--------+---------------+---------+---------+------+------+----------------+
|  1 | PRIMARY     | <derived2> | system | NULL          | NULL    | NULL    | NULL |    1 |                |
|  1 | PRIMARY     | users      | range  | created       | created | 4       | NULL |    1 | Using where    |
|  2 | DERIVED     | NULL       | NULL   | NULL          | NULL    | NULL    | NULL | NULL | No tables used |
+----+-------------+------------+--------+---------------+---------+---------+------+------+----------------+
3 rows in set (0.02 sec)

Conclusion
Obviously, the 1-st query is better, as it doesn't require creating any temporary tables. Even with my little sample data, it took 0 seconds to execute the 1-st query and 0,02 secs for the 2-nd.
Comment: I hope you're using `SELECT *` for demonstration
Comment: @FreshPrinceOfSO Yes, for demonstration
Comment: OK whoops, my query doesn't do exactly what I wanted. Although my question still stands
Comment: My question is more about "is it more efficient to call the function within the where clause or within a sub query?", The question is not "how can I find time within 10 days?" - that was just an example
Comment: @Drahcir If you give us your table structure with sample data via sqlfiddle, we'll be able to analyze EXPLAIN results.
Comment: Thanks for the testing. I am suprised by the results, I was expecting that the 1st query would execute `NOW()` for all rows, and the 2nd query would only execute once. I expected the 2nd query to be faster, thanks for proving me wrong
Answer: 1) When you talk about date optimisation, using timestamps is the way to go.
2) I suggest instead of calling a function to do the math, create another column for each rows with their timestamps
3) As PeeHaa said on  this thread: « When talking about which piece of code is faster (in your OP) you're talking about micro-optimization and is really something you shouldn't have to worry about. ☺
The real question is which piece of code is: better maintainable, readable, understandable. »
I understand what is very large database management but once you've optimised indexes and datatypes you most likely will be good enough.
Comment: Thanks but your answer doesn't apply in this case. **1)** Am already using timestamps, `time` column is a `datetime` format. **2)** I wanted to compare my column with the current time (`NOW()`), so that's not really possible. **3)** This question is about PHP's function vs MySQL's `NOW` function, mine is all about MySQL.


Does resteasy support automatically mapping String/JSON MultipartFormDataInput to a object using jackson?

Question: In my rest service I am trying to upload file with JSON object using multipart/form-data. I am using resteasy MultipartFormDataInput in my back end to handle the request and access file and JSON object
I can handle my file and JSON object as below;
<code> @POST
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public void uploadFile(MultipartFormDataInput input) throws IOException {
    Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
    List<InputPart> fileInputParts = uploadForm.get("uploadedFile");
    List<InputPart> jsonInputParts = uploadForm.get("content");

    //convert the uploaded file to inputstream
    InputStream inputStream = fileInputParts.get(0).getBody(InputStream.class, null);
    byte[] bytes = IOUtils.toByteArray(inputStream);

    //Convert the uploaded JSON object
    GenericRestBean bean = new ObjectMapper().readValue(jsonInputParts .get(0).getBodyAsString(), GenericRestBean.class);
</code>
I am using jackson Object mapper to convert body string into JSON object. The problem in here is this mapping will ignore normal bean validation and I need to re implement it manually.
Does resteasy support automatically mapping String/JSON part to a object using jackson? If yes can anyone help me to get this object from MultipartFormDataInput object?
Answer: By further reading I able to find a solution for my issue. We can unmarshall Input part using GenericType as below;
<code>GenericRestBean bean = content.get(0).getBody(new GnericType<GenericReferenceRestBean>() {});
</code>
But I still have issue with bean validation. Since we put our bean validation inside the bean we have to put @Valid annotation wherever we need to validate that bean. But here how I can put that annotation? Please share if anyone have an idea.


Need confirmation of level 2 charging with 10 gauge wire

Question: My condo was built in 2021 and the builder told us it was wired for automobile charging.  Now we are finding out that the wiring provided is only 10 gauge.  Since our garages are downstairs and under neighbor's condos, rewiring to a 6 or 8 gauge wire is very expensive. Also, the wiring is probably 50 feet from my breaker box.  My understanding is that 10 gauge wires will support a continuous 24 amps (30 amps x 80%).  I found a chart on the internet that shows at 24 amps, the Tesla Model 3 charges at 22 miles per hour.  Using a range of about 300 miles, it will take 13.6 hours to fully charge.  Can someone confirm my math? Can a level 2 charger be set to deliver a specific amperage?  If not, the circuit breaker would trip, or I can imagine the wire would heat excessively at 30 amps.
Answer:
Using a range of about 300 miles, it will take 13.6 hours to fully charge.

So if you leave it plugged in overnight (let's say 8 hours on the low end) it will charge 60% of the battery. Which gives you a daily range of 180 miles without needing to stop at another charger. That should be plenty in most places. and the remaining capacity can be used as a reserve which can be topped up on any day you don't need to commute to work by car.

Can a level 2 charger be set to deliver a specific amperage?

yes, The charger will have a setting to limit the current. You will need to check the installation manual for the specifics.
Answer:
Can a level 2 charger be set to deliver a specific amperage?

Most of them can, yes. The "charger" is not a charger at all. It is simply a smart GFCI which sends a signal telling the car how many amps it can take. The car's onboard actual charger obeys that signal.  It's an ingenious standard, not surprising since it's SAE's fourth major design of a charging standard (after so many false starts). And hey, SAE isn't in the business of selling service upgrades. They're in it to sell cars.
Anyway, most chargers- sorry, EVSE's, allow you to set that "amps" signal either by cracking the case and setting DIP switches, or by a 'soft setting' done by a special procedure. (To approve a soft setting, UL wants it to be weird and difficult to do, so homeowners don't tamper with it).  A few do not - ClipperCreek comes to mind. So watch out.
Since you will probably not be able to use Grid Limiting in your condo space, a unit with that feature is probably off the table. That means your best bet might actually be the Tesla Wall Connector (Tesla socket), because the industry will be switching to it over the next 2 years.

only 10 gauge

You don't need 40-50A.  Really.  We get a lot of questions about this.  An excellent video by Technology Connections can set you straight.  And feel free to wind back to 18:30 or even the beginning if you'd like more of a backgrounder.
Alec's words: A big charger is expensive, and may come with more headaches than you bargained for. And there are plenty of those.
Alec breezed over this but my #1 is "Don't set your panel on fire".  Only a NEC Article 220 Load Calculation (pref: 220.82 alternate method) can determine the headroom in your panel.  That x 80% is your max charge. (others: a grid-limit EVSE like Wallbox can beat this, but that may be impractical to install in a condo).
#2 is not blowing up your condo's transformer, and you will probably need to report the EV charging setup to the power company. The power company may limit your charge rate anyway, so don't go putting in a 60A circuit only to get told you're limited to 20A anyway.
#3 is city permits - one person in Maryland, their town had a brutal permit process, but waived it for 15-20A circuits. *NEC does not distinguish 120V vs 240V circuits... so super easy!

My condo was built in 2021 and the builder told us it was wired for automobile charging. Now we are finding out that the wiring provided is only 10 gauge.

So if you listened to the video, the builder made the right call. They're up against panel limits - I bet your panel is 100A. They're up against transformer/provisioning limits from the utility. And their assumptions about your commute pattern are entirely reasonable: high density housing is found in urban cores: Oakland, Pasadena, Little Five Points, etc. People who buy such condos commute within that same metro - typically 30-50 miles tops each way, since traffic is pretty bad. (BTDT). So yes, if I was asked to make a blank sheet recommendation, I'd say 30A breaker myself out of a concern that for some people 20A might be too little.
Cars take a lot of power, yes, but not as much as you'd think.

My understanding is that 10 gauge wires will support a continuous 24 amps (30 amps x 80%). I found a chart on the internet that shows at 24 amps, the Tesla Model 3 charges at 22 miles per hour.

Yeah, that's about right. Teslas are more efficient generally, and the Model 3 particularly so.

Using a range of about 300 miles, it will take 13.6 hours to fully charge. Can someone confirm my math?

The error is in assuming a) the car's battery is totally empty at the end of the day, and also b) that it will need to be totally full by morning. Neither is true: just look at your experience in gas cars. You might leave with 3/4 tank and arrive back home with 1/2 tank. EV batteries work the same way, except home charging is like having an uncle who owns a gas station pour a can of gas into your car every night (as much as will fit). The size of the can corresponds to the charge capacity.
Who's kidding who?  You'd game that. :) You'd deliberately arrive home from travel on empty, and let your car slowly recover back to full over days, since "gas given" > "gas used in a typical day".
Answer: I have Tesla and charge it with 30A circuit.
That would be 24A continuous charge.
Tesla is clever and knows (detects) that I am on 30A circuit so it only uses 24A limit, without you doing anything.
I use Tesla Mobile Charger.
That gives me 264 miles range if charging for 12 hour overnight (8 PM to 8 AM).
I only drive 150 miles per day (round trip) so it works for me.
My settings on Tesla is to charge to Max 90% (to protect battery) and I newer go below 10 % to prevent getting stranded.
PS, the cable newer gets warm.
Comment: The Tesla Mobile Connector has a variety of [dongle adapters](https://shop.tesla.com/product/gen-2-nema-adapters) for several different connectors of different amps. The dongle contains a microchip, which uses the 4th pin as a datacomm line to tell the EVSE (and car) what the amperage is. "Hi, I'm a NEMA 14-30 socket, charge at 24 amps!"   If someone abused this by making a homebrew adapter cable, the Bad Thing would happen.
Comment: Thank you everyone!  I thought this topic would generate lively and informative responses and it did not disappoint.


$ A^2(t) - 5A(t) = 6I_n$ Show there exists $P : [0,1] \to GL_n(\mathbb R), \ C^1$ s.t. $\forall t \ \ P(t)A(0)P^{-1}(t) = A(t)$

Question:
Let $A : [0,1] \to M_n(\mathbb R)$ s.t. $\forall \ t \in [0,1], \
A^2(t) - 5A(t) = 6I_n.$
Show there exists $P : [0,1] \to GL_n(\mathbb R), \ C^1$ s.t. $\forall
\ t \in [0,1],\ P(t)A(0)P^{-1}(t) = A(t)$

So $X^2 - 5X - 6 = \ (X-6)(X+1)$
Hence $\forall t \in [0,1] \ A(t)$ is diagonalizable with $6$ and $1$ as eigenvalues.
Then I would use the "continuity of the roots" of the carachteristic polynomial to say that the multiplicity of $6$ and $1$ the same for all $t$, so for all $t$, $A(t) \sim A(0)$.
How to proceed?
Comment: I think you don't know well you curriculum. In any case, first understand the solution and then worry about superfluous considerations on what parts of the argument you would like to modify.
Comment: Is $A$ required to be $C^1$?
Comment: $A(t)(A(t)-5I_n)=6I_n=A(0)(A(0)-5I_n)$. Therefore $A(t)-5I_n$ and $A(0)-5I_n$ are invertible. You only need to show that $(A(t)-5I_n)(A(0)-5I_n)^{-1}$ is $C^1$ (implicit function theorem).
Comment: (This theorem is not in my curriculum so I suppose it had to be solved without)
Comment: @Servaes Must be, although he didn't put it there. Otherwise, there is no hope for such $P$.
Comment: No I checked, it's not my curriculum and it was not at the time the exercise was given. That's why I put parentheses.
Comment: It is not precised that $A$ is $C^1$.
Comment: Imagine $A(t)=6I_n$ for $t\in[0,1/2]$ and $A(t)=-I_n$ for $t\in(1/2,1]$. It satisfies the equation. Can you have such a $P$ in this case?
Comment: About the implicit function theorem, it is not needed in my solution, actually. From $A\in C^1$ (or just continuous, but in that case you might need the theorem back) you can get $(A(t)-5I_n)(A(0)-5I_n)^{-1}\in C^1$.
Comment: @Orole I thought the same, otherwise the statement is false. Also, it seems unlikely that the implicit function theorem is not among the very first things in any mathematical curriculum.
Comment: even in the first two years? Is the theorem really necessary if $A$ is only continuous?
Comment: @Lucas Necessary, not. A theorem is never necessary, since it can always be replaced by its proof. It is only convenient since it allows me to be as lazy as possible.
Answer: We assume that $A(t)\in C^1$.
There are integers $p\geq 0,q\geq 0$ s.t. $p+q=n$ and $A(0)$ is similar to $diag(6I_p,-I_q)$. Note that $trace(A(t))$ is continuous and the eigenvalues $(\lambda_i(t)$ of $A(t)$ can be numbered in such a way that they are continuous functions of $A(t)$; consequently, for every $t$, $A(t)$ is also similar to  $diag(6I_p,-I_q)$.
More precisely $A(t)=6U(t)-V(t)$ where $U,V$ are projectors of trace $p,q$ s.t. $UV=VU=0$. From $7V=A^2-6A,42U=A^2+A$, we deduce that $U(t),V(t)$ are $C^1$. To show the existence of $P(t)$, it is enough to
(*) find a $C^1$ parametrization of a basis of $E(t)=\ker(U(t)-I_n)$, a vector subspace of dimension $p$, that is an element of the Grassmannian $G_{p,n}$.
Since $G_{p,n}$ is compact, it suffices to prove locally (*). Let $t_0\in[0,1)$. We may assume that $U(t)-I=\begin{pmatrix}P_{p,p}&Q_{p,q}\\R_{q,p}&S_{q,q}\end{pmatrix}$ where $rank(U(t_0)-I)=rank(S(t_0))=q$. Thus, locally, $S(t)$ is invertible and $\begin{pmatrix}x_p\\y_q\end{pmatrix}\in E(t)$ iff $y=-S^{-1}Rx$, that is
$E(t)=\{\begin{pmatrix}x\\-S(t)^{-1}R(t)x\end{pmatrix};x\in \mathbb{R}^p\}\in G_{p,n}$. Finally, the required $C^1$ parametrization is locally
$t\rightarrow \{\begin{pmatrix}e_1\\-S(t)^{-1}R(t)e_1\end{pmatrix},\cdots,\begin{pmatrix}e_p\\-S(t)^{-1}R(t)e_p\end{pmatrix}\}$.


How to find included .h files if you're using vim?

Question: If I have a few #includelines at the top, and I want to see the files that are included, in Eclipse one can control+click on the file name. Is there any equivalent for vim?
Answer: If the file is a local included one, then you can type gf while having your cursor over the name of that file.
This is the command to do a "go file", so you leave the current file and jump to the selected file.
Answer: The above answer may work for VIM, but in general, if these are header files that you are providing, you should look in the project directory to see them, as they should contain a path and then the file such as #include "path/to/the/header.h"
From here you simply navigate to the header file. For header files included with <Angle Braces.h> you'll need to look into your compiler specific folders
Comment: I just started working on a large project. The path is just `"example.h"` and it's not in the same file, nor is it in the path, but it compiles fine.
Comment: This tells me that the make file must be doing some of the work for you in determining where files are located. Check either in the makefile (literally just called `makefile`) or in `makefile.globals`. Are you using an IDE to compile this, or command line?
Comment: Yes, makefiles are being used to compile the project. I'm using command line. There are about 15 makefiles, making finding each header file a headache without an IDE.
Comment: How many files are in your project? Are there 15 separate projects that you are combining to make yours? 15 makefiles seems a little excessive, even for medium-large projects
Answer: I found the answer shortly after posting.
http://vim.wikia.com/wiki/Open_file_under_cursor


How do I target only certain elements with the same directive, without changing the markup?

Question: I've been researching this for a few hours now.
Let's say I have a jQuery selector of $('#bottom .downloads .links a').click.....
How can I do the same type of thing in an Angular directive?
This is what I have so far and it works, but for all  tags on the page.
angular.module('directives', []).directive('a', function(mongoDB){ //Don't need ['customServices'], it can just be [] to use mongoDB
return {
    restrict : 'E',
    link : function(scope, element, attrs){
    element.on('click', function(){
        //But this gets called for all links on the page
                //I just want it to be links within the #bottom .downloads .links div
                //I wanted to use a directive instead of ng-click="someMethod()"
    });
}

});
Is there a way to target this directive to only a certain div?  I guess I could change the restrict to 'C' or 'A' and add an attribute to the links, but I was wondering if I could still layout the front end like I currently am used to with my jQuery selectors.
Answer: There is a pretty significant philosophical difference between AngularJS and jQuery. In jQuery, everything is in the DOM - including your data - and you do everything through DOM transformations. AngularJS, on the other hand, has separation of concerns built in: models, views, controllers, services, etc., are all separate. We use controllers to glue code together, but each component knows nothing about the other components.
So whereas in jQuery, one might use a selector to find all links matching a certain pattern and then add a certain functionality to it (say a click handler), in AngularJS, the HTML is the "offical record". Instead of abstracting away the attachment of a click handler into a JavaScript function, it is put right into the markup:
Click me!

In this case, doWhatever is a method on the scope for that part of the page, probably set in your controller:
$scope.doWhatever = function () {
  console.log("Hello!");
}

So the way you are approaching the problem is not going to work in AngularJS. Instead, you need to look at directives not like jQuery selectors with a function, but as an extension of HTML. You ask yourself, "what does HTML not do out of the box that I need it to?" Your answer is your directive.
But AngularJS already has a built-in directive for click handlers (the ngClick used above).
Answer: Angular already has an a directive, so you probably shouldn't create your own.
In an Angular world, to "target only a certain div" (well,  within the div) we declaratively target that  with a directive, rather than use CSS-like selectors.  So yes, restrict to 'A' and add an attribute to the  would be best:
...

I personally think this reads better.  Looking at the HTML it is clear which s have special/additional functionality.
As @Josh pointed out, you would only need to do this if ng-click isn't sufficient for your needs.
Comment: Yeah, I've been able to do the methods that both of you suggest.  I am just trying to find a way where I don't have to change the front end markup.  I found a way to kind of get it to work, but it's messy...after element.on('click', function(){ I do if($(element).parents('#bottom .downloads .links').length != 0).  I feel that with how smart Angular is, there must be a way to do it without marking up the HTML.
Comment: The reason I'm trying so hard to find an Angular solution is because I want to use my service(s) for these clicks.
Comment: @TJ, I think it is going to be difficult/messy if you want/have to reuse your existing markup.  Your solution looks reasonable -- I can't think of anything better.


how to parse string into json

Question: i have difficulty when i try to parse the following string into json can anybody gauide me or suggest me proper way of parsing following json string
'[{"club_id":"19","club_name":"Al Lawrence","club_desc":"We welcome anyone who enjoys the camaraderie of competition at any level.   Al currently coaches many Houston area runners ranging from elite to back-of-the-packers.  Today the club still has a number of members who receive professional independent coaching from Al, but that certainly is not a requirement for membership in the Al Lawrence Running Club.","club_latitude":"29.770042","club_longitude":"-95.37","club_zip":"77001","club_member_size":"93","club_size":"s","club_type":"training","club_url":"http:\/\/www.alrcus.org\/","club_img":"1390975493.jpg","is_published":"1"},{"club_id":"20","club_name":"Bay Area Fit","club_desc":"Welcome to Houston FIT! We are a group of training partners and friends preparing together for a full or half marathon in 2013\/2014. Even if you\u2019ve never run a step before, training with our group will help you conquer mental and physical barriers you never thought possible.","club_latitude":"29.564405","club_longitude":"-95.091113","club_zip":"77058","club_member_size":"302","club_size":"l","club_type":"training","club_url":"http:\/\/www.houstonfit.com\/","club_img":"1390975687.jpg","is_published":"1"},{"club_id":"22","club_name":"Bay Area Running Club","club_desc":"Order now before the next HARRA race!  Password texas.  Color, size and logo location options available plus you can add BARC on the back for just $5 more.  Flat shipping rate of $4.95 if you buy one or two singlets and no tax!  Orders are shipped out 24-48 hours after purchase. ","club_latitude":"29.583945","club_longitude":"-95.033832","club_zip":"77586","club_member_size":"450","club_size":"l","club_type":"non-training","club_url":"http:\/\/www.barchouston.com\/","club_img":"1390989179.jpg","is_published":"1"},{"club_id":"29","club_name":"Houston Harriors","club_desc":"The 1st race of the HARRA 2014 Spring Series\r\nSaturday, February 22nd, 2014 Houston, Texas\r\nSponsored by the Houston Harriers","club_latitude":"29.733042110628393","club_longitude":"-95.33655524253845","club_zip":"77001","club_member_size":"0","club_size":"","club_type":"tranning","club_url":"http:\/\/www.houstonharriers.com\/","club_img":"1391078677.jpg","is_published":"1"}]'

i have tried by eval() and JSON.parse method but error arise
Uncaught SyntaxError: Unexpected token

Comment: The string is already JSON. You are trying to convert from JSON to a JavaScript object.
Comment: It is an array. That is why `JSON.parse` doesn't work.
Comment: @Danny — JSON allows an array at the top level.
Comment: @Quentin ah, never knew that. Figured it didn't.
Answer: You cannot have control characters inside a JSON string.
Your JavaScript string literal includes:
"The 1st race of the HARRA 2014 Spring Series\r\nSaturday, February 22nd, 2014 Houston, Texas\r\nSponsored by the Houston Harriers"

This gets converted to this fragment of JSON:
"The 1st race of the HARRA 2014 Spring Series
Saturday, February 22nd, 2014 Houston, Texas
Sponsored by the Houston Harriers"

The literal new lines are forbidden. If you want them in the data, then you'll have to escape the escape characters in the JavaScript:
"The 1st race of the HARRA 2014 Spring Series\\r\\nSaturday, February 22nd, 2014 Houston, Texas\\r\\nSponsored by the Houston Harriers"

In general, however, assuming the JSON is from a trusted source, you shouldn't be embedded a string literal of JSON in JavaScript in the first place. Just take away the ' from the start and end and you'll have a JavaScript object literal that doesn't need parsing inside the JS.
Answer: The problem is arising from the escape characters in the JSON. For example: http:\/\/ and \n.
If you double-escape them (http:\\/\\/ and \\n), the parse will work:
Demo
Answer: Your problem is in the data itself where you have \r\n this is because you cannot have contorl chars in a json string.
If you remove them it all works correctly see the fiddle below
http://jsfiddle.net/DwXnb/
Comment: Control characters may not be valid, but escape sequences are. They don't need to be removed, they just need to be escaped for *both* `'` and `"` strings. `\\r\\n`

how to parse string into json


How to Query DateTime with Reactive Mongo?

Question: This is what I currently have:
BSONDocument("updated" -> BSONDocument("$gte" -> BSONDateTime(DateTime.now.plusDays(-2).getMillis),
            "$lt" -> BSONDateTime(DateTime.now.plusDays(-1).getMillis)))

However when I use this I don't get anything back from the db its just stalls, I've been waiting for a response for an hour when it usually takes seconds with other types of queries.
In the DB shell the dates come up in ISODate format if that helps
thanks
Comment: Have you tried to run the same query in the mongo shell?
Answer: You can do it  using
collection.find(gte("created",BsonDateTime(epoch)))


Ubuntu 14.10 Nvidia 540m Optimus latest graphic driver

Question: I am using ubuntu 14.10 and 331.113 NVidia driver without an issue. However I would like to install the latest possible NVidia driver that would work with my GPU. The problem is that if I download and install driver from NVidia page, it installs but I'm unable to login to the system, having information in /var/log/syslog that gnome-session crashed. If I try to install package using terminal and xorg-edgers ppa, I do not see anything newer than nvidia-331 even after sudo apt-get update.
Could someone provide me some manual how to install latest NVidia driver in this case?
Comment: Ubuntu 14.10 is not supported any more.
Comment: Welcome to Ask Ubuntu! **;-)** We're sorry, but Ubuntu 14.10 is an end-of life product and is not supported any more, so it's off-topic here too.  Please refer to https://help.ubuntu.com/community/Upgrades on how to upgrade.
Answer: You can install the latest drivers by adding the brand-new NVIDIA PPA:
sudo add-apt-repository ppa:graphics-drivers/ppa
And installing or upgrading the drivers:
sudo apt-get update && sudo apt-get install nvidia-355


20.04 Alert Volume slider missing

Question: In previous versions I was able to change volume of system alert so it is not playing on full power of my speakers with slider like this:

But this is not possible in system settings anymore. Is there any way to change this setting from console?
Comment: I'm not a GNOME user, but in the mean time I'd use `pavucontrol` to adjust the volume of *System Sounds*  (it might be that's what you need to do, but you may get a better suggestion from a GNOME user)
Answer: Did not found a way to change this from command line but as @guiverc suggested I was able to lower system sounds volume using pavucontrol:
sudo apt install pavucontrol

Playback -> System Sounds
And it does not affect other applications volume so works perfect.

20.04 Alert Volume slider missing


Creating certificate with bouncycastle

Question: I'm trying to create self-signed certificate for S/MIME with bouncycastle library. I used examples and some posts in the Internet. Code below.
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024, random);
    KeyPair keyPair = kpGen.generateKeyPair();
    PublicKey RSAPubKey = keyPair.getPublic();
    PrivateKey RSAPrivateKey = keyPair.getPrivate();
    X500Name subjectDN = new X500Name("CN =" + domain);
    SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(RSAPubKey.getEncoded()));
    X509v3CertificateBuilder v3CertBuild;
    v3CertBuild = new X509v3CertificateBuilder(subjectDN,
            BigInteger.valueOf(new SecureRandom().nextInt()),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)),
            subjectDN,
            pubKeyInfo);
    DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
    v3CertBuild.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(pubKeyInfo).getKeyIdentifier());
    v3CertBuild.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(pubKeyInfo).getKeyIdentifier());
    v3CertBuild.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_emailProtection);
    v3CertBuild.addExtension(Extension.extendedKeyUsage, false, purposes.get(0));
    v3CertBuild.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
    GeneralName[] genNames = new GeneralName[1];
    genNames[0] = new GeneralName(GeneralName.rfc822Name, new DERIA5String(domain));
    v3CertBuild.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(genNames));
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(RSAPrivateKey);
    X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertBuild.build(sigGen));
    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) certificate;
    bagAttr.setBagAttribute(
            PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
            new DERBMPString(domain));
    KeyStore kstore = KeyStore.getInstance("PKCS12", "BC");
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = certificate;
    kstore.load(null, null);
    FileOutputStream fOut = new FileOutputStream(domain+".p12");
    PKCS12BagAttributeCarrier bagAttr1 = (PKCS12BagAttributeCarrier) keyPair.getPrivate();
    bagAttr1.setBagAttribute(
            PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
            new DERBMPString(domain));
    bagAttr.setBagAttribute(
        PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(RSAPubKey.getEncoded()));
    kstore.setKeyEntry(domain, RSAPrivateKey, null, chain);
    kstore.store(fOut, password.toCharArray());

And I have this exception:
java.lang.RuntimeException: java.io.IOException: DER length more than 4 bytes: 39
at org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.engineGetCertificateChain(Unknown Source)
at org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.getUsedCertificateSet(Unknown Source)
at org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.doStore(Unknown Source)
at org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.engineStore(Unknown Source)
at java.security.KeyStore.store(KeyStore.java:1377)
at javaapplication1.Certificate.createCert(Certificate.java:91)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:38)

Or sometimes:
java.lang.RuntimeException: java.io.IOException: unknown tag 29 encountered
java.lang.RuntimeException: java.io.EOFException: DEF length 64 object truncated by 46

It stops at last line.Searched a lot about this exception, but still can't understand what's wrong with my code. Please, help me find a solution...
Comment: Suggest switching to `SecureRandom.getInstanceStrong()` if it's available and generating at least a 2048-bit RSA key.
Comment: @Scovetta Now it freeze at generateKeyPair().
Answer: The misstake was in:
v3CertBuild.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(pubKeyInfo).getKeyIdentifier());
v3CertBuild.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(pubKeyInfo).getKeyIdentifier());

getKeyIndentifier() was unnecessary...

Creating certificate with bouncycastle


Set of all perfect squares

Question: I have been going through Velleman's How to prove book and they have explained the set of all perfect squares using this set:
$S = \{ n^2 | n \in N\}$
Then it is claimed that the set S can also be rewritten as:
$S =\{x | \exists n \in N(x = n^2)\}$
I'm not able to understand the second form of the set S. In the first set, the elementhood test was $n \in N$. So any number n belonging to N will be in set S. But in the second form, the elementhood test is $\exists n \in N(x = n^2)$, but here there is no way of knowing about the result of the equality test $x = n^2$ because we don't have about the value of x yet. So how are both the set similar ?
Comment: I'm not sure your understanding of the first set is correct. It means, "take the set of all $n^2$ where $n$ is a natural number", not that any $n \in \mathbb N$ will be in $S$. It should be clear why this is the set of all perfect squares. The second form's condition is "there exists some natural number $n$ such that $x = n^2$": this exactly describes all perfect squares as well, so we just take the set of all such $x$.
Comment: Set notation is not necessarily an algorithm to compute $S$. You can use set notation to define sets which in fact are *not* computable. So you don't need to *know* the value of $x$ yet, and that is not the correct way to think about the shorthand of set notation.
Answer: The first definition says this: $S$ is the set of all squares of natural numbers.
The second definition says this: $S$ is the set of all $x$ such that $x$ is the square of some natural number.
Comment: I'll let you have this one, yours had better language.

Set of all perfect squares


Kobolds and Catacombs solo adventure loading extremely slowly

Question: Whenever I want to play a solo Kobolds and Catacombs game, the game shuffles through 30 or 40 of the loading boxes (Blaming the Rogue, Polishing Mana Crystals etc.)
Is this intentional? Does this happen to everyone? Or is it the fault of my client?
MacBook Pro 13", 2016, macOS High Sierra 10.13.1.
Comment: You're not listing any of the other hardware information, CPU speed, RAM, video card, etc.
Answer: It seems that it was only temporary, caused by server lag.
Kobolds and Catacombs was only a few minutes old when I started playing it, and too many other people were, too, so the server couldn't handle it and was extremely slow.


How to prevent battery charging unless dips below 95%? on an Asus U31SD-XH51

Question: I have an Asus U31SD-XH51 laptop running latest Ubuntu 12.04 LTS and I want to know if there is a way to prevent the system from charging the battery unless its charged level dips below 95%?
This is a feature I notice from my Windows 7 partition.  According to Asus, while the charge level is at least 95%, the system would not charge in order to prevent deterioration.  However, this is not the case on Ubuntu 12.04 because the system would still charge my battery even at 99%.
Anyone shred some light for me?
Answer: For my model, U31SD-XH51, I simply added "acip_backlight=vendor" to grub and update it.  It actually fixing all backlight problem for me.  No longer I need to mess with /etc/rc.local or LMT(laptop-mode-tools).  If anyone got a U-series, please follow the steps below and give it a shot.

sudo gedit /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"
sudo update-grub

Best of all, the battery charging concern I am having is fixed as well.  Now, it won't charge unless dips below 95%.


How to send array elements to stdin of a command?

Question: I have a command that can receive a list of file paths, newline separated, from stdin. I have these file paths stored in an array. How should I send the array elements to the command?
I have used the following, but have a vague feeling that I'm not doing it efficiently:
files=("/first/file" "/second/file" "/some/directory" "/file/with spaces")
for i in "${places[@]}" ; do echo "$i" ; done | command ...

Answer: I prefer printf:
printf "%s\n" "${array[@]}" | ...

You can also use IFS to join array elements using a character:
(IFS=$'\n'; echo "${array[*]}") | ...

The difference between "${array[@]}" and "${array[*]}" is that the former expands to the array elements as separate words, the latter expands to a single word formed by joining the array elements using the first character of IFS.
Comment: I took your approach to loop over an array using gnu parallel: `printf "%s\n" "${array[@]}" | parallel my_command {} $second_param_for_mycommand ` Having problems to get the $second_param_for_mycommand with `parallel my_command ::: "${array[@]}"`
Comment: I had leaned toward `printf` because of `print0` from `find` making a null separated list, but forgot that it prints again when the arguments exceed the number of %s in the string. The IFS way is really interesting too, you've got my +1.
Comment: @Arronical if you got the files from `find`, the the default action uses newline as the separator
Comment: Oh sorry I'm being confusing, I hadn't got them from find, it had just made my brain think in the direction of `printf`.


Return object implementing multiple traits - decorator pattern

Question: I am currently implementing decorator pattern in Rust.
In Scala we could implement method chaining via traits like:
new Scanner
    with Whitespaces
    with Keywords

I want to do the same in Rust. So, different traits for scanner:
pub struct Lexer();

pub trait Scan {
    fn scan(&self, start: &String) -> DomainTags;
}

pub struct Keywords<T> {
    decorated: T
}
impl<T: Scan> Scan for Keywords<T> {
    fn scan(&self, start: &String) -> DomainTags {
        ...
    }
}

pub struct Whitespaces<T> {
    decorated: T
}
impl<T: Scan> Scan for Whitespaces<T> {
    fn scan(&self, start: &String) -> DomainTags {
        ...
    }
}

But since I want to build my lexers with method like:
pub fn build() -> ??? {
    let lex = Lexer();
    let lex = Keyword {
        decorated: Whitespaces {
            decorated: lex
        }
    };
    lex
}

I don't know if it is possible to statically deduce the return type to something like  decltype(lex). What is the common approach, towards implementing the method? What could be improved?
To clarify: I want to return decltype(lex), because I may also have multiple traits for single Lexer, like:
pub trait Load {
    fn load<T : Load>(&self, keywords: &String);
}

impl Load for Lexer {
    fn load<Lexer>(&self, keyword : &String) {
       ...
    }
}

And I hope to return a decorated object with implementation of Load trait as well. Both method load and scan should be available.
Comment: So depending on some condition, your function may return either a `Lexer` or a `Keyword` or a `Whitespace`? Then you need to return a `Box`.
Comment: Yes, you are right. I've edited a question. In case of using multiple traits, should it be a Box or so?
Answer: A function can only return a single type of value, so the type returned by your function can't depend on runtime conditions. However that type may be a boxed trait, in which case the type of the value stored in the box may change provided it implements the appropriate trait (or traits).
From the example code you've provided, I think that Lexer should be a trait like trait Lexer: Scan + Load {} (or maybe the Scan and Load traits don't need to exist at all and the scan and load methods can be defined directly in Lexer). Then your build function should just return a boxed Lexer:
pub trait Lexer {
    fn scan (&self, start: &String) -> DomainTags;
    fn load (&self, keyword : &String);
}

pub struct Keywords<T> {
    decorated: T
}
impl<T: Lexer> Lexer for Keywords<T> {
    …
}

pub struct Whitespaces<T> {
    decorated: T
}
impl<T: Lexer> Lexer for Whitespaces<T> {
    …
}

pub fn build (cond: bool) -> Box<dyn Lexer> {
    if cond {
        Box::new (Whitespaces { … })
    } else {
        Box::new (Keywords { … })
    }
}


Design of location & tag based filtering

Question: I'm no UI expert, but I'm working on a experimental pet project that consists of an interface to search "items" (could be events, real state, etc. doesn't really matter) by location and tags.
I believe that I have more or less solved the "location" part of the filtering as you will see in the screenshot below (taking ideas from existing solutions), but I'm still struggling with the tag filtering.

The idea is the following:

User selects location
Items are sorted by distance
User adds a tag
Tag is added to the list, but results are not filtered.
User checks a tag, items are filtered to show only items with that tag.
user adds another tag, tag is automatically checked, and filter is applied (any item containg one of the tags)

Tags can be unchecked (filter is reapplied without the tag), or removed from the list.
Also, there would be a select / unselect all to simplify the process.
Do you think this process is enough simple and user-friendly? Are there other ways to do this?
Plus, I also want to add a search input somewhere, I've been considering putting it in the header, but, my fear is that in such case, it is not clear if the filters are applied when searching a specific phrase. And putting it below the map makes it dificult to notice. Maybe there's another approach I could take?
Thanks!
Comment: Have you looked at FourSquare? They have something fairly similar -- they don't have tags, but they have "Show Me" filters which would work in a similar way.
Answer: A lot can depend on the context so it'll help to actually write down a few scenarios that you expect the user to be in. E.g. I am looking for a resturaints where there is live music. It helps think through how someone would use the interface to find that.
For e.g. in google I can just type "Resturaunt live music loc:Spain" So the user is only dealing with 1 input field.
But lets say there are scenarios where filtering is the right way to go.. there are many good examples of this like yelp, amazon etc. So the design you have in general is going to be fine.
However a few things to consider:

User generated tags are difficult to work with as the language can vary a lot, list can be very long etc. So you might end up with different tags that are intended to be the same in the list. e.g. "live-music" and "live music" etc
The placement of the map is above the filters, this establishes a visual heirarchy where maps is not impacted by filtering. Better way would be to have the filters go all the way up and have the map on the right (assuming map should also display filtered results)
It seems like that to the right of tags is a search results. If so, interaction between map and listing could be odd - what happens if the user selects a result on the map. When the user scrolls, does the map stay on the top or gets scrolled away.  Have a look at the interation on http://totkare.com/search?q=20165&facility_type_id=1&lat_lng=[39.0527088,-77.3841197]
Comment: Thats some good feedback! Initially I was not planning to show results on the map, It was thought just as a visual aid to select location, but your suggestions might be changing my mind.
Comment: quick mockup: http://i.imgur.com/q3tO2oZ.png


Ubuntu wine drop-down menus issue

Question: Environment:
Ubuntu 18.04
kernel 4.15
Crossover 17.5.0-1
Wine 2.8
There is an issue when selecting any drop-down menu in wine applications. Drop-down menus doesn't to be appear. The issue reproduces in clear wine, playonlinux, crossover.
For instance any of menus below doesn't open:

Sometimes, for about 1/100 clicks it is appears on half a second.
I'm more than sure that this is a problem in some kind of package/library,
coz i didn't face it several days ago.
I think this issue doesn't related to some missing library.
I tried to solve it using opt/cxoffice/bin/cxfix --all and opt/cxoffice/bin/cxdiag is fully satisfied.
Also i tried to disable all gnome extensions. And the issue doesn't correlate with that, because i didn't do any manipulations with extensions before normal work of drop-down menus and the appearance of this problem.
Tried to successfully remove/clear any package related to wine and cxoffice / playonlinux etc. Reinstalled crossover - and nothing happens.
P.s. while clicking the window is blinking and it seems that someone (maybe Gnome window manager) intercepts window management.
UPDATE
i posted an issue with some debug details for winehq community
https://forum.winehq.org/viewtopic.php?f=8&t=30642
Answer: The issue was related to Gnome settings.
Erasing all settings helped:
sudo rm -rf .gnome .gnome2 .gconf .gconfd .metacity .cache .dbus .dmrc .mission-control .thumbnails ~/.config/dconf/user ~.compiz*

I'l explore what setting exactly caused the issue.
UPDATE
I couldn't imagine that this sh*t setting could affect window management or something related !

Allow different sources for each window causes such weird wine windows behavior !
P.s. i can somehow understand such unacceptable errors as segfaults in gnome-software-center, BUT INPUT SOURCE, shame on you Gnome developers!

Ubuntu wine drop-down menus issue


Invoke Javascript method from code-behind based on a condition.

Question: This is my javascript method in .aspx file. I want to invoke this method from code-behind based on a certain condition:
function confirmboxAndHideMessage() {
    //HideMessage();
    var response = confirm("are you sure?.");
    if (response == true) {
        document.getElementById("<%=chkValidated.ClientID%>").checked = true;
        HideMessage();
    }
    else {
        HideMessage();
        return true;
    }
}

The condition upon which I want to invoke is something like this:
        if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
        {
            btnProceedAddNewRecords.Attributes.Add("OnClick", "javascript:return confirmboxAndHideMessage();");
        }
        else
        {
            btnProceedAddNewRecords.Attributes.Remove("OnClick");
        }

This condition is being exercised in a method which is called in PageLoad event inside
if (!IsPostBack) { /* condition */ }

It is not working and my guess is that the way i am adding the method in button attribute is wrong. My request is that, kindly suggest a way I can invoke this javascript method from my code-behind based on the stated condition. If you think that my approach is flawed, Please do suggest Alternatives. Thanks.
Answer: Just add the following code where the condition is like
 public void test()
{
    String name = "test";
    if (name == "test")
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "hdrEmpty", "if(confirm('are you sure you want to continue?')==true){ Testfunction(); };", true); return;
    }
}

I am sure it will work for you.
Comment: Thanks for replying to my query. Please explain what "hdrEmpty" and "this.GetType()" parameters do?
Comment: @ebad86 "this.gettype" its return the type of current instance. And "hdrempty" its a key(that is unique identifier to script block), you can add at place of "hdrempty" whatever you want but unique. that recognize your event.
Answer: use to set/unset  OnClientClick
if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
  {
     btnProceedAddNewRecords.OnClientClick="return confirmboxAndHideMessage();";
  }
else
  {
     btnProceedAddNewRecords.OnClientClick="retun false;";
  }

Answer: You should return true or false from the function. You probably want to return true for a positive response:
function confirmboxAndHideMessage() {
  var response = confirm("are you sure?.");
  if (response == true) {
    document.getElementById("<%=chkValidated.ClientID%>").checked = true;
    HideMessage();
    return true;
  } else {
    HideMessage();
    return false;
  }
}

Use lowercase for the event name (as XHTML is picky about that), and remove javascript: from the code:
btnProceedAddNewRecords.Attributes.Add("onclick", "return confirmboxAndHideMessage();");

Put the code that sets the attribute outside the check for IsPostBack, otherwise it will not be updated when the condition changes.