javascript documentation on Date.parse

Question: I was able to parse date string in JavaScript using the following script:
var mydate = new Date(Date.parse('06/15/2012','MM/dd/yyyy'));

What really bothers me is that there is no proper documentation for the above method. MSDN, w3school and Mozilla developer sites have docs on one parameter only.
i.e., Date.parse('some date string');
What is the best JavaScript reference that has correct up to date information?
Answer: The method only pays attention to the first parameter. That is,
var mydate = new Date(Date.parse('06/15/2012'));

would give you the same result.
Comment: Pointy - Thanx. It worked with one parameter. I guess the post that recommended the second parameter was wrong.
Answer: The MDN documentation is correct.
Javascript is a dynamic, weakly typed language and it doesn't check method signatures. It just passes whatever you put into a method call to the Function object and lets it worry about it.
In this case, Date.parse ignores your second parameter.
The reason that it works is because Date.parse is designed to recognise RFC 2822 compliant dates and... parse them.
If you execute
Date.parse('06/07/2012','MM/dd/yyyy') === Date.parse('06/07/2012','dd/MM/yyyy')

in a browser console, you'll see that the second string made no difference to the parsing.

javascript documentation on Date.parse


Spring - extract files from NAS folder

Question: I'm trying to pull some files from a NAS (Linux) to local machine by using Spring.
I'd like not to use SFTP session in Spring even it works... in fact I used to pull files from an sftp server but due to some reason now the only resource I have is this NAS.
Is there any way to get it worked ? Or I have to write my own class?
Answer: Quoting from here java read file from network device:

The simplest way to do this would be to read it using regular file paths.
On Windows:
new File("\\\\server\\path\\to\\file.txt")
// (double-backslashes required for backslashes in path)

On Unix:
First mount the share using Samba (SMB, NFS or whatever other protocol) to some location like /mnt/network. Then you can use:
new File("/mnt/network/path/to/file.txt")

Once you have the File object you can use FileInputStream, FileReader or whatever else you want to read the file in.

As far as you are able to mount the remote shared dir to the local filesystem you can easily start to use regular Spring Integration:
<int-file:inbound-channel-adapter channel="files"
                directory="/mnt/network/path/to/">
    <int:poller fixed-delay="10000"/>
</int-file:inbound-channel-adapter>

Comment: What is the condition to use `new File("/mnt/network/path/to/file.txt")` ? Because the location of my files are accessible with credentiels, not sure how to do in this case.
Comment: I think that should be done on OS level via user permissions to that mounted remote disk.
Comment: I tried this line `File f = new File("/mnt/network/path/to/file.txt");` but when I evaluated expression `f.getAbsolutePath()` what I got is a path under my project root like `C:/projects/project1/mnt/network/path/to/file.txt` while it does not exist.
Comment: Well, you are on Windows and you don't follow its style: `new File("\\\\server\\path\\to\\file.txt")` ?
Comment: Oh I thought the NAS was on Linux so I used `new File("/mnt/network/path/to/file.txt")`... problem solved, thanks !

Spring - extract files from NAS folder


How to secure remote APIs for use with tyk?

Question: All calls are made through the tyk proxy to access the remote api.
How to make the remote api available only through the tyk proxy?
Comment: This answer might help: http://stackoverflow.com/questions/42557962/how-to-secure-remote-api-for-calls-not-coming-from-tyk
Comment: Using a firewall and only allowing traffic from the Tyk IP?
Answer: The two options mentioned here How to secure remote api for calls not coming from tyk? are very good. Either could work. I don't think there is a setting withing Tyk to limit this. Would have to be done from upstream


iPhone app - Persistent hamburger menu vs last page visited

Question: I'm wondering which option is best for an iPhone app using a hamburger menu (placed at the top left):

The menu is persistent on every single page even when the user goes
to a sub-level.
When the user goes to a sub-level, the hamburger menu is replaced by a back button or a button whose label is the name of last page visited.
Both. The menu is persistent on every page and a back button appears when needed.

Thanks for your help :)
Comment: There's no way to answer this. It's entirely dependent on all of the unique factors of your particular app. The IA, the content, the functionality, the needs, the customer, etc, etc.
Answer: Always have your navigation persistent.
But that doesn't mean you can't have a "back" button in place when it's needed when you dig deeper on portions of the site.

download bmml source – Wireframes created with Balsamiq Mockups
Now this is just for the sake of your answer, but I highly suggest against the hamburger menu. Many products (twitter and Facebook to name a few) have moved away from the hamburger menu because of various reasons:

Discoverability was at an all time low
Not a lot of people understood what the hamburger menu was

They all placed a navigation element that was persistent on the bottom of the page, where people could toggle between what they knew were big hit points on the site (timeline, discover, messages, etc).
Some examples:
Comment: Thanks. I do agree with you, the bottom menu (always visible options) works better than the hamburger menu. However, I think the hamburger menu is a better option when you have many categories (equally important) and sub-categories.
Comment: Yeah it's a hard one honestly. Interesting point too about subcategories and categories that are equally important.
Comment: Persistent navigation is important only when it is. Sometimes it's not. :)
Answer: I'd recommend iOS standards unless you really need to break from convention.  Standard iOS expectation is that you always have a back / up-level nav in the upper left corner. If you put 2 nav icons side-by-side in the upper left (Hamburger and Back Nav) that makes them both less usable and creates challenges - which is the one on the left most side?  Your #2 is the most common implementation.  Do users need to get back to the top most menu frequently enough to require having the hamburger nav on all screens? Then consider...
iOS standards also call for the use of the Tab Bar across the bottom - it is an option if you have a small (7) number of items in your nav (though it does persistently take up screen real-estate so isn't ideal unless the user needs to quickly access a few key screens).
The big question for any use of Hamburger Menus is... what are you putting in there?  @Majo0od incorrectly states the reasons why hamburger menus are problematic.  Hamburger menus have been being maligned considerably lately and most of the critiques have zero to do with user experience.  List Menus (Hamburger Menus) work great when they provide a consistent list of items clearly delineated.  The majority of user testing with List Menus shows that users very easily understand what they are and often go there to find stuff if the thing they're looking for isn't obvious elsewhere on the screen.  This has led to some bad practice among designers who started tossing everything in there - this leads to a garbage pile of items which makes it difficult for users to find what they're looking for or to know what to expect on subsequent visits to that menu.  A similar List Menu metaphor used all over both iOS and Android is 3 dots on the right (doesn't look like a hamburger so it isn't as maligned but has identical problems when not used consistently).  This is usually used to show a contextual list based on where the user is rather than an omnipresent top left list menu. Going back to my point for this paragraph... what are you using it for? Is it a clearly delineated list of concise items that is contextually relevant to where the user is in the app? Could it be better implemented using a different design pattern? Use the right tool for the job.
Answer: Use "back" button on sub-level pages and make menu accessible for the users with swipe gesture on all pages.
Comment: I don`t know if we understand each other. Hamburger menu icon is always visible on 1 level but menu is also accessible on every other level via swipe gesture. On sub-levels hamburger icon is replaced with back button.
Comment: Yeah I re-read your answer (and corrected myself). That's why I deleted what I wrote.
Comment: While this is an option, it's not backed up with arguments as to why it is better than what was suggestions.


Using MSTest in an open source project

Question: A colleague and I are writing an application that we intend to go Open Source with and are trying to decide on a testing framework. Without integration of NUnit (one of us has resharper while the other does not) we are leaning toward MSTest. However, if the majority of people that work on opensource .net applications only have the express edition of Visual Studio, we may have to change our mind on that.
What version of VS do you use and would MSTest turn you off to an Open Source Project?
Answer: Frankly I never heared of anyone using the Express editions. everybody I know or I talked with either use the fully fledged Visual Studio environment, or they use the compiler/libraries from the free SDK and some editor on top of it (CodeWarrior, CodeInsight etc) and rely on some variant of make to build.
As for the test framework, is a double edged sword. I'd recommend NUnit, but then... remember what happened with NDoc?
Comment: @Martinho: http://channel9.msdn.com/forums/Coffeehouse/214985-The-Sad-Death-of-NDoc/
Answer: If I truly felt strongly enough to participate in the Open Source project, MSTest alone wouldn't be enough to turn me away. I'd be willing to adapt to whatever the development tools/environment was.
...and for what it's worth, I use the full version of Visual Studio with Resharper.
Answer: Personally, I'm using VS:TS, so no, test units in MSTest wouldn't turn anything off for me ;), on the other hand, most probably, you will receive different answers from the majority of people, that are not professional programmers as well (working for money doesn't mean you can not work with / on OS projects) (the question is, how many you will find here).
However, if I understand you correctly, you don't want to use nUnit, because you it's not integrated with VS08, you might then check out these projects:
1. http://sourceforge.net/projects/visualnunit/
2. http://sourceforge.net/projects/nunitaddin/
Integrating NUnit with VS08 doesn't seem to the biggest problem, on the other hand, getting VS with built in testing framework might be a bit harder, at least for some people.
Comment: The other developer tried visualnunit but it locked up his VS. We werent aware there was an opensource version of TestDriven.Net - thanks!
Answer: I use MonoDevelop and NUnit.
Answer: I use VS 2k8 pro & MSTest as much as possible.
Answer: Even Microsoft's open source code (Prism/Composite Wpf) doesn't use MSTest.  They use NUnit for that project, I believe.
Answer: You may be able to use visual nunit to add an nunit test runner in VS. link I've never used it but it may be worth a shot.
Answer: If your problem is integration with Visual Studio, try Gallio. It includes MbUnit, but its runner can run tests from other frameworks, like NUnit, xUnit, etc.
Answer: It would turn me off. See MSBuild, NAnt, NUnit, MSTest, and frustration (not written by me!) - I suspect a number of people feel that way. MSBuild seems like a poorly-done copy of NAnt (we use both), and MSTest likewise looks like Microsoft's usual "not invented here" answer to open source. While I realize that there are good business reasons for Microsoft to develop their own tools, those reasons don't apply to their customers.
There are plug-ins to use NUnit inside Visual Studio without ReSharper, or you can always configure it to run from the Tools menu.
If you don't like NUnit, please consider one of the other open source testing alternatives. See NUnit vs. MbUnit vs. MSTest vs. xUnit.net
Answer: I think that people who don't use windows will be knocked out of the project by the choice to use MSTest. Most other c# testing libraries are available in mono, which is what mac and linux users would be using.
I don't know how many cross-platform developers you are trying to attract, but if it's an issue then you need to consider Linux/Mac devs.

Using MSTest in an open source project


Why does Flyway's Validate ignore missing files?

Question: I use Flyway's migrate when I start my application to, well, migrate the database. As per default validateOnMigrate is enabled and validate reports an error if a already applied file is changed.
So far so good, but it seems to ignore cases where an already applied file is missing.
Secondly, if the schema contains a migration that is newer than the latest available, migrate logs a warning but doesn't fail either, for example:

Schema xxx has a version (1.1.1) that is newer than the latest
  available migration (1.0.1) !

Is there a way to prevent this behaviour? I would like to have options like failIfMigrationIsMissing and failIfSchemaIsNewer.
All of this would be useful to make sure nobody installs or starts an older version on top of a newer database, e.g. downgrades. Actually I thought this would be the default behaviour, or do I miss something here?
Comment: Please file an enhancement request in the issue tracker. Thx.
Comment: @AxelFontaine: I made it two: https://github.com/flyway/flyway/issues/988 and https://github.com/flyway/flyway/issues/989
Answer: Here's a scheme that works with flyway 4.0.3. You can check all the migrations if your versioning is more complex.
flyway.migrate();
MigrationInfoService migrationInfoService = flyway.info();
MigrationInfo[] applied = migrationInfoService.applied();
MigrationInfo last = applied[applied.length - 1];
if (MigrationState.FUTURE_SUCCESS.equals(last.getState())) {
    throw new Exception("Database downgrade detected.");
}


I want to use c# web service (*.asmx) in php with jquery

Question: I want to use c# web service (*.asmx) in php via jQuery.
my web servis is :
http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit
and my php code is :
    $.ajax({
      type: "POST",
      url: "http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit",
      dataType: 'text/xml; charset=utf-8',
      success: function(data) {alert('ok')},
      error  : function(e) {alert('error')}
    });

But it dont work.
i need help
Comment: Welcome to Stack Overflow! w3schools is a wrong and misleading site. You shouldn't use it as reference for any sort of language. For PHP, there's the [PHP Manual](http://php.net), for JavaScript, there's [Mozilla Developer Network (or MDN)](https://developer.mozilla.org/). See http://w3fools.com to further understand why you should never use w3schools.
Answer: You are violating the same origin policy restriction that's built into the browsers. You cannot send cross domain AJAX requests. If you want this to work the ASMX web service must be located on the same domain as the PHP page hosting this javascript code. In this example that would be http://www.w3schools.com/.
If the service you are attempting to consume is located on a remote domain you could write a PHP script on your domain which will consume the remote service (by sending the appropriate HTTP request) and then send an AJAX request to this PHP script instead of directly attempting to call the remote service which is not possible. The new PHP script will simply act as a bridge between your domain and the remote domain where the ASMX service is hosted.
Of course if the remote service supports JSONP or CORS you could consume it directly. That's not the case with ASMX services out-of-the box. Contact the author of the service to see if he supports them.
Comment: CORS support in many browsers is still incomplete, it is nice one and I've used it as primary data exchange method but I also did make sure that there is JSONP fallback if CORS is not available or if it is broken in client browser.


Mix long term caching and code splitting in webpack 2

Question: I'm writing a javascript webapp using webpack 2 as module bundler.
What I need is a way to mix long term caching feature (https://webpack.js.org/guides/caching/) and code splitting (https://webpack.js.org/guides/code-splitting/).
I'm able to lazy load a vendor library (pixi.js in my case) using require.ensure but this cause a bundle creation including the lib. I'm also able to create cachable bundles, but I would like to create a bundle for long term caching and use it in lazy loaded part.
Is it possible?
Edit 1
I add some parts of my config for a better explanation.
entry: {
  vendor: ['some', 'vendors', 'libs'],
  pixi: ['pixi.js'],
  main: ['babel-polyfill', './app/index.js'],
},
output: {
  [... other configuration]
  filename: '[name].[chunkhash].bundle.js',
  chunkFilename: '[name].[chunkhash].js'
},

I'm using the vendor bundle for external libraries needed at startup time, but the pixi.js is only needed in some cases, but I would like to be long term cached.
The bundling phase emit this 2 files (and many others):
pixi.8ef3aeac142f1bf921bf.bundle.js
6.9331d810904191781167.js
their content is almost the same. The second one is created by the require.ensure but I would like the pixi.8ef3aeac142f1bf921bf.bundle.js was used.
Comment: question: why you need `pixi` bundle? If you are load the pixi component with require.ensure is already provided by the `6.9331d810904191781167.js`. You do not need to declare a bundle for it.
Comment: I would like to enable long term caching and I'm not sure that the "6." part of the chunk filename will remain the same if I add other require.ensure.
Comment: Ok I am updating the existing answer then. Look at it.
Answer: Using require.ensure produce a different code chunk that will be built in a different file. The kind of cache you want to offer is about the naming policy you give to those bundles (and your server configuration of course).
The parameter you are looking for is chunckFilename.
output: {
  chunkFilename: '[name].chunk.js',
}

If you set it like this you will always have predeterminated chuncks named 0.chunk.js, 1.chunk.js, etc..
Of course that can pose a problem for clients, so you would like to configure this parameter as follows:
output: {
  chunkFilename: '[name].[chunkhash].chunk.js',
}

Adding chunkhash to the name of your chunk will give you 0.4c473bca1d7688737499.chunk.js, 1.2cfbf4a9cc0e1f24ec2c.chunk.js, etc kind of chunk names.
The chunkhash is identical for each application build that doesn't change the chunck code. That means that if you never change your library, the chunkhash will never change, thus the user will never have to re-download that file again.
If you want to ensure the chunk to always have the same name, then you can specify the name on the require.ensure declaration:
require.ensure([], function(require){
  var pixi = require('pixi');
  // ...
}, "pixi"); // this will be passed webpack template under [name] and can be used with chunkFilename

I personally suggest the same approach for bundles naming:
output: {
  /**
   * Specifies the name of each output file on disk.
   * IMPORTANT: You must not specify an absolute path here!
   *
   * See: https://webpack.js.org/configuration/output/#output-filename
   */
  filename: '[name].[hash].bundle.js',

  /** The filename of non-entry chunks as relative path
   * inside the output.path directory.
   *
   * See: https://webpack.js.org/concepts/output/#output-chunkfilename
   */
  chunkFilename: '[name].[chunkhash].chunk.js',
}

Comment: I have an almost identical configuration but is not what I'm looking for. I'll try to edit my answer with some config snippets.
Comment: @c3s4 I have updated the answer with the example of how to name your chunk
Comment: sorry for thi late answer. It works perfectly for what I need.
Thanks


wifi is not working in my hp laptop 15-bs580TX FOR Ubuntu

Question: am using hp laptop 15-bs580TX
my os is ubuntu 17.10
wifi option is not displaying
how to fix this?
my wifi adapter is realtek
plz help me
Comment: Please edit to include results for `lspci -nnk | grep -iA3 net`
Comment: Try shutdown, then boot the system again ( not restart). See this question https://askubuntu.com/questions/791945/wifi-not-connecting-after-restart-in-ubuntu-16-04
Answer: Probably the drivers are deactivated.
To fix this Go to

Settings > Software sources(15.10) or Software & updates (later versions) > Go to Additional Drivers tab > Click on USE radio button of the respective wifi driver.

You can also refer this question for more details.


Why isn't the dispenser giving me spectrespecs?

Question: I am in Year 6: Spectrespecs (PS3 version) and have got the spectrespecs at Hogsmeade Station. When following Nick to the gate I need another pair of spectrespecs from the mailbox but I can only get a cartoon out of it and no spectrespecs. How do I get the spectrespecs so I can open the gate?
Comment: Sounds like a bug. Have you got the ability and the gold brick after leaving the train station?
Answer: Since you mentioned following Nick, I infer you are playing the To the Next Mission - Young Dumbledore, Draught of Living Death level.
If you have unlocked the gold brick (as you stated you did) then you should have no issue retrieving the pair of spectrespecs to unlock the gate.  Generally if you don't receive an item from a box it's because you have the item activated already, it's always worth double checking your spell wheel and see if you have the option available.
The area in question is shown here around 1:40.
Comment: Can you check that link?  There appears to be a copy and paste error.
Comment: For some reason the word wrap introduced a break in the link, possibly related to cutting and pasting ... from the edit screen the full link was there.  I've put in a shorter, youtube link. Thanks!


Why is the US keyboard symbol layout different from most other keyboards?

Question: If you look at the US keyboard layout and compare to many other layouts(except UK English) the symbols are often in a different order.
What is the historical reason for this?
It would seem to me that if they are going to copy the QWERTY keyboard layout like most countries did then they would also copy the symbol locations?
I am ignoring the fact that some have different symbols entirely.  For example looking at the Spanish keyboard, it's like somebody just put the symbols in random places.
Spanish

French

German
Comment: Can you show screenshots of keyboards in other countries/languages to highlight the differences that you are talking about? I think it would help provide a reference point to answer the question. Thanks.
Comment: You also should add an image of keyboard with US layout because not everyone know what it is like.
Comment: Symbols on UK/US keyboards are also different (though not as drastically different as some of those you've shown).
Comment: +1 for showing US layout, as it has different shape of enter key, which is not shown above...
Answer: The QWERTY keyboard layout was established in 1874 by Sholes & Glidden typewriters. Every language has certain keys that are used more often, like in English the letter W is one of the most used letters in our alphabet. However in Spain it is a very rare letter to use, and if used it's many times because of anglicised words. Same goes for the german languages, the Y is rarely used, so to place it in the centre of the keyboard or "kezboard" as the german QWERTZ layout is nicknamed, wouldn't really make much sense. Instead the Z is used much more often. These small variations have few documentation so we can't be completely sure to the actual reason, but it seems to be pure comfort of certain language users. The QWERTZ layout is not only used in Germany though, also throughout the Balkans, Austria and to some extent even Eastern European countries like Poland, Czech Republic, Romania...
As to the different symbols, it's purely based on usage of native writers. In France and Spain you will have a lot more accent symbols and in Germany there are more Diaeresis or Umlaut characters.
Fun fact, in Spain we have 4 different languages which means we have keyboard variations in our own country. In Catalonia we speak Catalan so we have keys like ç or · which on the Spanish keyboard are not available as they don't use those symbols.
Comment: This question was solely about symbols.  Citations are recommended.  [] are incredibly uncommon in about every language  yet in Spanish they are on the home row.
Comment: On my spanish keyboard those keys are pressed with ctrl + alt
Comment: @PhilipRH - concerning Poland and QWERTZ - back in the days the largest stream of typewriters came from Germany, thus it became the "official" layout (diacritic characters like ą, ę, ś, ć, ż, etc. where placed on the keys between standard characters and Enter key). When the computers started to appear, the geeks used US layout and the diacritic characters were obtained by pressing AltGr with certain letter. This resulted in two Polish layouts - "typist's" (QWERTZ) and "programmer" (QWERTY). Shift to XXI century - the "typist's" layout is in basically extinct.


casting from uchar* to uint* make unpredictable result

Question: I'm compiling this code with C99 (with some different type definitions like uint32 instead of uint32_t) for an old arm architecture.
    uint32 x2 = *((uint32 *) &data[t]);
    uint32 x3;
    memcpy(&x3, &data[t], 4);
    printf("%d %d %d %d %d %d", x2, x3, data[t], data[t + 1], data[t + 2], data[t + 3]);

(data is uchar* and have length > t + 4)
but surprisingly the output is this:
-268435454 2 2 0 0 0

what is wrong with this casting?
Comment: @Hassan `uint32_t` is part of C99, you said you were using C99
Comment: Unaligned access may be or may not be supported depending on the ARM version. IMO, you should include the architecture.
Comment: Better to use `sizeof(x3)` rather than `4`.
Comment: to be both endian and alignment safe you need to build the 32 bit number 8 bits at a time if you want to do something like this.  independent of underlying architecture.  or start with an aligned size uint32_t for example and then if you want to extract bytes at those addresses then mask and shift them out, not the other way around (larger to smaller has a much higher chance of success then smaller to larger).
Comment: Check your format specifiers too -- if `int` is 16-bit then using `%d` to print `uint32` causes undefined behaviour. You should probably write `%lu` and explicitly cast the argument to `(unsigned long)` . (In fact it'd be even better to use standard fixed-width type `uint32_t` specified by C99, instead of customized type uint32)
Comment: @M.M Or use `"%"PRIX32` from ``.
Comment: @JonathonReinhart if `uint32_t` were used instead. Who knows what `uint32` is
Comment: @M.M the compiler that I'm using, have uint32 instead of uint32_t.
Comment: You need to used `packed(1)` attribute to access `data`
Comment: @M.M excuse me. updated.
Comment: Possibly relevant and/or interesting offsite explanation: https://medium.com/@iLevex/the-curious-case-of-unaligned-access-on-arm-5dd0ebe24965
Answer: The x2 line causes undefined behavior. Firstly  data[t] might not have 32-bit alignment, and secondly, it's probably a strict aliasing violation to read a 32-bit value from that location.
Just remove that line and use the x3 version.
Comment: data is uchar * and therefor there is no alignment within it. also if there is any alignment in data, memcpy should fails too. Aliasing violation occurs in case of writing. In this example there is only reading from data, but in 3 different ways.
Comment: @Hassan yes, the fact that there is no alignment in `data` is the problem.  There needs to be alignment for the cast to work.  And `memcpy` does not require any alignment.   And aliasing violation can occur for both reading and writing.
Comment: @chux are you saying there's no aliasing violation in the original code? (if so, you'd be wrong, unless `data` points to malloc'd space and it earlier had values written into it as `uint32`, which we can't tell from the posted code)
Comment: @Hassan Agree about no Aliasing violation .  Disagree about "memcpy should fails too".  `memcpy()` works fine here.
Comment: I see AA in the `printf()` due to x3, but not `x2`.
Answer: As commented by the rest of the answers, the problem comes from an unaligned access. While unaligned access is absolutely supported by x64 or x86, you cannot say that it is fully (un/-)supported by ARM, because it is ARM version dependent.
There are three posibilities:

before ARMv5 (included). ARM didn't support unaligned access which is what uint32 x2 = *((uint32 *) &data[t]); is doing (from LDR point of view, three of the four bytes of the 32bit variable are unaligned to 4, and just one is aligned), so the result is undefined (hence an error). Given that, the problem has to be fixed by software (on ARM, __packed for unaligned pointers or structs is useful).
after ARMv7 (included), they do allow unaligned access*, so the code should be valid, without errors (however, performance is a total different topic, and I am pretty sure it will be slower compared with aligned access to 32bit, but this topic deserves its own entry).
ARMv6. Usually, ARM has something which makes things funnier, and alignment is not going to be different. Here, they added a bit in order to select which way you prefer (ARMv5 or ARMv7).
Considering "for an old arm architecture" comment, your case looks like the first one, but if you include your assembly code and architecture, that would be great for a complete answer.

*some instructions will fail as they cannot support it (i.e. STM)
Answer: You have several issues here. Do not use pointer punning, use unions for it.
Your printf format is wrong as well. You should use %u instead of %d.


Multiple image change on click (similar to Cargo image gallery scrub)

Question: I am trying to replicate Cargo's image gallery scrub using my own HTML/CSS and/or Java. Example of what I want here on image click: https://sage-smith.com/. It is similar to this stack thread (which worked in my code): how to change image onclick javascript function?
However, this solution only offers to click between 2 images. I am trying to do it with multiple images (like an image gallery).
This is what I have so far:
HTML

Javascript
  function changeImage(element) {
     element.src = element.bln ? "collage3.jpg" : "asset-2.png";
     element.bln = !element.bln;  /* assigns opposite boolean value always */
 }

Answer: if you have to change only 2 images you can add some style by displaying none and block in css
simple example:

// js

function yourFunction(){
  //here is you need to add style for img1 like  display block aaa img2 is
  //display none !
  document.querySelector(".img1").style.display = 'block'";
  document.querySelector(".img2").style.display = 'none'";

  //if you need to back images on click again you can do it by false and  true
}

//this is a simple code that i thought

Answer: First I would recommend you preload your images. Have an array of image sources, and then create a new array of images that you can then loop through. In this example I've used a promise and async/await to manage this operation.
Have a container for each image set. Attach a listener to it. The function that we reference in addEventListener actually returns a new function that will be used as a handler when the event is triggered. We pass in the container, an id, and the image set that it is going to be responsible for.
Inside handleClick we initialise index which is the current index of the array. We set the initial image in the container, and then increase index ready for the next click.
The closure (the function returned by handleClick does the work. When a click is triggered it checks index to see if it's exceeded the length of the array (in which case it resets index to 0), and then updates the image, finally increasing index for the next round.

const data=[["https://dummyimage.com/100x100/ad40ad/000000","https://dummyimage.com/100x100/454545/000000","https://dummyimage.com/100x100/789acc/000000","https://dummyimage.com/100x100/994563/000000","https://dummyimage.com/100x100/fff456/000000"],["https://dummyimage.com/100x100/ad40ad/000000","https://dummyimage.com/100x100/454545/000000","https://dummyimage.com/100x100/789acc/000000","https://dummyimage.com/100x100/994563/000000","https://dummyimage.com/100x100/fff456/000000"]];

// Returns a new array of images from
// the source array
function loadImageSet(arr) {
  return new Promise(res => {
    const set = arr.map(src => {
      const img = new Image();
      img.src = src;
      return img;
    });
    res(set);
  });
}

// Returns a nested array of images
function preload(data) {
  return Promise.all(data.map(loadImageSet));
}

async function main(data) {

  // Get the images
  const images = await preload(data);

  // Cache the containers
  const containers = document.querySelectorAll('div');

  // For each container add a listener. `handleClick`
  // does some initial setup (using the id, and image set),
  // and then returns a new function that is called
  // when `click` is triggered
  containers.forEach(c => {
    const { id } = c.dataset;
    const imageSet = images[id - 1];
    c.addEventListener('click', handleClick(c, id, imageSet), false);
  });

};

// Call the main function
main(data);

// Accepts an id and an image set
function handleClick(container, id, imageSet) {

  // Initialises the array index
  let index = 0;

  // Initialises the first image
  container.appendChild(imageSet[index]);

  // Increases the index
  ++index;

  // Return the function that is called when
  // the click event is triggered
  return function () {

    // Reset `index` if it hits the `imageSet` length
    if (index === imageSet.length) index = 0;

    // Replace the image with the next one in
    // in the `imageSet` array
    const img = container.querySelector('img');
    img.replaceWith(imageSet[index]);

    // Finally increase `index`
    ++index;
  }

}
div { display: inline-block; height: 100px; width: 100px; }
div:hover { cursor: pointer; }
img { height: 100px; width: 100px; }

Comment: hey @andy! thank you for getting back to me. so this worked when i plugged it into my code, however, i am trying to target specific div classes, this code targets all div tags. how do i achieve that? here is my test site - [link] (https://pauline-esguerra-2.superhi.com/).
Comment: `const containers = document.querySelectorAll('.myClass');` (where `myClass` is the class you're using) should be sufficient. Just make sure that the length of the images array matches the number of containers you have. @PaulineEsguerra
Comment: "make sure the length of the images array matches the number of containers you have." how do i do this? ie if i have three containers, what do i change in the code?
Comment: You make sure that your images array has three nested arrays. In my example there are two, one for each container.


How do you send an attachment with cdo.message if the file is in use

Question: I am trying to send an email in classic asp site with an attachment. I am recieving  the error "The process cannot access the file because it is being used by another process. "
The file is sitting in a shared folder on the same physical server that is hosting the site. If I check in computer management on the server I can confirm that a user has it open.
My question then is: Am I able to send a copy of the file that is saved to disk using cdo.message if that file is in use? I stripped away the rest of my code to do a test and I was still getting the same error using this.
<code>'Create the Message Object
Set objMsg = Server.CreateObject("CDO.Message")
'Set the properties of the Message
With objMsg
    Set .Configuration = cdoConfig
        .From = sFrom
        .To = sTo
        .Subject = sSubject
        .TextBody = sBody
        .Send
    End With
</code>
Answer: No you can't circumvent this restriction nor would you want to else you could be sending a corrupt file.
Comment: Curtis:  I dunno what to tell you, imagine if outlook could really breach a read lock on the file (and frankly I would be surprised that it could) and the other process was in middle of updating the file but outlook read it as is and sent it anyway.  It would be sending garbage.  Is this really desirable?
Comment: I was thinking the same. I tried though with outlook before I even bothered beginning to look and it was able to do it without a problem.


Diff between Simulink models .slx

Question: I am using Git and I am using MATLAB/Simulink.
I know that there is some kind of integration in the new versions of MATLAB/Simulink with Git but I was wondering if there is an easy way to read a git diff between 2 Simulink models which are of the format .slx
This can be useful when, for example, you have a simulink model in which you have a so-called MATLAB Embedded Function and you want to understand what the differences are between the functions in different versions of your software.
It can be also useful to understand the blocks which were commented and all the differences between two different Simulink models (.slx).
Answer: I found a solution to my problem.

If you are in your repository you MUST have a .git folder.
Go to this folder and open the file  config (create it if it is not available, but it should be there normally).
Add the following code to the file:
[diff "slx"]
textconv = unzip -c -a

Then you need to create or modify the file REPOSITORY/.gitattributes and add:
*.slx diff=slx

In this way when you do a git diff on a Simulink model (.slx) you will have a quite readable result.
I hope it will help someone else.
Comment: MathWorks also offer a model comparison through XML files generated from the models using Simulink Report Generator, see: http://uk.mathworks.com/help/rptgenext/model-comparison.html
Comment: Yes I know. To use that you should go the creation of a so-called SIMULINK project. I didn't want to do that. But it is just a matter of taste.
Comment: This might work, but as the Simulink file format is not documented, you run the risk of it not working when you switch version/release or when you compare two models created in different releases of MATLAB.
Comment: Upvote on this, it's amazing... :)  Is there any way to do this for direct file viewing of the folder as well?  Doing this with Git Extensions works perfectly to have it unzip when using the built-in diff tool, but when viewing the file directly, it does not unzip first...
Answer: Whilst a text comparison can give some idea of what has changed for simple changes, the information that goes to into a Simulink model is stored in a variety of places with the SLX container. A tool like the Simulink Comparison features within the Simulink Report Generator can give much more insight into what has changed, as well as allowing operations like merge.
Simulink has had Git integration, via a Simulink Project, since R2014a, or via the MATLAB Current Folder tool since R2014b.
Answer: There are commercial tools that can perform a diff of Simulink models, some can even merge them too.  The Mathworks tool was mentioned in the comments of another answer, but there are other tools such as SimDiff that can integrate with Git directly.
Disclaimer: I work for the company that makes SimDiff
Comment: SimDiff has been on the market since 2005, which I think is earlier than the Mathworks tool.  Speed and accuracy has always been a point of emphasis for SimDiff.  One significant advantage is that MATLAB doesn't need to be opened to perform a diff, which can save time and avoid using a MATLAB license.
Comment: Thanks for the answer. Could you highlight or point out what are the differences between SimDiff and the MathWorks tool beside the git direct integration? Is there a Student Version?
Thanks
Comment: As far as a student license, I don't think we currently have one but students may instead be eligible for extended trial periods.  But you should probably [contact sales](http://www.ensoftcorp.com/company/#ContactUs) to confirm that; I'm not up to date on the latest policies.
Answer: DiffPlug is a free git client with native support for Simulink.  Diffing models isn't free, but you can view them from history for free.

Diff between Simulink models .slx


Decorative ceiling junction box cover

Question: I know the junction box cannot be permanently covered, but I am looking for ideas for decorative covers. we are taking down a stairwell light fixture and just want to cover it up with something other than the plain round plates.
Comment: Personally, I'd watch garage sales for a stuffed fish.
Comment: Voting to close as off-topic (decorating advice).
Answer: There are numerous approaches.
The simplest is paint. If a blank cover and its screws are painted to match the wall, the box will recede in appearance.
Similarly, if the wall is wallpapered, you can wrap the blank cover with paper, gluing down a slight margin of the paper to the underside of the cover. Paint the heads of screws a color close to the paper's tone.
You can buy medallions or rosettes (meant for centers of ceilings) that can be glued to a blank cover.

If you search for ceiling medallions, you can find hundreds of styles, although many of them are pierced for electrical wires.
<code> Images and links are illustrative only, not an endorsement of goods or sources.
</code>
Comment: Ceiling medallions would still need to allow removal of the cover.
Comment: @Harper Several approaches possible. Adhesives that allow easy on/off, like those used for dorm posters; small holes drilled through the medallion to allow affixing screws; velcro; double faced foam tape, new piece after each removal; etc.

Decorative ceiling junction box cover


Issuue while implementing onClickListener

Question: See this simple code,But i am getting Description
The method onClick(View) of type CheckboxActivity must override a superclass method   CheckboxActivity.java on my onClick(View v) method.
public class CheckboxActivity extends Activity implements Button.OnClickListener{
        /** Called when the activity is first created. */
        Button b1;
        CheckBox c1, c2;
        EditText et1;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            et1 = (EditText) this.findViewById(R.id.text1);
            c1 = (CheckBox) findViewById(R.id.check1);
            c2 = (CheckBox) findViewById(R.id.check2);
            b1 = (Button) findViewById(R.id.button1);
            b1.setOnClickListener(this);
        }

        @Override
           public void onClick(View v){
            et1.setText("");
            if (c1.isChecked())
            et1.setText("Android ");
            if (c2.isChecked())
            et1.setText(et1.getText()+"iPhone ");
        }
    }

Anyone please help

.
Answer: Try:
public class CheckboxActivity extends Activity implements OnClickListener

Comment: You have to import OnClickListener of any widget or View first.Is not it ?.I import did as u told but facing same problem.
Comment: @Android Killer The import for the `OnClickListener` interface is `import android.view.View.OnClickListener;`
Comment: yes i already did that buddy.Still getting same problem.If i am removing @Override from onClick(View v), then it is working fine.Any idea?
Comment: @Android Killer ,`@Override` means you are overriding a method from the super class and `Activity` doesn't have a `onClick` method. In your case you implement the `OnClickListener` which is an interface and you don't use `@Override`, you just implement the methods from that interface.
Answer: You delete your onClick() first.
Then change ur first line as
public class CheckboxActivity extends Activity implements OnClickListener

and the import should be
android.view.View.OnClickListener;

Then after your onCreate() do a right click -> Source -> Override/Implemented Methods
the onClick() will be automatically selected in the dialog box. Click ok and type in ur required things into the method.
Answer: I don't have sources of Activity and don't have working environment to write code and run javac, so I'm just guessing, please check yourself:

Activity has onClick method already - make anonymous OnClickListener
instance and pass it to the button (or remove inheritance from
Button.OnClickListener and don't forget to call super when view is
not your button). Could be also that contract has different access
level in activity.
Level of language is 1.5 and you can't use annotation @override for interfaces.


Swift changing image doesn't work

Question: EDIT: After changing the image to a label and transform a string ">" 90 degrees it is still not working correctly. I print out the values of the degrees and it works as expected but the transform is not happening.
I have a totally strange behaviour in my iOS App. I have a table view with section headers. In these section headers are typical dropdown images. One arrow down and one arrow up image. When I tap on the header section the cells display or hide dynamically. Now I want to change the image also according to that.
This is the code that runs when I tap the section header:
func selectedSection(sender: UIButton) {
    let previousSelected = self.selectedSection
    self.selectedSection = sender.tag

    if previousSelected != self.selectedSection {
        // one section opens another gets closed
        // workaround so the animation does not look awful for section headers
        print("Previous: \(previousSelected)")
        sectionHeaders[previousSelected].toggleIcon()
        print("Selected: \(self.selectedSection)")
        sectionHeaders[self.selectedSection].toggleIcon()
        print("***********")

        var indexPathToInsert = [IndexPath]()
        var indexPathToDelete = [IndexPath]()

        for i in 0..<self.menuItems[self.selectedSection].getSubItems().count {
            indexPathToInsert.append(IndexPath(row: i, section: self.selectedSection))
        }

        for i in 0..<self.menuItems[previousSelected].getSubItems().count {
            indexPathToDelete.append(IndexPath(row: i, section: previousSelected))
        }

        tableView.beginUpdates()
        tableView.deleteRows(at: indexPathToDelete, with: .none)
        tableView.insertRows(at: indexPathToInsert, with: .automatic)
        tableView.endUpdates()
    } else {
        // close the section so the selected section is 0 again
        self.selectedSection = 0

        print("Previous: \(previousSelected)")
        sectionHeaders[previousSelected].toggleIcon()
        print("***********")
        tableView.reloadSections([previousSelected], with: .none)
    }
}

Toggle Icon looks like this:
func toggleIcon() {
    isOpen = !isOpen
    print("\(isOpen)")

    if isOpen {
        print("Works")
        self.sectionIcon.image = UIImage(named: "arrow-up")
    } else {
        print("Does not work")
        self.sectionIcon.image = UIImage(named: "arrow-down")
    }
}

When I run this and click on different headers everything works as expected. But as soon as I close one section without opening another this section is broken. The code still works but it does not change the image. It prints out:
'Selected: 1'
true
Works

And when I use a breakpoint the code is called where it sets the icon to arrow-up. However, it does not change the image.
I really don't understand what is happening. Is it not allowed to change an image more than once?
Thanks for your help!
Answer: I'm not sure if this is what cause the issue, but keep in mind that ALL UI Changes has be on the main thread.
on Swift 3,
try wrapping your call to update the image with something like
DispatchQueue.main.async { }

Good luck :)
Comment: Thanks for your response. Sadly, it's not working -.-
Answer: Ok I was able to solve it with my own implementation.
I changed the else statement in selectedSection(sender: UIButton) to:
// close the section so the selected section is 0 again
        self.selectedSection = 0

        print("Previous: \(previousSelected)")
        sectionHeaders[previousSelected].toggleIcon()
        print("***********")

        var indexPathToDelete = [IndexPath]()
        for i in 0..<self.menuItems[previousSelected].getSubItems().count {
            indexPathToDelete.append(IndexPath(row: i, section: previousSelected))
        }

        tableView.beginUpdates()
        tableView.deleteRows(at: indexPathToDelete, with: .left)
        tableView.endUpdates()

So animating the whole section did not work. Thanks @Mitesh jadav for his option but this does not close the other open sections so I sticked with my solution.

Swift changing image doesn't work


Proposal: replace current PGN viewer

Question: If you look at pgn-viewer, there are quite a few bugs and feature requests that have never gotten resolved. I ran into one just now in an answer I posted. The last update to the code repo (https://github.com/andrewphoy/chess-replayer) was 7 years ago and seems abandoned.
I propose using the new lichess embedded pgn viewer (https://github.com/lichess-org/pgn-viewer) instead, to get a more featureful viewer while still being lightweight.
However, the previous viewer was MIT licensed while this is AGPL-3.0. I'm not sure what the Stack Exchange policy for embedded content is.
Comment: Please do not edit my original posts to change my context. That's what the answers or comments are for. It is a bug if you consider not replaying a valid PGN.
Comment: For the record, the issue you encountered, it is *not* a bug. The replayer is not built to detect checks. You must exactly specify which knight is to move there. For example, the replayer is allows castling through an attacked square: https://chess.stackexchange.com/questions/24112/why-is-apronus-allowing-the-white-king-to-castle-through-an-attacked-square
Answer: While an upgraded replayer is a nice idea, my concern is coding out things such dummy pawns (How likely is it that a non-orthodox promotion is optimal?), moving into check, null moves, etc. Doing so would take away a fun aspects and functions of our replayer that other sites do not support.
Comment: Yes, we have to balance out coding custom moves with the added features/bugfixes compared to the current viewer. I lean towards replacing but that's what meta votes are for.
Answer: While moving away from what may be abandonware would be a good thing I think there is not enough information here to decide if the upsides outweigh the negatives. Information on, for example,

What is not supported in the new viewer that is in the current one?
What is supported in the new viewer that is not in the current one, and what benefit will they bring?
Will the user interface change in any way for features that are supported by both? The joy of standards is that there are so many to choose from ...
Will existing posts be broken? Reassurance will be required here.
Is it proposed to provide any guidance on how to use the viewer, especially to new users?

would be extremely useful. Without this I'm afraid my position (as a software developer) is "if it ain't broke don't fix it."
Comment: While we are at wanted features: A small b or w arrow or dot indicating the orientation of the board and who has the right to move. (At the moment it seems that the board points to the player who will move, without any indication. Can be overruled to standard look-from-White, but confusing nonetheless.)

Proposal: replace current PGN viewer


How can I catch more lint in my dryer?

Question: In the 3 story townhouse I'm currently in, the contractor originally built the (stackable) dryer vent to go straight up from it's location (top floor), then when it gets above the ceiling, it angles up to vent out at the roof top.  needless to say, this is very problematic as it requires regular cleaning.  Is there anything I can do on the dryer itself to increase the amount of lint caught while drying so that I don't have to pull this thing out to clean the vent pipe behind it as often?
Answer: They sell inline lint traps, that can be installed along the exhaust vent.

This should catch most; if not all of the excess lint, and give you a convenient easy way to clean the lint. The lint should be cleaned often (along with the dryers internal lint trap), to increase dryer efficiency and decrease the chance of fire.
Keep in mind, these are recommended to be used with a "booster fan" setup. If your exhaust line is longer than about 6' (1.8 m), you'll have to install a dryer booster fan to safely use one of these lint traps.
If you have a gas dryer, you may not be able to use an inline lint trap. Check with the manufacturer of the dryer, before installing a lint trap like this.
Warning
They sell products like this that have an open front, that "deflect" heat into the house.  These are not a good idea, since they also "deflect" moisture into the home which can lead to mold and poor indoor air quality.
Comment: You will need to clean the trap OFTEN!!!!!! Like every time you use the dryer. Otherwise, use of this trap will cause your dryer to stop working properly. Clothes will take a very long time to dry, and you risk causing a fire.
Comment: +1 on the "do not use one that deflects heat" point.

How can I catch more lint in my dryer?


Making Multiple Sequential Network Request in SwiftUI

Question: I need to make multiple request to the same url. For each request:

response is retrieved in the receiveValue closure
response which is a data is signed by invoking a webview which has javascript to sign the data. The webview view takes bindings as parameters
the signed data has to now be sent back to the server, that is another network request

However, in making these multiple requests, the next request should only be made after the previous request has completed, as the server will reject it if there is a request currently been processed. Below, I have tried to show some snippet of code what I have at the moment, but it is not working. Also, the webview view is in a .view file. In the View file, the completion closure assigns the data to @state var which triggers to webview view to sign the data. After which the signed data has to be sent to the server. I am new to this and any help will be well appreciated.
func makeMultiRequest(completion: @escaping (responseData: String) -> Void) {

        let url: String = URL ....

        let _: () = Just(url)
            .flatMap { url in
                Publishers.Sequence(sequence: Array(0..<3))
                    .flatMap { _ in
                        self.makeSingleRequest(url: url)
                            .flatMap { result -> AnyPublisher<SomeObject, Never> in

                                switch result {
                                case .success(let response):
                                    return Just(response).eraseToAnyPublisher()
                                case .failure(let error):
                                    return Empty().eraseToAnyPublisher()
                                }
                            }
                    }
            }
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break
                case .failure(let error):
                    print("Error: \(error)")
                }
            }, receiveValue: { dataToSign in
                completion(dataToSign)
            })
            .store(in: &cancellables)
    }

    func makeSingleRequest(url: String) -> AnyPublisher<Result<SomeObject, Error>, Never> {

        guard let url = URL(string: url) else {
            return ... some error
                .eraseToAnyPublisher()
        }

        let request = createRequest()

        return URLSession.shared
            .dataTaskPublisher(for: request)
            .map(\.data)
            .tryMap { data -> SomeObject in
                return try JSONDecoder().decode(SomeObject.self, from: data)
            }
            .mapError { error in
                error as Error
            }
            .map { response -> Result<SomeObject, Error> in
                if response.error.isEmpty {
                    return Result.success(response)
                }
                // all other errors
                return Result.failure("Failed")
            }
            .catch { error -> AnyPublisher<Result<SomeObject, Error>, Never> in
                return Just(Result<SomeObject, Error>.failure(error))
                    .eraseToAnyPublisher()
            }
            .eraseToAnyPublisher()
    }

Comment: Look into `async/await`
Answer: Let's start with your makeSingleRequest function. You've got a lot going on in there and I'm not sure it's all necessary. A single request has a single result, either it succeeded or failed and every Publisher already has a mechanism for conveying that. You are also doing a lot of manual managing of the error conditions that seem unusual to me. I reworked the function and came up with something like this:
func makeSingleRequest(url: URL) -> AnyPublisher<SomeObject, Error> {
      let request = URLRequest(url: url)
      return URLSession.shared
        .dataTaskPublisher(for: request)
        .map(\.data)
        .decode(type: SomeObject.self, decoder: JSONDecoder())
        .eraseToAnyPublisher()
}

Note the use of the built in publisher operator decode which handles the JSON parsing for you so you don't have to do that explicitly.
To make a publisher that does three of them in a row:
/// create a publisher which makes three requests an sends the results of each to a subscriber
func makeMultiRequest(for urlString: String) throws -> AnyPublisher<SomeObject, Error> {
  guard let url = URL(string: urlString) else {
    throw RequestErrors.invalidURLString(urlString)
  }

  return (0..<3)
    .publisher
    .map { _ in return url }
    .flatMap(makeSingleRequest)
    .eraseToAnyPublisher()
}

Note that a sequence, like the range (0..<3) already has a publisher method. The flatMap is what runs the pipeline create by makeSingleRequest and extracts the SomeObject instance that is generated then passes it further down the pipeline.
And you can call it as:
let subscription = try makeMultiRequest(for: "http://someserver.com")
  .sink { completion in
    switch completion {
    case .finished:
      // all done
      break
    case .failure(let error):
      // Do something with an error
      break
    }
  } receiveValue: { someObject in
    // do a thing with the object
  }

The receiveValue should be called three times as each request completes.


kineticjs mouse event does not listen when I use an array

Question: In kintic JS of HTML5 I am trying to vanish lines on mouse over it works fine when I am doing it with variables:
http://jsfiddle.net/Vbwta/
<code>        var layer = new Kinetic.Layer();
        lines0= new Kinetic.Line({
        points: [73+10, 70+10, 340+10, 23+10],
        stroke: 'red',
        strokeWidth: 7,
      });

      lines0.on('mouseover', function() {
            lines0.hide();
          layer.draw();;
         });

    lines1= new Kinetic.Line({
        points: [53, 50, 320, 03],
        stroke: 'red',
        strokeWidth: 7,
      });

      lines1.on('mouseover', function() {
            //document.body.style.cursor = 'pointer';
            lines1.hide();
          layer.draw();;
         });
</code>
But the same thing does not work properly when I am using array:
http://jsfiddle.net/uNak5/
<code>var lines= new Array();
    lines[0]= new Kinetic.Line({
        points: [73+10, 70+10, 340+10, 23+10],
        stroke: 'red',
        strokeWidth: 7,
      });

      lines[0].on('mouseover', function() {
            lines[a].hide();
          layer.draw();;
         });

    lines[1]= new Kinetic.Line({
        points: [53, 50, 320, 03],
        stroke: 'red',
        strokeWidth: 7,
      });

      lines[1].on('mouseover', function() {
            //document.body.style.cursor = 'pointer';
            lines[1].hide();
          layer.draw();;
         });

         layer.add(lines[0]);
         layer.add(lines[1]);
</code>
Answer: http://jsfiddle.net/uNak5/1/
I updated the code, you had the reference to your array item set to
<code>    lines[a]
</code>
rather that
<code>    lines[0]
</code>
in your listener
<code>    .on('mouseover', function());
</code>
Comment: Or, simply use `this.hide()`
Comment: I agree with Shmiddty, (this) can be used in your .on() to refer to the item itself. Example, with some extra fun.


Which companions return for knights of the fallen empire/eternal throne?

Question: So I just finished Star Wars: Knights of the Fallen Empire chapter one. And I heard that most companions will not be returning to the alliance. Which of the class companions will make a return for the story and join the alliance?
Answer: Source for these: I played all of both expansions (so far) and did every recruitment mission.  No companions return in KotET as yet, these are all from KotFE.
General

C2-N2
2V-R8

Also, Treek and HK-51 are unaffected.
Knight

T7-01
Sergeant Rusk*

Consular

Qyzen Fess

Trooper

Aric Jorgan
M1-4X
Yuun

Also, Tanno Vik appears but does not return.
Smuggler

Bowdaar
Guss Tuno

Sith Warrior

Vette
Broonmark
Lieutenant Pierce

Sith Inquisitor

Talos Drellik
Xalek

Imperial Agent

Kaliyo Djannis
Scorpio (briefly)
Dr. Lokin

Bounty Hunter

Skadge*
Gault
Torian
Blizz

* mutually exclusive

One companion also dies in KotET:

 Either Torian or Vette
Comment: You can get companions back from the bottom of the base on Odessen. I was able to get Nadia Grell back as a Jedi Consular. I've only played KotFE, not KotET.
Comment: Thanks this really helps. I wonder what happens to the others though.
Comment: @Clomp Yup, that's bypassing the story and just retrieving all of the base companions.  Worth mentioning though!


Does the circuit providing a light at the electrical panel have to be ONLY for that light?

Question: Does the circuit providing a light at the electrical panel have to be ONLY for that light?
I'm fairly sure there specifically has to be a light at the panel, as well as a circuit with an accessible outlet. My electrician at the panel install felt these needed to be separate, which I, with experience stumbling through the dark to a fusebox (20 years before that house got circuit breakers) certainly agree with. But... This means I'm spending an entire 15 amp breaker to run a 60W lightbulb (or its 8 W replacement.) Do I need to? Is that circuit required to be JUST for the panel area, or is that not actually the case? In particular, if I'm running other lighting loads off it, is it still acceptable so long as it does, indeed, light the panel area?
USA location, 2011 NEC is the code currently adopted.
Answer: The required lighting outlet for areas with equipment is definitely not required to be on a dedicated circuit. It can be on any general circuit.
Same goes for the receptacle. It is not required to be dedicated, but typically this is. This receptacle is required for unfinished basement areas. It's not required to be at the panel, but usually this is the easiest place to put it.

2011 NEC
III. Required Outlets
210.70 Lighting Outlets Required
(A) Dwelling Units.
In dwelling units, lighting outlets shall be installed in accordance
  with 210.70(A)(1), (A)(2), and (A)(3).
(3) Storage or Equipment Spaces.
For attics, underfloor spaces, utility rooms, and basements, at least
  one lighting outlet containing a switch or controlled by a wall switch
  shall be installed where these spaces are used for storage or contain
  equipment requiring servicing. At least one point of control shall be
  at the usual point of entry to these spaces. The lighting outlet shall
  be provided at or near the equipment requiring servicing.

2011 NEC
III. Required Outlets
210.52 Dwelling Unit Receptacle Outlets
(G) Basements, Garages, and Accessory Buildings.
For a one-family dwelling, the following provisions shall apply:
(1)  At least one receptacle outlet, in addition to those for specific equipment, shall be installed in each basement, in each attached
  garage, and in each detached garage or accessory building with
  electric power.
(2)  Where a portion of the basement is finished into one or more habitable rooms, each separate unfinished portion shall have a
  receptacle outlet installed in accordance with this section.


Share games between PSN users

Question: It's been a while since I've bought games from the PSN store. In a lot of games' descriptions, I've seen a section that says "2-n Network players", where n is some larger number.
Does this indicate that I am able to share my games with friends?
If yes, does this mean that my friends can play the entire game? By that I mean, would he/she be able to play the story mode of the game? Could they even play the game online in online rooms?
Or is this just indicating that I can play together with friends?
Answer: You are misunderstanding what this means. This is not saying you can share your license with others, it is saying how many players can play together in an online game.
For instance, from the PES 2017 store page, it says "Network Players 2-22".

This means that as few as 2 people can play in an online game together, but so can as many as 22 players. This doesn't mean you can purchase a game and share your license.
As for the part above it that says "1-4 Players", that is referring to how many can play on a single system.
It's somewhat obvious, but if you buy a physical copy, you can let as many people as you want borrow it to let them play, but you'll still need the disc if you want to play yourself.
Comment: You are totally right. Since I saw a share option for the games, I thought maybe it's for sharing the license.
Comment: @AliBahraminezhad no, if I had to guess, it's for sharing the game with Shareplay.

Share games between PSN users


Getting a dropdownlist to check a checkbox in asp.net/C#

Question: <input runat ="server" type ="checkbox" id="helprequest" />
Help request
<asp:DropDownList ID="options" runat="server" OnSelectedIndexChanged="checkHelpRequest">
    <asp:ListItem Text="Windows"></asp:ListItem>
    <asp:ListItem Text="Macintosh"></asp:ListItem>
    <asp:ListItem Text="Linux"></asp:ListItem>
    <asp:ListItem Text="Other"></asp:ListItem>
</asp:DropDownList>

In my codebehind, I have
protected void checkHelpRequest(object sender, EventArgs e)
{
    helprequest.Checked = true;
}

But when I select something on the dropdownlist, the checkbox, does not get marked as checked, how do I get the checkbox to appear as checked when I change the index on a dropdownlist?
Comment: Do you have autopostback="true" set on this control? You might also want to investigate other ways of doing this, for example jQuery.
Answer: Your DropDownList does not have AutoPostBack='true' set.  Without setting this, your dropdown will not post back when you change the selected index.
Just change it to:
<asp:DropDownList AutoPostBack="true" ID="options"
      runat="server" OnSelectedIndexChanged="checkHelpRequest">

Without setting this, your checkHelpRequest method will still be called when your drop down changes index, but only after a postback is caused by some other control, like a button, or another DropDownList that does have AutoPostBack set.


way to find all application using a particular java version in Windows server

Question: We have got two java versions on our server Java 1.6 and Java 1.7. Is there a way to find out what are the applications that are running on the machine that calls the version. Our requirement is to uninstall Java 1.6 but our concern is that it should not affect other application that uses the version so trying to find all the application that uses it.
Comment: If you do `java -version` in command line that is most likely the version it is running all java applications with... unless specified in a `bat` file and/or `direct path`
Answer: You can try
<code>ps aux | grep 'java'
</code>
if you're on Linux.
(UPDATE: OP subsequently clarified that we're on Windows here.)
That will show you which Java runtimes are running which apps. In the event that you can't tell (for example, the java in the ps output may be a symlink), just invoke that directly:
<code>$ ps aux | grep 'java'
wwheeler        52434   0.0  0.7  8279924 112772 s000  S+    4:53PM   0:04.12 /usr/bin/java -Dorg.gradle.daemon=true -Xdock:name=Gradle -Xdock:icon=/usr/local/Cellar/gradle/2.12/libexec/media/gradle.icns -Dorg.gradle.appname=gradle -classpath /usr/local/Cellar/gradle/2.12/libexec/lib/gradle-launcher-2.12.jar org.gradle.launcher.GradleMain bootRun
wwheeler         9158   0.0  0.0  2434840    776 s002  S+    6:07PM   0:00.00 grep java
$ /usr/bin/java -version
java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)
</code>
Comment: then use task manager and show the complete path to determine which is which
Comment: unfortunately all servers are on windows
Comment: If you do java -version in command line that is most likely the version it is running all java applications with... unless specified in a bat file and/or direct path
Comment: @3kings Agreed, but it sounds like there's some question about whether that's actually the case. So I want to help him verify. (Well, if he were on Linux.)
Comment: @3kings we do have many processes running on the server. these are basically bat or exe files. they nay have a reference to the bin folder of the java1.6 we want to get rid of. so if there is a way to find all the running process and the java they call?
Answer: No way to collect information about what application(s) use specific JRE instance. You must do it manually, because these information exist inside your application's configuration.
Supplement information, For finding JRE is running, Open your Task manager:

Open tab Details, find java process

Right click, then choose Properties from context menu:

You will see specific Java JRE is running.
Comment: Ok, I already understand your idea. I will revise the answer.
Comment: thanks but what if there are other application that uses the java 1.6 version internally
Comment: I don't understand your comment, can you make your idea more clearly?
Answer: Try this, when most of app's, software, browsers, etc. are open/running,
Start --> System Information --> Software Environment --> Loaded Modules --> (Filter on Manufacturer and see Name, Version column
The above is for Laptop, same will hold good for server.


Will pushing an old commit overwrite more recent already pushed commits?

Question: Hi there,
I don't know if the title is clear enough...
I have made a commit a few days ago and I forgot to push it.
Since then, I have made other commits and I pushed them.
Now, I want to push the old commit but I am afraid it would overwrite my most recent commits.
I mean, let's say, in the old commit, I have modified the method 'myMethod:'. In an other commit I modified this method again, and that's the version I want to keep.
What will happen if I now push the first commit ? Will this method be "reset" ?
Comment: Did you switch branches (with checkout) between making the earlier commits and the new one?
Comment: Yes I did, could it be a problem ?
Comment: What you should do depends on which commit is on which branch and which commit should be pushed to which branch. Without describing that you can't get reasonable advice (except the fact, that without `-f`, `git push` will never discard anything).
Comment: All the commits I am talking about are on or should be pushed to the same branch. The accepted answer was correct in my case, I am now reading some more docs about git :)
Answer: Push will just transfer all your commits (that happened since the last push/pull operation), in the proper sequence, to the other Repository, nothing will get overwritten.
Comment: The OP does not understand how git commits are sequenced. 'Proper' doesn't mean anything to him.
Comment: Thanks for your answer, that's actually what I thought but I preferred to ask. And @JimMaguire, I'll look into what you told me to google.
Comment: False. Push will not automatically transfer all your commits!
Comment: What you mean? Every time i do `push` all my commits get pushed. Or none, if there is something wrong. Of course, only the commits from the current branch gets pushed, other branches won't be touched.


Why my custom button states are not working?

Question: I made a custom 9-patch images for my button's background. Buttons are in drawable-hdpi and drawable-mdpi folder. I created custom selector file for my button states.
selector file login_button.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:drawable="@drawable/login_button_down" />

    <item android:state_focused="true" android:drawable="@drawable/login_button_down" />

    <item android:drawable="@drawable/login_button" />
</selector>

Then I made a custom styles.xml file for the button style:

Then applied this style to my theme file in themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

And finally added button itself to the layout file:
<Button
   android:text="@string/login_text"
   android:id="@+id/buttonSignIn"
   android:layout_width="130dp"
   android:layout_height="wrap_content">
</Button>

But if I click the button, then background image is not changed. Code is ok and all compiles nicely. I know that I have same image for two different states, but it doesn't work even for one state in emulator. Can anyone point me where is the problem?
EDIT:
Obviously normal state is working, because it gets it's image from selector xml file. Now i'm wondering why the other states are not...
Comment: If you place the `login_button` as `android:background` does it work?
Comment: @Macarse No. Added to button android:background="@drawable/login_button", even tried to comment out button style in themes.xml - result 0.
Comment: Is this a style or a theme? And how are you applying it to your button or your activity?
Comment: @Morrison Chang It's a style added to theme. I'm applying it to my activity using android:theme="@style/customTheme"
Comment: So does anyone else have any clue why this code isn't working?
Answer: I thought maybe is something to do with naming, so I named button state images with different name than login_button, because selector xml file has the same name. And I edited my selector xml file also.
Selector xml file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:drawable="@drawable/login_btn_down" />

    <item android:state_focused="true" android:drawable="@drawable/login_btn_down" />

    <item android:drawable="@drawable/login_btn" />
</selector>


How can I turn on a looking-at coordinates display?

Question: In Minecraft: Education Edition, I'm trying to build something for someone; how do I see the coordinates of the block I looking at? I can't turn debug mode on like in Java Edition so is there another way to do it?
Comment: Can you do `/gamerule showcoordinates true`? That might work it might not idk, if it does work ill leave it as an answer
Comment: No like when you turn on debug mode, there is a thing called looking at: x y z @Penguin
Comment: @Coder2195 that is impossible on bedrock/edu
Answer: Coord
Looking at a block and opening the chat, then typing /setblock  but don't hit enter! The autocomplete will show you the x, y, and z.
The more efficient option is to run /gamerule showcoordinates true and do some math or stand on the block.
/fill ?
Let's say you wanna easily /fill an area. Stand on one corner, then either remember or write down it's coordinates displayed to you by /gamerule showcoordinates true.
Then go to the other corner, look at the block, and type /fill  and press Tab three times. Then just type the earlier set of coords and complete to command.
Comment: is there a way to replicate Looking at Block: x y z
Comment: @Coder2195 are you saying you want to add a debug menu? If so, then you can't (to the extent of my knowledge), sorry!
Comment: :( im building a minecraft mansion for my gf :(((((( @Penguin
Comment: @Coder2195 does this solution work for you then? Also may I ask why you need this? Maybe there's a better way
Comment: I'm trying to make filling easizer so I just look at the block write down coords and then fill location @Penguin
Comment: @Coder2195 I've edited in a easy way to do that, check it out and see if that works
Comment: @Penguin On Java, the easier way with fill is to look at 1 corner, type /fill, hit tab 3 times, then enter. This produces an error (expectably). Now move to the other corner, look at the second block, open chat, hit up arrow to recall the prior (incomplete) command, press tab 3 times and you have the complete set of coords, just add what to fill with. Not sure if bedrock enables this,
Comment: @Coder2195 Seems like a persistent display is not an option, but the `/setblock` approach will produce the coords. Look at given block, type /setblock , press tab 3 times. You should get the coords of the block you're looking at.
Answer: You have to go into settings and toggle coordinates. I'm pretty experienced when it comes to Minecraft Edu, and use coordinates quite a bit.
Comment: Can you show those settings? If this was a vanilla setting, I assume someone would have pointed that out already, or is it something that was introduced recently?
Comment: @Joachim He seems to have misunderstood the question, OP wants the coords of the block he is looking at rather than his own position. Also, I don't believe there are mods for Education Edition


ClaimsPrincipal in HotChocolate resolver not loading from the JWT

Question: Evening all.  I've been at trying to resolve some authorization/authentication issues with Blazor/HotChocolate/Azure AD B2C for a few days and I believe I have managed to nail it down to the following:
public string GetMe(ClaimsPrincipal claimsPrincipal, [Service] IHttpContextAccessor httpContextAccessor)
        {
            ClaimsPrincipal authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(httpContextAccessor.HttpContext.Request.Headers["Authorization"])));

            //var a = Request.HttpContext.User;
            // Omitted code for brevity
            var userId = claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier);

            return userId;
        }

In the above, the claimsPrincipal does not recognize the claims from the JWT; however, the code for authenticatedUser does parse the claims.  I want to give credit where due, the code for the parsing was found at (Hot Chocolate Authenticated Connected User)  The whole idea came from there and has shed a lot of light on the source of this problem so thank you to everyone in that thread.
The code is a total mess right now as I've just been going through trying to nail down the issue.  I am not going to clean it up and just post it as is in the hope that future google searchers will run across it if they have the same issue.
Program.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Identity.Web;
using Microsoft.EntityFrameworkCore;
using HotChocolate.AspNetCore.Authorization;
using HotChocolate.Resolvers;
using Microsoft.AspNetCore.Authorization;
using HotChocolate.AspNetCore;
using HotChocolate.Execution;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));
builder.Services.AddPooledDbContextFactory<CasesMatter.Server.Data.Contexts.Postgres>
    (options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddSingleton<Microsoft.AspNetCore.Authorization.IAuthorizationHandler, CasesMatter.Server.MinimumAgeHandler>();

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("SalesDepartment",
        policy => policy.Requirements.Add(new SalesDepartmentRequirement()));
    options.AddPolicy("AtLeast21",
        policy => policy.Requirements.Add(new CasesMatter.Server.MinimumAgeRequirement(21)));
});

builder.Services.AddScoped<CasesMatter.Server.Data.Interfaces.IContact, CasesMatter.Server.Data.Access.ContactDAL>();
builder.Services.AddScoped<CasesMatter.Server.GraphQL.ContactResolver>();

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();

builder.Services.AddGraphQLServer()
    //.AddIntrospectionAllowedRule()
    .RegisterService<CasesMatter.Shared.Data.Interfaces.IContact>()
    .AddAuthorization()
    .AddQueryType<CasesMatter.Server.GraphQL.ContactResolver>()
    //.AddFiltering()
    //.AddSorting()
    //.AddProjections()
    .AddHttpRequestInterceptor<HttpRequestInterceptor>();

builder.Services.Configure<JwtBearerOptions>(
    JwtBearerDefaults.AuthenticationScheme, options =>
    {
        options.TokenValidationParameters.NameClaimType = "name";
    });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");

app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();//.RequireAuthorization();
});

app.Run();

public class SalesDepartmentRequirement : IAuthorizationRequirement
{
    public SalesDepartmentRequirement()
    {
        string a = "";
    }
}

public class SalesDepartmentAuthorizationHandler
    : AuthorizationHandler<SalesDepartmentRequirement, IResolverContext>
{
    public override Task HandleAsync(AuthorizationHandlerContext context)
    {
        return base.HandleAsync(context);
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SalesDepartmentRequirement requirement, IResolverContext resource)
    {
        throw new NotImplementedException();
    }

    //protected override Task HandleRequirementAsync(
    //    AuthorizationHandlerContext context,
    //    SalesDepartmentRequirement requirement,
    //    IResolverContext resource)
    //{
    //    if (true)
    //    {
    //        context.Succeed(requirement);
    //    }

    //    return Task.CompletedTask;
    //}
}

public class HttpRequestInterceptor : DefaultHttpRequestInterceptor
{
    public override ValueTask OnCreateAsync(HttpContext context,
        IRequestExecutor requestExecutor, IQueryRequestBuilder requestBuilder,
        CancellationToken cancellationToken)
    {
        var identity = new ClaimsIdentity();
        identity.AddClaim(new Claim(ClaimTypes.Country, "us"));

        context.User.AddIdentity(identity);

        return base.OnCreateAsync(context, requestExecutor, requestBuilder,
            cancellationToken);
    }
}

ContactResolver.cs

using HotChocolate.AspNetCore.Authorization;
using System.Security.Claims;

namespace CasesMatter.Server.GraphQL
{
    public class ContactResolver
    {
        //[UsePaging]
        //[UseProjection]
        //[UseFiltering]
        //[UseSorting]
        [Authorize(Policy = "SalesDepartment")]
        [Authorize(Policy = "AtLeast21")]
        [GraphQLDescription("Gets a list of contacts having a display name like the text provided.")]
        public List<Data.DBO.Contact> GetContacts([Service] Data.Interfaces.IContact service)
            => service.GetContacts();

        public string GetMe(ClaimsPrincipal claimsPrincipal, [Service] IHttpContextAccessor httpContextAccessor)
        {
            ClaimsPrincipal authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(httpContextAccessor.HttpContext.Request.Headers["Authorization"])));

            //var a = Request.HttpContext.User;
            // Omitted code for brevity
            var userId = claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier);

            return userId;
        }
    }

    public static class JwtParser
    {
        public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
        {
            List<Claim> claims = new();
            string payload = jwt.Split('.')[1];
            byte[] jsonBytes = ParseBase64WithoutPadding(payload);
            Dictionary<string, object> keyValuePairs = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);
            ExtractRolesFromJwt(claims, keyValuePairs);
            claims.AddRange(keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString())));
            return claims;
        }

        private static void ExtractRolesFromJwt(List<Claim> claims, Dictionary<string, object> keyValuePairs)
        {
            keyValuePairs.TryGetValue(ClaimTypes.Role, out object roles);
            if (roles is null) return;
            string[] parsedRoles = roles.ToString().Trim().TrimStart('[').TrimEnd(']').Split(',');
            if (parsedRoles.Length > 1)
            {
                foreach (string parsedRole in parsedRoles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, parsedRole.Trim('"')));
                }
            }
            else
            {
                claims.Add(new Claim(ClaimTypes.Role, parsedRoles[0]));
            }
            keyValuePairs.Remove(ClaimTypes.Role);
        }

        private static byte[] ParseBase64WithoutPadding(string base64)
        {
            switch (base64.Length % 4)
            {
                case 2:
                    base64 += "==";
                    break;
                case 3:
                    base64 += "=";
                    break;
            }
            return Convert.FromBase64String(base64);
        }
    }
}

The longer story was that I started trying to setup authorization and continued struggling with why calls to the HotChocolate resolver methods were not triggering the Authorize policies I had in place.  After pounding around on it a while, it dawned on me that it could be because there was actually an Authentication issue and the user was not authenticated according to HotChocolate's interpretation.  I pulled the JWT and plugged it into postman and ran the query against the host.  I found that the "authenticatedUser" variable actually had all the claims from the JWT while the claimsPrincipal had none.  The claimsPrincipal is not arriving at the resolver with the identity information.
Thus, my ultimate question, does anyone know how I have failed?
Comment: I ended up using a TokenValidationManager.

in program.cs:
app.UseTokenValidationManager();

in another file:
public static class TokenValidationManagerExtensions
    {
        public static IApplicationBuilder UseTokenValidationManager(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware();
        }
    }

then creating the TokenValidationManager class and in the InvokeAsync method, just going through the claims.
Comment: Did you ever manage to get the ClaimsPrincipal injected properly? I'm just struggling with this myself...
Answer: I had the same problem when using multiple authentication schemes. There is a reported issue on GitHub: Authorization fails on multiple authentication schemes unless RequireAuthorization() is set.
To solve that I had to add a HttpRequestInterceptor to force the user authentication:
public class HttpRequestInterceptor : DefaultHttpRequestInterceptor
{
    private readonly IPolicyEvaluator _policyEvaluator;
    private readonly IAuthorizationPolicyProvider _policyProvider;

    public HttpRequestInterceptor(IPolicyEvaluator policyEvaluator,
        IAuthorizationPolicyProvider policyProvider)
    {
        _policyEvaluator = policyEvaluator;
        _policyProvider = policyProvider;
    }

    public override async ValueTask OnCreateAsync(HttpContext context,
        IRequestExecutor requestExecutor, IQueryRequestBuilder requestBuilder,
        CancellationToken cancellationToken)
    {
        await _policyEvaluator.AuthenticateAsync(await _policyProvider.GetDefaultPolicyAsync(), context);
        await base.OnCreateAsync(context, requestExecutor, requestBuilder, cancellationToken);
    }
}

And I registered the interceptor after the GraphQL Server:
services
    .AddGraphQLServer()
    .AddHttpRequestInterceptor<HttpRequestInterceptor>();

Other extreme solution would have been to enable Global authorization using the RequireAuthorization() middleware:
app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL().RequireAuthorization();
});


Which is the best way to display "Favorites" in a mobile app?

Question: Which is the general practice to display a "Favorites" button in mobile apps? Should I should use a row in a list of options or a button in a fixed bar that is always displayed throughout the app?
Does it matter if a "Favorites" section is not going to be an important part of the app, and therefore it's just an add-on?

Which is the best approach to display "Favorites" in a mobile app?
Comment: @CeceXX looks like we're following each other around the SE ecosystem!
Comment: @JohnGB this seems pretty broadly applicable to me. It's very much a question of OS conventions and user expectations, not "my app" implementation.
Comment: It depends entirely on the app, the content, the users, etc. There's no generic 'best' way to do this.
Comment: @plainclothes Yes, this is great :-)
Comment: @CeceXX I've put this on hold, as you are more asking "How should my app do it" than a general UX question.  If you rephrase your question to be clearer and more generic, you can ask for it to be re-evaluated.
Answer: Validate hierarchy
You say it's not an important part of the app, but are you sure? If your app has many potential views and users are going to spend a lot of time with it, a Favorites feature can gain a lot of traction.
Follow expectations
Once you're certain about feature hierarchy, it's good to stick with the OS's conventions. The main nav bar (along the bottom for iOS, top for Android) is for primary views. Anything that isn't going to be frequently accessed should not live there.
Answer: Since the inbox is going to be of variable length I would recommend putting the favorites feature in a fixed location. If I were to mark my favorites then not check my inbox for a while it could be buried hundreds of emails deep. In my yahoomail I have over 19k emails, that would take ages to get to my favorites at the end of the inbox (I know this is an outlier type scenario but could still happen).
If those 4 features are going to be the only ones on the nav bar then I think it fits in perfectly right there, it does not appear crowded and is easy to access.
Comment: I assumed these were the actual messages, since the header is labeled Inbox and there are both sent and received. If these are indeed inboxes then that does make a difference and I would agree that it may make more sense to put the favorites in there as there probably wont be too many inboxes, especially if rearrangeable so users could lock favorites near the top.
Comment: But, by definition, "outlier" scenarios do not belong in the nav bar.
Comment: 19k emails being the outlier, having over ~10 emails in the box (enough to push favorites off screen) will be pretty much always.
Comment: These are just inboxes, not actual message, right? Will the avg user have more than 10 inboxes? For the record, I do think Faves is a primary nav point, but OP said it's not.
Comment: ^ "lock near top" is the key if this is truly a lower hierarchy element.


How is $ −0.408792 = \overline{1}.591208?$

Question: $$\log x = −24\times \log(1.04) = (−24) \times 0.017033 = −0.408792
= \overline{1}.591208 = \overline{1} .5912 \text{(approx)}$$

How did the negative value turn into positive?
Comment: $-0.408792\neq 1.591208$.  Are you sure you didn't crop the image poorly or have some important signs missing?  Further, in the linked image there is an overline on the one, $\overline{1}.591208$... what is that meant to represent here?  It has no defined meaning in this context that I am aware of...
Comment: exactly, I couldn't find the formula they used to make the value with overline.
Comment: If you are tasked with solving $\log(x)=-24\times \log(1.04)$ (*regardless which base is intended for the log, be it $\ln, \log_{10}$ or even $\log_2$*), use the property that $a\log b = \log b^a$ to learn that $\log(x)=-24\times\log(1.04)\implies \log(x)=\log(1.04^{-24})$ which since $\log$ is an injective function on its domain in the reals implies $x=1.04^{-24}\approx 0.39012$
Comment: It seems to be $1.591208=2+(-0.408792)$ though it doesn't make much sense.
Answer: I've seen the notation $\bar{1}.5912$ on this site before. From context, I inferred that it meant $-1 + 0.5912$ (which is indeed equal to $-0.4088$). It's written this way because if you have a $\log$ table, you look up $0.5912$ in the table, then multiply your answer by the base to the power of $-1$.
Comment: I confirm this the notation used when computations were mage with logarithm tables (before computers). In $\bar n.xxxxxx$ denoted the integer part of the logarithm when this logarithm is negative.
Comment: Basically its a business administration math and here is the full solution of the math: https://ibb.co/gW65sR
Comment: @Nilot Now that you know what the notation means, can you follow the solution clearly?
Comment: @Y.Forman as I don't understand maths much, can you tell me what will be the value of -0.2574 and how?
Comment: @Nilot What do you mean "what will be the value"? (And I can't see where that number comes up in the solution you posted.)
Comment: @Y.Forman it's from another problem where I stuck. it will be logx = -0.2574
Comment: @Nilot Are you using log tables? If you have a calculator, you don't have to bother with the bar notation -- just type in $10^{-0.408792}$ for your first example or $10^{-0.2574}$ for this new one
Comment: @Y.Forman Got it. So by this I will directly get the value of 'x' and can skip the bar notation & anti log. I got the value of x = 0.5528. Thank you.
Answer: The notation reflects the form $$x=a \times 10^n$$where $1\le a \lt 10$ and $n$ is an integer. Tables are produced in this range for $0\le \log_{10} a \lt 1$ and one writes $\log_{10} x = n+\log_{10} a$ if $n\ge 0$ and $ x=\bar n+\log_{10} a$ concatenating as if a decimal, if $n\lt 0$.  One deals with the integer parts and the fractional parts separately - the fractional parts sometimes give a carry.
This was taught in my school in the 1970s, and facilitated computation based on the use of tables. There were other aids like slide rules (where keeping track of the power of ten was also essential). Now, of course, it is a lot less common.
Comment: [+1] Full agreement : at that time "logarithms" were  considered as a kind of numbers "not as the others", partly due to this bar-notation. Instead of your last sequence, I would have written : "I thought, now that, for at least twenty years, "log" is a button on pocket computers,  this notation had been completely eradicated...