Error linkedlist peek() not null and size() =0

Question: import java.util.LinkedList;

public LinkedList<String> mylinkedlist;

/*...*/

System.out.println("STRING: "+ mylinkedlist.peek() +" SIZE: "+ mylinkedlist.size());

output

STRING: blablabla SIZE: 0

it is a debugging question : How can peek() return a value and size of the list be 0 ?
EDIT FEB 25 - Bug appear again
The error :
java.util.NoSuchElementException
    at java.util.LinkedList.removeFirst(LinkedList.java:270)
    at java.util.LinkedList.pop(LinkedList.java:801)
    at GrblCommunicator.streamCommands(GrblCommunicator.java:164)
    at GrblCommunicator.responseMessage(GrblCommunicator.java:234)
    at ResponseMessageHandler.handleResponse(ResponseMessageHandler.java:33)
    at SerialConnectionJserial.serialEvent(SerialConnectionJserial.java:114)
    at com.fazecast.jSerialComm.SerialPort$SerialPortEventListener.waitForSerialEvent(SerialPort.java:1387)
    at com.fazecast.jSerialComm.SerialPort$SerialPortEventListener$1.run(SerialPort.java:1300)
    at java.lang.Thread.run(Thread.java:748)

The code :
import java.util.LinkedList;

/*...*/

public volatile LinkedList<String> commandBuffer;

public void streamCommands() {

        if (this.commandBuffer.size() == 0) {
            // NO-OP
            return;
        }

        if (this.sendPaused) {
            // Another NO-OP
            return;
        }

        while (CommUtils.checkRoomInBuffer(this.sentBufferSize, this.commandBuffer.peek())
                && allowMoreCommands()) {

            if(this.commandBuffer.size()==0) {
                System.out.println("ERROR DE COMMAND BUFFER SIZE GrblComm 155: ");
                return;
            }
            else
            {
                 String commandString = this.commandBuffer.pop();

LINE 164 is : this.commandBuffer.pop();
I do not understand this bug because there is a this.commandBuffer.size() test !!!!!
please, explain me !!!
EDIT FEB 25
Im gonna try to replace LinkedList by ConcurrentLinkedDeque
EDIT FEB 26
Same error :
java.util.NoSuchElementException
    at java.util.concurrent.ConcurrentLinkedDeque.screenNullResult(ConcurrentLinkedDeque.java:810)
    at java.util.concurrent.ConcurrentLinkedDeque.removeFirst(ConcurrentLinkedDeque.java:990)
    at java.util.concurrent.ConcurrentLinkedDeque.pop(ConcurrentLinkedDeque.java:1036)
    at GrblCommunicator.streamCommands(GrblCommunicator.java:167)
    at GrblCommunicator.responseMessage(GrblCommunicator.java:240)
    at ResponseMessageHandler.handleResponse(ResponseMessageHandler.java:33)
    at SerialConnectionJserial.serialEvent(SerialConnectionJserial.java:114)
    at com.fazecast.jSerialComm.SerialPort$SerialPortEventListener.waitForSerialEvent(SerialPort.java:1391)
    at com.fazecast.jSerialComm.SerialPort$SerialPortEventListener$1.run(SerialPort.java:1295)

Comment: Please edit your question and show us a [mre] which demonstrates an empty LinkedList whose `peek` method returns a non-null value.
Comment: how can `mylinkedlist` has a value to `peek` when its size is 0?
Comment: Because there is nothing in the list.
Comment: is this an implementation of or a pure LinkedList?
Comment: the question is not very clear: are you wondering why that happened (debugging question), or are you interested in some way to do that happen (more theoretical question)?
Comment: its a debugging question
Comment: Do you have a special implementation of `LinkedList` or can you ensure, that at the point, where the object is created, it is really a `java.util.LinkedList` that's being instantiated? I know that there are for example `Map` implementations that only return an estimate value, when calling `size()`.
Comment: Can you please display `System.out.println("Class: " + mylinkedlist.getClass().getName());`?
Comment: Let me explain : this code is for a CNC and stream command (linkedlist) to the CNC. Its a non-reproductible bug: It happen some time. I think it come from serial/usb communication noise. Whatever. To correct this bug by software adjustment i found this awesome thing: when bug = : peek() return a string value (command) but size is 0 (command list) .  So it throw a nullpointer. I can correct it, but i want understand why. Just why and how a peek() can return a value and in the same time the list size() returning 0 . Its non-sens.  I will add the getclass.getname to my next try .
Comment: mylinkedlist.getClass().getName() => java.util.LinkedList
Comment: @Ledahu Please add the "this code is for a CNC and ..." explanation to the question, it provides context. Are you running the code in some special JVM / computer for that CNC machinery, or is it running on a regular JVM (like the Oracle one)?
Comment: the bug appear again today ... its crasy . I edited with more code . please help . Its run JVM 1.8.0_231 , oracle
Answer: It is not possible for you to peek an item in a LinkedList AND have the size of it be zero. Think about what you're saying - "How can I look at this value and have the list have no values?". The reason for this is that peek() retrieves the first item in the list but does NOT remove it. However, you may be looking for pop() instead. Using pop() you can retrieve AND remove the first item at the same time. Per the documentation here "Pops an element from the stack represented by this list. In other words, removes and returns the first element of this list".
LinkedList<String> myList = new LinkedList<>();
myList.add("blablabla");
System.out.println("String: " + myList.pop() + ", Size: " + myList.size());

This prints out:
String: blablabla, Size: 0

Comment: yep. But its a debugging question . peek() return a value and size() is 0...
Answer: If you absolutely need to return a value when the size is 0, you have a few options.

Create your own LinkedList implementation
Catch the exception that will be thrown currently, and then return the value that you find appropriate for this scenario
Check the size of the linked list before calling .peek() and return the appropriate value instead of calling .peek() if the size is 0. If it is not 0, go ahead and make the call.
Answer: Implementation of peak() method for java.util.LinkedList says that "Retrieves, but does not remove, the head (first element) of this list."
So with java.util.LinkedList it's not possible.
You may have imported LinkedList from some other library other that "java.util.LinkedList"
Comment: If after reading the answers we are editing our questions, We shouldn't down vote at least those answers.
Answer: For now, the only explantation is in this thread
"A LinkedList is not thread-safe"
Thread safety issue
so i will use : LinkedBlockingQueue


vim plugin FuzzyFinderTextMate error

Question: I installed the vim plugin on many different ways. I try to start it with Ctrl-T but what I get is always that error:
E492: Not an editor command: FuzzyFinderTextMate
Comment: Please clarify "many different ways" - is the .vim file containing the plugin in a directory you know is having its contents sourced? From quick googling, it appears you also need a ruby gem - have you installed that appropriately as well?
Comment: That plugin should not map Ctrl+T as that is a tag navigation command. I've had version issues with that plugin in the past.
Answer: I was getting the same error "E492: Not an editor command: FuzzyFinderTextMate" with OS X 10.6.2.  It turns out the default vim installation in Snow Leopard was not compiled with ruby  support.  Once I recompiled vim with ruby support, the plugin worked as expected.
The installation steps that worked for me:

Compile Vim with Ruby using macports: sudo port install vim +ruby
Download fuzzyfinder.vim 2.16 to ~/.vim/plugin
Download fuzzy_file_finder.rb to ~/.vim/ruby
Download fuzzyfinder_textmate.vim to ~/.vim/plugin
Added the following line to ~/.vimrc: map <C-j> :FuzzyFinderTextMate<CR>

If you run into problems, check the original and update blog posts for help.
Comment: I do not think any version Of FuzzyFinder_Textmate is supported anymore. Karmen's answer of command-t is probably the correct answer now
Answer: command-t is the way to go now in my opinion. Works awesomely!!
https://wincent.com/products/command-t
Answer: I'm pretty sure this plugin has lost its original flair. Doesn't seem to work well. Read more: http://weblog.jamisbuck.org/2009/1/28/the-future-of-fuzzyfinder-textmate and https://wincent.com/blog/fuzzyfinder
Comment: It works well, it just takes some effort to find the versions of every required file that work well together. Have a look at github for fuzzyfinder_textmate and fuzzy_file_finder.rb:

http://github.com/jamis/fuzzy_file_finder/network
http://github.com/jamis/fuzzyfinder_textmate

The most recent versions work well with FuzzyFinder 2.22.3.
Comment: http://github.com/jonuts/fuzzyfinder_textmate - that version works well and includes the correct version fo fuzzy finder. It may not be maintained anymore, but it still feels like the best option to me.
Answer: This worked for me on 10.6.4:
Grab fuzzyfinder.vim and fuzzyfinder_textmate.vim from http://github.com/sethbc/fuzzyfinder_textmate.  Drop both of those into ~/.vim/plugin
Then grab fuzzy_file_finder.rb from github.com/jamis/fuzzy_file_finder and drop it into ~/.vim/ruby
In .vimrc, I added:
map <leader>t :FuzzyFinderTextMate<CR>

so "\t" (without the quotes) will launch, though you should map whatever feels best for you (see other answers/comments).
(My apologies for the dearth of links.  It seems I lack sufficient reputation to post more than one link.)

vim plugin FuzzyFinderTextMate error


Fail Install node-gyp rebuild on Ubuntu 20.04.2 LTS

Question: I'm trying to run a project in visual code, however whenever I npm install it results in this npm-gyp error, I already installed the latest version of node, npm, python, I also installed python 2.7 and nothing works, I already installed the components essentials, and even the pip.
user@ubuntu:~/testeGit/testeGitHub$ npm install
npm WARN deprecated firstname.lastname@example.com: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.

> email@example.com install /home/user/testeGit/testeGitHub/node_modules/sharp
> node-gyp rebuild

ERROR: https://dl.bintray.com/lovell/sharp/libvips-8.5.5-linux-x64.tar.gz status code 403
gyp: Call to 'node -e "require('./binding').download_vips()"' returned exit status 1 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/share/nodejs/node-gyp/lib/configure.js:355:16)
gyp ERR! stack     at ChildProcess.emit (events.js:198:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
gyp ERR! System Linux 5.8.0-59-generic
gyp ERR! command "/usr/bin/node" "/usr/bin/node-gyp" "rebuild"
gyp ERR! cwd /home/user/testeGit/testeGitHub/node_modules/sharp
gyp ERR! node -v v10.19.0
gyp ERR! node-gyp -v v6.1.0
gyp ERR! not ok
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.3.2 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for firstname.lastname@example.com: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules/watchpack-chokidar2/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for firstname.lastname@example.com: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN email@example.com No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! firstname.lastname@example.com install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/user/.npm/_logs/2021-06-25T01_34_27_616Z-debug.log

LOG:
Log_File_Here
Answer: node_modules/sharp is failing to build. You're using an OS that apparently doesn't have pre-built binaries for this node package.
https://sharp.pixelplumbing.com/install
Follow the build instructions, and in particular see the libvips section.
You may also want to try updating your package (you are using 0.18.4 whereas the latest is 0.28.3), as
https://dl.bintray.com/lovell/sharp/libvips-8.5.5-linux-x64.tar.gz
is returning a 403 Forbidden error, meaning either the author has changed the link or that host is no longer hosting it, or perhaps not sharing it to the public.


How do I get the pipboy app to connect to my Xbox one?

Question: I am trying to set-up the pipboy smart phone app. I can scan and find my console but it fails after I sign-in. I know I'm signing in correctly and once I do get past the sign-in screen, it gives me standard troubleshooting tips for the smart-glass, all of which I've followed but without success. I do have the Xbox smart-glass app as well, which works fine, so I'm not sure what is causing the problem here.
Comment: Just a sanity check, do you have 'Pip-Boy App Enabled' set to 'On' in the Gameplay section of the settings menu in Fallout 4?
Comment: It might matter what kind of phone you're using. I did this with my Samsung Galaxy S4 Active with no problem at all. You say the phone finds the console fine, so I assume your network setup is okay.
Comment: One thing to consider, having tried this, I noticed right away that although it may be cool to use the pip-boy app, using it as such does not pause the game like going into your in-game pip-boy does. You've been warned. :)
Answer: There are directions for this on Bethesda's website:

Open the game.
Navigate to Settings, then Gameplay.
Switch the "Pip-Boy App Enabled" option to On.

Exit and restart the game.


Redirect to a new tab within javascript file

Question: I have code that sets:
top.location.href = [someurl]

But I want it to open up in a new tab. Is there anyway to have the above code include: target="_blank"?
Answer: Use the method window.open(url, target) to open a new window (it depends on the browser or the user's settings whether the URL is opened in a new window or tab):
window.open('http://stackoverflow.com', '_blank');

For more information about window.open(), read the documentation at w3schools.
Please note: Randomly opening a new window (or tab) isn't allowed in most browsers, because it is then treated as an "unwanted popup".
Comment: @T.J.Crowder I'm sorry, you're absolutely right. Already changed the link.
Comment: _blank isn't necessarily required since it is the default.
Answer: If you're doing this in response to a user's action (such as a click), you can use window.open:
window.open("someurl", "_blank");

On most browsers with default settings, that will open a new tab rather than a new window. The user is, of course, in charge and can change the settings so it's a new window instead.
You cannot do this with a decent browser if it's not in response to a user's click, so that web pages cannot open tabs randomly.
Answer: Here is alternative for window.open - working example here (stackoverflow snippets not allow to opening)
let a= document.createElement('a');
a.target= '_blank';
a.href= 'https://example.com/';
a.click();

Answer: Use this code
 window.open ('URL', "_newtab" );

Comment: What does this answer provide that the other ones here have not?
Comment: The question is : what's the added value of using **_newtab** rather than **_blank** ? You just paste a JS line with no explanation. Stackoverflow desserve a better answer ! Thanks.
Comment:

Add the above code in a file , and run it on browser.
Comment: Can expand your answer, and link to some source about `_newtab` please


I want to make my frame close when the X(close button) is clicked

Question: I have a small template that ive built for the purpose of implementing an applet through a simple java application via netbeans 7.1 (as in not using Javacard, Netbeans Platform etc ..just a simple java application with applet initialized when application runs)
I have managed to make it invoke the applet when i press the run button in netbeans and i ahve functionality inside the applet but, i cant seem to get it to close and i have a horrible feeling people are gonna tell me to have used jFrame and implement the EXIT_ON_CLOSE method.
This is NOT something I would like to know how to do , my mission is to implement it using Frames != jFrames.
I hope someone can help as its bugged me for a bit now and i have to get on with Java assignment that involves its use.
Enclosed is the code/classes for A: the appletframe and B:the applet
    * 1.4   Write an applet to display a line of text.
    * The text should then change its font size and style (bold, italic, underline)
    * depending on where the mouse is clicked on the screen.
    */
   package appletframe;
   import java.awt.Graphics;
  import java.awt.Frame;
 import java.applet.Applet;

  /**
  * @author MuthaLoad aka Gruffy2012
  */

  import java.awt.*;

  public class AppletFrame extends Applet{

 public static void main(String[] args) {

/*construct needs object instances*/
MrApplet mrApplet = new MrApplet(); // create instance/obj of MrApplet
Frame myFrame = new Frame("Applet"); // create frame "title optional"
//setDefaultCloseOperation(myFrame.EXIT_ON_CLOSE);(jFrame- not wanted)

/* add applet to the frame*/
//myFrame.addWindowListener();
myFrame.add(mrApplet, BorderLayout.CENTER);
myFrame.setBounds(10,10,500,500);
myFrame.setVisible(true); // step to make frame visible

/*initialize instance of mrApplet*/
mrApplet.init();
} // end main
} // end class

B: applet
   package appletframe;

import java.awt.*; //for buttons
import java.awt.event.*; //for events
import java.applet.*; //main applet api`s
import java.awt.Graphics; //graphics

public class MrApplet extends Applet implements ActionListener
{

private static final long serialVersionUID = 1L;
Button btnClick;
String msg = "";

public void init()
{
    // TODO start asynchronous download of heavy resources
    setSize(500, 500);
    Button btnClick = new Button("Press Me ");
    btnClick.addActionListener(this);
    add(btnClick);
}
public void actionPerformed(ActionEvent e)
{
    //throw new UnsupportedOperationException("Not supported yet.");
    msg = "Yay, the button works";
            repaint();
}
public void paint (Graphics g)
{
    g.setFont(new Font("Serif", Font.ITALIC, 30)); //new font obj, font , font style, font size
    g.setColor(new Color(0,255,0)); //new color obj, r,g,b
    g.drawString(msg, 40, 80);

}
// TODO overwrite start(), stop() and destroy() methods
}

Once again thanks for reading, and to clarify any confusions..
I am looking for a pointer as to the solution of closing my applet and frame window upon exit , without reimplementing it all using jFrame, though i know this would be easier in the first instance.
Thankyou and as always, indebted to all your advice.
gruffy321
Comment: `EXIT_ON_CLOSE` is a constant, not a method.
Answer: add this line at the end of ApplicationFrame class.
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

You want to do it with Frame not with JFrame, then you have to add the WindowListener event to the frame and have to override windowClosing() method.
myFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
   System.exit(0);
});

Comment: Missing a  closing curly closing bracket just fyi
Comment: Yeah, now thanks for the super quuick response but like i stated , i simply do not want a jframe option (I know the API comes with simplifed access to very simple functions that have to be implemented manually using the frame (notjFrame)API). Thankyou anyway Chandra for bing so super quick
Comment: amazing thanks for super duper quick response again chandra, i wil go off and try this out now, cheers bud.. Gruffy
Comment: RE, YOUR EDITED RESPONSE>>>>>Well i have just tried and cant work out where the ")" should go, i have added it and moved it around but to no avail, also tried adding and extra "}" to close it but hasnt worked either, I SEEM TO BE MISSING SOMETHING HERE HUH.


Entity Reference and Views: how to implement the "Referencing entity" relationship

Question: I've got a main content type: "tournament", and a number of complimentary content types, e. g. "news", "judges", "participants".
A piece of news may relate to one or more tournaments or not relate to any tournaments.
<code>Node type: News
Has field: Relevant Tournament(s)
                ↓
Node type: Tournament
</code>
The relation between tournaments and news should be set when creating a piece of news: you write news title, news contents and tick the relevant tournaments. So it's the complimentary node type that has the entity reference field.
On each tournament's page there should be a block that displays news relevant to the displayed tournament.
What i tried:

Created a Block View and put it to tournaments' pages.
Added a Contextual filter that retrieves tournament's Nid from URL.
Added an EntityReference Relationship (either "Referencing or "Referenced").
Set Format Style to Unformatted + Rendered Entity.
Attached either of Relationships to the Rendered Entity Format Style.
Also tried attaching Relationships to the Contextual filter.

But i failed to achieve the desired result.
I found a guide that might be relevant to my issue. But i failed to understand it because it involves PHP-hacking and is very Commerce-specific.
Answer: Okay, i got it figured out.
It wasn't working while i was using the "Rendered entity" Format Style.
When i changed to "Content" format style, it started working.
A complete recipe for reverse Views Entity Reference can be found here: http://drupal.org/node/1724396#comment-6406274
Comment: What I want to know is WHY it doesn't work in "rendered entity" format and how to make it work....? Any thoughts?
Answer: You can also check http://drupal.org/project/content_dependency
It provides automatic reversed referrals previews of different entity types.
Answer: Maybe an obvious question/answer:
Did you add a the "Content:rendered node" field to the fields of your view? You can refer to your Entity Reference Relationship (either "Referencing or "Referenced") in this field.
This might do the trick.. Otherwise, good luck!
Comment: I didn't use Fields, i used "Rendered entity" as a Format Style in the first place.


ReactJS: Pngquant failed to build, make sure that libpng-dev is installed

Question: I am trying to setup a react project. It has lot of dependencies and while downloading one of module it is throwing this error. This is on windows.
pngquant failed to build, make sure that libpng-dev is installed
Output:
‼ unable to get local issuer certificate
 pngquant pre-build test failed
 compiling from source
 pngquant pre-build test passed successfully
 Error: pngquant failed to build, make sure that libpng-dev is installed
Comment: If you have a package.json file , then try npm install , it will install all the dependencies
Comment: Got it fixed. Had version mismatch issues.
Comment: sudo apt install -y build-essential gcc make libpng-dev helped me
Comment: I fix it with https://stackoverflow.com/questions/49308545/error-with-npm-update-pngquant-binary-does-not-seem-to-work-correctly
Answer: You didn't installed lib-png so that error is coming.Try to install lib-png first.
sudo apt-get install libpng-dev
npm install -g pngquant-bin

Comment: for windows try npm install --save-dev pngquant --msvs_version=2013 this one
Comment: I am trying to do it on windows.
Comment: Had to fix my versions. Node 8.11 npm 5.6 yarn 1.6
Comment: I have the same error with node 8.12 and npm 6.4.1, tried Mukesh's solution but it does not work
Answer: To expound more on @Mukesh's answer.
I experienced this issue when building a react project that uses the imagemin-pngquant package.
When I run npm install on the server I get the below error:
pngquant pre-build test failed
compiling from source
pngquant pre-build test passed successfully
Error: pngquant failed to build, make sure that libpng-dev is installed

Here's how I fixed it:
Install libpng-dev package on your machine/server:
sudo apt-get install libpng-dev

Add pngquant-bin package to your npm packages in the package.json file (if it doesn't yet exist):
"dependencies": {
  .
  .
  .
  "imagemin-pngquant": "^9.0.1",
  .
  .
  .
}

OR
Run the command to install the pngquant-bin package:
npm install imagemin-pngquant --save // to install the latest

OR

npm install firstname.lastname@example.com --save // to install a specific version

Note: You can try npm install firstname.lastname@example.com --save if you encounter issues with the latest version.
Now everything should be fine if you install the npm packages and build the project again using:
npm install
npm run build

That's all.
I hope this helps
Answer: I faced the same issue:
Solution
Step 1
sudo apt-get update -y

Step 2
sudo apt-get install -y libpng-dev

These two steps sorted out my issue and working fine.
Answer: On Ubuntu you can try to fix it with apt-get install -y libpango1.0-dev command, worked for older node v6
Comment: This was the fix for me on an old Vagrant box. Looks like it's expecting this or another dependent library but gives the "be sure libpng-dev is installed" error as a default message.
Answer: This worked for me on Windows:

Run Windows PowerShell as Admin
npm install --global --production windows-build-tools

If you have made any previous npm installation attempt which you most likely had, clean everything and then do a fresh dependency installation:

rm node_modules -R
rm package-lock.json
npm install

Good luck!


Can Database be count as actor in use case diagram?

Question: I am creating application for Diabetes log system. I am confused whether database in UML -Use case diagram count as actor or not ?
the application is recording the diabetes glucose reading which will be saved in firebase and it can also retrieve the readings for showing the progress in chart format.
please can someone help me?
thank you.
Comment: Make it a new question please. And a bit more context too.
Comment: You need to elaborate on the database's role. Without that information you can not get a valid answer.
Comment: sorry, the application is recording the diabetes glucose reading which will be saved in firebase and it can also retrieve the readings for showing the progress in chart format.
Comment: Ok. In that case the given answer "no" applies.
Comment: sorry another question, I am going to create a page for displaying progress as line graph will that be <> or <> to database ??
Answer: No, databases should not be included in a Use Case Diagram of an isolated system. Databases are a static internal part of a system and do not directly take part without a front interface (i.e. your system itself).
However, if your database is an external entity i.e. it is being shared between different systems then maybe it would be wise to show it as an actor.
Comment: Hi Rohan, could you provide clarification on your second point? Aren't actors supposed to be those only that use a system's functionality? Could you provide some reading suggestions?
Answer: That depends on what use case diagram are you working on. UML standard does not attach diagrams to levels of abstraction.
You can create a use case for the behaviour of the whole product with the whole surrounding system and all human users - from the point of view of an external user. And you can create it for a better explanation of behaviour of a small sub-sub-subsystem.
In the first case, even the main application won't appear as an agent or meant as a subject. In the second case, if that subsystem works with DB, DB will be an agent.
UML is a free enough standard and rarely strictly forbids something.


ssh: connect to host myremotehost.com port 22: Connection refused

Question: So I am trying to get ssh working on my server. I can connect on my local network with the local ip address of the server perfectly fine. When I try to connect remotely (through a domain name that I set-up for the server, which I know works) I get this connection refused error:
ssh: connect to host bahhudson.mine.nu port 22: Connection refused

From the research I have done into the problem it looks like something is going wrong with my router. I have configured port-forwarding, but that's the only think I can think is causing the "Connection Refused" error... My router is a WRT120N and I have configured it for port-forwarding based on Portforward.com, which seems somewhat outdated since some of those images are not exactly like what my router settings look like, but I have tried multiple ways for setting the portforwarding up, and I know that forwarding for port 80 works because my server has HTTP access which is working...
Also VPN access was getting blocked in what I believe to be a similar way, so the solution to the SSH port 22 being blocked might also be similar to that of the VPN being blocked as well.
Any ideas?
Thanks!
Answer: Just to share.
(might be with different configuration)
In my case, I found that that error can happen because I have not install openssh-server in the other machine.
After I install openssh-server in the other machine, the problem:
ssh: connect to host 192.168.XXX.XXX port 22: Connection refused

is solved.
Comment: It seems silly to forget this but it was my case! This answer should be the first check before trying other tricks
Comment: Same case with me. I have not installed in my host computer ssh sevice (`sudo apt install openssh-server`). Once did, `ssh-copy-id -i id_rsa.pub firstname.lastname@example.com` did not throw any error. I ws copying ssh key to the host in from the Docker container it was hosting using ssh.
Answer:
First check openssh-server installed in that system.

check the status of ssh service, make ssh service start.
 sudo service ssh status
 sudo service ssh start

Check whether port 22 in that system is blocked by iptables. Just allow port in iptables and then check.
 sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT

Else change port number of ssh from 22 to 2222 by editing
 vi /etc/ssh/sshd_config
 /etc/init.d/ssh restart.

Comment: Thanks! It worked for me! This should be the accepted solution!
Comment: in my case ssh was failing while starting the service. This error was the output: `sshd: no hostkeys available -- exiting` and this was the fix: `ssh-keygen -A`
Answer: Your ISP may block connections to port 22 (nothing you or your router can do about it). Just set SSHd to run on a different port, e.g. 2222.
In /etc/ssh/sshd_config, change Port 22 to Port 2222 and then sudo service ssh restart. Port forward 2222 (or whatever), and try again.
Comment: Just try this: **Incoming 2222** on router has to forward to 2222 (with port 2222 set in `sshd_config`).
Comment: I still get the same connection refused error (22 when I don't specify a port when using ssh and 2222 when I use -p 222). I put incoming port 22 to forward to 2222 and changed the port to 2222 in sshd_config. Am I leaving out something?
Comment: @izx kudos for the router rules. At some point I thought that I was freaking out and don't know what I'm doing. LOL!
Comment: For future readers. Make sure that you are referring `/etc/ssh/sshd_config` (notice ssh**d**) file. After pulling my hair for an hour I came to know this small difference. ;P
Comment: My new router uses port 22 for it's remote administration feature and doesn't list it anywhere on the interface, so it may not necessarily be the ISP.
Comment: I am using Google Cloud Shell and no matter what I try the error is the same.
Answer: I solved this problem by reinstalling openssh-server as follows:
sudo apt-get purge openssh-server
sudo apt-get install openssh-server

Comment: On client or server ? Sorry, I don't know much.
Comment: On client......
Answer: Check the SSH service status and start the SSH service if it is stopped:
sudo service ssh status

In my case SSH was stopped, but after starting the service:
sudo service ssh start

I can be able to remote login to Linux.
Answer: I got the same error, but, after restarting my computer, everything worked again.
So, you may want to give it a try before reinstalling some components.
Answer: The other likely cause is that the proxy in between the terminal-session and the host-server needs userid-password access, that it is rejecting to allow the traffic flow, this is due to a network-firewall or ssl-socks etc.
Comment: This does not seem like a 'likely cause', especially given the accepted answer.
Answer: The solution will be by adding the port number of your server preceded with "-p":
Example of the command line:
ssh -L localport:127.0.0.1:localport username@ServerIP **-p** **serverport**

Answer: Just go to whm then  open Host Access Control
Change as follows
sshd ALL allow
Answer: If it's your own private server, your best course of action is to start simple and not complicate things. Since you cannot access your machine via SSH, you can login to your provider hosting the Ubuntu server and reboot the machine from there. After rebooting, try logging back in via console (or putty) with ssh user@ip-address again.


Length of a segment in a triangle and tangent of an angle

Question: Given $\Delta$$ABC$ with $AB$$\bot$$BC$, $BD$ is the altitude to $AC$, $AF$ bisects angle $BAC$, $AP=12$ , and $PF=8$. Find $\tan(\angle BAF$) and find $PD$.

Efforts made: I've tried to apply angle bisector theorem but i couldn't get anything usefull ,and i've also tried to add some lines such as $FD$ but it didn't help me much though.
Note: I don't want the solution to the problem,only hints.
Thanks in advance.
Answer: Let $BC=a,CA=b,AB=c$.

I don't want the solution to the problem,only hints

I think you can get the answers using the followings :

Since $AF$ bisects angle $BAC$, we have $AB:AC=BF:FC$ from which we can represent $BF,FC$ by $a,b,c$.
The area of $\triangle{ABC}$ equals $\frac 12\times AB\times BC=\frac 12\times BD\times AC$ from which we can represent $BD$ by $a,b,c$.
Since $\triangle{DAP}$ is similar to $\triangle{BAF}$, we can represent $DA$ by $c$.
Since $\triangle{CBA}$ is similar to $\triangle{CDB}$, using $b^2-a^2=c^2$, we can represent $c$ by $b$, and $a$ by $b$ from which we can get $\tan(\angle{BAF})$.
Having $\cos(\angle{BAF})$ leads to $c$ and $PD$.
Comment: @Jhon: Since $c:b=BF:FC$, i.e. $c:b=a-FC:FC$, we have $FC=\frac{ab}{b+c}$.
Comment: Thanks for the hints,one question: From your first hint  how can you represent $FC$ by $a,b,c$ ?
Answer: HINTS:
Length of angle bisector at angle $  $A$ = \dfrac {2 b c }{ b+c} \cos A/2, $ with opposite sides $BD$ and $ BC$,
Similarity of triangles within a right angled triangle with results like $ AB^2 = AD\cdot AC, $
and, algebraic manipulations.
RESULTS:
$ \tan BAF = \frac12 $
$ PD\approx  5.36656.$


Deleting a file based on disk ID

Question: As described here, using SetFileInformationByHandle with FILE_DISPOSITION_INFO
allows one to set a file with an open handle to be deleted upon all handles being closed.
However, I am trying to delete a file based on its file index (disk ID) retrieved by FILE_DISPOSITION_INFO and
OpenFileById in order to safely delete files/directories in a directory which differ only in case.
This is safe to do in my use case, as on an NTFS system, file indexes are persistent until deletion,
negating the use of ReplaceFile, which the current codebase handles.
However, when attempting to delete the handle, I get error 87 (ERROR_INVALID_PARAMETER).
If I delete using a handle created with CreateFileW, I run into no problems.
I can't do this, though, as Windows will not be able to distinguish between two file/folders of the same case, even though NTFS can.
I am also aware that there is an ambiguity with hardlinked files opened with OpenFileById,
as hardlinked files share the same disk ID.
The issue of hardlinked files can be considered irrelevant for this scenario.
I will only be deleting directories by ID, which cannot be hardlinked.
Is there a parameter or setting I am missing in my OpenFileById call?
Somehow, in my SetFileInformationByHandle call?
Additional methods I have tried:

Calling DuplicateHandle with the OpenFileById handle, providing DELETE for dwDesiredAccess, and using that.
Same ERROR_INVALID_PARAMETER result.
Using ReOpenFile with the OpenFileById handle, providing DELETE for dwDesiredAccess, and using that.
Same ERROR_INVALID_PARAMETER result.
Using ReOpenFile with the OpenFileById handle, providing DELETE for dwDesiredAccess, and providing the FILE_FLAG_DELETE_ON_CLOSE flag.
No error is given, but the file remains after all handles are closed.

Here is a minimal, yet complete, example which reproduces the problem:
#include <stdio.h>
#include <sys/stat.h>
#include <Windows.h>

DWORD getFileID(LPCWSTR path, LARGE_INTEGER *id)
{
    HANDLE h = CreateFileW(path, 0, 0, 0, OPEN_EXISTING,
        FILE_FLAG_OPEN_REPARSE_POINT |
        FILE_FLAG_BACKUP_SEMANTICS |
        FILE_FLAG_POSIX_SEMANTICS,
        0);
    if (h == INVALID_HANDLE_VALUE)
        return GetLastError();

    BY_HANDLE_FILE_INFORMATION info;
    if (!GetFileInformationByHandle(h, &info))
    {
        DWORD err = GetLastError();
        CloseHandle(h);
        return err;
    }
    id->HighPart = info.nFileIndexHigh;
    id->LowPart = info.nFileIndexLow;
    CloseHandle(h);
    return ERROR_SUCCESS;
}

DWORD deleteFileHandle(HANDLE fileHandle)
{
    FILE_DISPOSITION_INFO info;
    info.DeleteFileW = TRUE;
    if (!SetFileInformationByHandle(
        fileHandle, FileDispositionInfo, &info, sizeof(info)))
    {
        return GetLastError();
    }
    return ERROR_SUCCESS;
}

int wmain(DWORD argc, LPWSTR argv[])
{
    if (argc != 3)
    {
        fwprintf(stderr, L"Arguments: <rootpath> <path>\n");
        return 1;
    }

    DWORD err;
    HANDLE rootHandle = CreateFileW(
        argv[1], 0, 0, 0, OPEN_EXISTING,
        FILE_FLAG_OPEN_REPARSE_POINT |
        FILE_FLAG_BACKUP_SEMANTICS |
        FILE_FLAG_POSIX_SEMANTICS,
        0);
    if (rootHandle == INVALID_HANDLE_VALUE)
    {
        err = GetLastError();
        fwprintf(stderr,
            L"Could not open root directory '%s', error code %d\n",
            argv[1], err);
        return err;
    }

    LARGE_INTEGER fileID;
    err = getFileID(argv[2], &fileID);
    if (err != ERROR_SUCCESS)
    {
        fwprintf(stderr,
            L"Could not get file ID of file/directory '%s', error code %d\n",
            argv[2], err);
        CloseHandle(rootHandle);
        return err;
    }
    fwprintf(stdout,
        L"The file ID of '%s' is %lld\n",
        argv[2], fileID.QuadPart);

    FILE_ID_DESCRIPTOR idStruct;
    idStruct.Type = FileIdType;
    idStruct.FileId = fileID;
    HANDLE fileHandle = OpenFileById(
        rootHandle, &idStruct, DELETE, FILE_SHARE_DELETE, 0,
        FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS);
    if (fileHandle == INVALID_HANDLE_VALUE)
    {
        err = GetLastError();
        CloseHandle(rootHandle);
        fwprintf(stderr,
            L"Could not open file by ID %lld, error code %d\n",
            fileID.QuadPart, err);
        return err;
    }

    err = deleteFileHandle(fileHandle);
    if (err != ERROR_SUCCESS)
    {
        fwprintf(stderr,
            L"Could not delete file by ID '%lld', error code %d\n",
            fileID.QuadPart, err);
    }

    CloseHandle(fileHandle);
    struct _stat _tmp;
    fwprintf(stdout,
        L"File was %ssuccessfully deleted\n",
        (_wstat(argv[2], &_tmp) == 0) ? L"not " : L"");
    CloseHandle(rootHandle);
    return err;
}

Any solution must work with Vista and above. Suggestions for code improvement are also welcome.
Comment: SWAG: As dumb as it sounds, might you not need to include POSIX_SEMANTICS on the OpenFileById call to get a "compatible" handle? Yeah - I know the POSIX_SEMANTICS nominally only has to do with file names...but there are dumber things in the world. @HarryJohnston mentioned the ERROR_INVALID_PARAMETER - maybe internally, it's "grossly" comparing flags.
Comment: For the record, the [documentation here: File System Behavior Overview (PDF)](http://download.microsoft.com/download/4/3/8/43889780-8d45-4b2e-9d3a-c696a890309f/File%20System%20Behavior%20Overview.pdf) confirms (section 4.3.2) that you can't set the delete-on-close flag for a handle that was opened by ID.
Comment: Try using DuplicateHandle on the handle you get from OpenFileById, with `dwDesiredAccess` set to `DELETE`.
Comment: @HarryJohnston Good idea, unfortunately didn't work. I've edited the question to include what I've tried so far.
Comment: Presumably the system kernel is configured to be case sensitive, or you wouldn't have such files in the first place; I take it using NtCreateFile isn't an option?
Comment: @HarryJohnston The files were created in Linux. Theoretically, the program should also be able to work with files with invalid names if it can delete by disk ID.
Comment: It doesn't look like it can, though.  The problem presumably being that a disk ID identifies a file rather than a directory entry, and you can only delete a directory entry.  Granted removing a directory by disk ID would be possible in principle since in NTFS a directory can't be hard linked, it doesn't look like Windows actually supports doing so.  I think you'll need to [set obcaseinsensitive to zero](https://technet.microsoft.com/en-nz/library/cc725747.aspx) and use the kernel API.
Comment: Alternatively, if you don't need to keep the conflicting names, it should be possible to rename them one at a time - presumably if you open a file by name when there are multiple matches you get a handle to one of them at random?
Comment: @HarryJohnston Unfortunately, this will be used on machines where setting kernel settings  and restarting would be impossible. As far as I can tell in my experimentation, opening a file by name when there are multiple matches opens the one with the first filename when sorted, so capitals first.

It's confusing that using [GetFinalPathNameByHandle](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364962(v=vs.85).aspx) gives the first hardlink path of a file.

I have absolutely no experience in Windows kernel development. If I could use the POSIX subsystem simply, this would be easy.
Comment: I gather the POSIX subsystem no longer exists in the newest Windows releases, so no help there.  There's still an NFS server so that's a potential option, but not available on all editions of Windows.  What about renaming them so they don't conflict?  If there are only two directories with matching names, and you want to remove one of them anyway, that should work perfectly - you don't need to be able to predict which one will wind up with which name, as you can check the file IDs.  Another thought: could you mount the file system in question in a VM?
Comment: @HarryJohnston The primary restriction is that is must work on Vista+ with default configurations, and be capable of running in the background. So, no NFS, no installations, and no reboots. A problem I see with renaming is that when a child of a directory is locked, the directory cannot be renamed (IIRC). The strange thing is I'd expect `SetFileInformationByHandle` to return `ERROR_INVALID_HANDLE` if the handle was incapable. It's also possible to find the first file path of a `OpenFileById` handle. Lastly, renaming simply wouldn't work for paths with "invalid" characters, like ``\`` or `*`.
Comment: OK, so POSIX wouldn't have helped in the first place, never mind then.  I'm not sure why a Linux directory would be in use while Windows has the file system mounted, but if it is you won't be able to rename it.  You hadn't mentioned invalid characters before, I'm not sure you can do anything with such a file in Windows even via the kernel, I think you would have to dismount the file system and manipulate it directly.  Given all your requirements, I think the answer is simply that this isn't possible.  Someone else might have a clever idea though, so good luck.
Comment: (Forgot to mention, `ERROR_INVALID_HANDLE` is typically only used if the handle you pass isn't actually a handle or is a handle to the completely wrong kind of object, e.g., calling SetEvent on a file handle.  Using a handle of the right sort but that lacks the necessary properties typically produces `ERROR_INVALID_PARAMETER` or `ERROR_ACCESS_DENIED`.  For example, calling DeleteFile on a directory produces `ERROR_ACCESS_DENIED`.)
Comment: @HarryJohnston In a dual-booted system with Linux, mounting an NTFS partition opens it in "POSIX mode", where the only restrictions are that a path cannot contain `NUL` or `/`. A music manager that edits paths would add `:` to some song files. The paths allowed by Windows are a subset. Using a POSIX namespace (without installation) would fix this when files created in Linux are attempted to be deleted in Windows, but I don't see how. The peculiar thing is that you can use `GetFinalPathNameByHandle` and still get the name of the first hardlink of a file opened by ID, even the path is invalid.
Comment: Hmmm.  It might (or might not) be possible to manipulate the files by passing the relevant control codes directly to the NTFS driver, bypassing the kernel's file system support.  But it would probably have to be done from a device driver, not an application.  (It might not need to be a kernel-mode device driver necessarily.)  It would definitely be challenging for anyone without device driver (and preferable file system driver) experience.
Comment: If you're not *too* concerned with performance, you might try `NTQueryInformationFile` querying for `FILE_NAME_INFORMATION`, which takes the file handle and returns a full path to the file, which you can turn around and open with `CreateFile()`. In such a case, you might still want to use POSIX_SEMANTICS to ensure you're getting compatible behavior by the underlying subsystem when you open the file w/ OpenFileById()
Comment: @Clay `OpenFileById` does not take the `FILE_FLAG_POSIX_SEMANTICS` flag. Also, querying for the filename will still fail if the filename is invalid/differs only in case.
Comment: @HarryJohnston Thank you for (as far as I can tell) *officially* confirming this is unsupported by Microsoft. Is there any other option you know to guarantee the deletion of a file with incredibly unusual names? Is there everywhere-installed access to the POSIX subsystem hanging around somewhere I can't find?
Comment: I wouldn't necessarily know if there was, but it seems unlikely.  Windows doesn't generally support that sort of edge case out of the box.
Answer: There's a user mode version of the kernel mode ZwCreateFile called NTCreteFile which, among other things will give you all of the access rights you can't get with OpenFileById (but you can get with CreateFile). It can do everything CreateFile can do and more. For example, it can even create directories.
The good part is, there's an immensely hacky (but entertaining) way of specifying a file ID in the POBJECT_ATTRIBUTES argument as well, so you get the best of all worlds...except that it's an even more awkward API to call than your run-of-the-mill awkward Windows APIs.
There are two versions of the documentation. One at:
https://msdn.microsoft.com/en-us/library/bb432380(v=vs.85).aspx
and one at:
https://msdn.microsoft.com/en-us/library/windows/hardware/ff556465(v=vs.85).aspx
...which links to the ZwCreateFile documentation at:
https://msdn.microsoft.com/en-us/library/windows/hardware/ff566424(v=vs.85).aspx
The reason I point this out is that the first article omits some of the goodies (like opening files by ID) that are documented in the last article. I have found this to be common and have also found that most of the documented Zwxxx functionality actually does exists in the equivalent, but incompletely documented NTxxx functions. So you gotta hold your mouth just right to get the requisite functionality.
Answer: In order to make FILE_DISPOSITION_INFO work you need to specify the DELETE access in the CreateFile function as reported in https://msdn.microsoft.com/en-us/library/windows/desktop/aa365539(v=VS.85).aspx:

You must specify appropriate access flags when creating the file
  handle for use with SetFileInformationByHandle. For example, if the
  application is using FILE_DISPOSITION_INFO with the DeleteFile member
  set to TRUE, the file would need DELETE access requested in the call
  to the CreateFile function. To see an example of this, see the Example
  Code section. For more information about file permissions, see File
  Security and Access Rights.
  I.e.

//...
  HANDLE hFile = CreateFile( TEXT("tempfile"),
                             GENERIC_READ | GENERIC_WRITE | DELETE,  //Specify DELETE access!
                             0 /* exclusive access */,
                             NULL,
                             CREATE_ALWAYS,
                             0,
                             NULL);

But it seems that an handle created with OpenFileById() cannot be used because the function cannot accept the DELETE flag.
From https://msdn.microsoft.com/en-us/library/windows/desktop/aa365432(v=vs.85).aspx on OpenFileById() it can be read:
dwDesired

Access [in]
     The access to the object. Access can be read, write, or both.

Even setting DELETE or GENERIC_ALL the function fails.
If you replace the handle passed to SetFileInformationByHandle with one created with the CreateFile function having the DELETE flag set, as above, it works.
Comment: `CreateFile` is not being used to create the handle that `FILE_DISPOSITION_INFO` is being used on, `OpenFileById` is. `GENERIC_ALL` was used for access, which includes delete. Replacing it with `GENERIC_READ | GENERIC_WRITE | DELETE` makes no difference.
Comment: I already know using `CreateFile` works, as described. This still has the problem of file paths not being unique with `CreateFile`. Is it possible to delete a file by disk ID in general, or reliably delete two files which differ only in case, if one is a file and the other a directory?
Comment: MS file system is not case sensitive, so in general the answer is no. I have checked what for me is the last chance: using `ReOpenFile` to reopen the flie created with `OpenFileById` adding the `DELETE` flag, but also this solution doesn't work :(
Comment: The problem is NTFS is case sensitive but Windows is not. Good idea on `ReOpenFile`, sad it didn't work. FindNextFile and similar methods still see them as separate files, however.
Comment: It seems that `OpenFileById` is crafted for internetwork files, so have a limited access to the real file. Maybe there is a function to change something on the opened file. Not one of the most used, nor one that I could recall. Maybe you want search in that direction something like `ReOpenFile`...
Answer: Have you looked into FILE_FLAG_POSIX_SEMANTICS? It will allow you to open files that differ only in case using CreateFile.
Edit: I guess I should have read your code first as I see you are using said flag.
Comment: Doesn't work. Have you tried it yourself? Also fails with invalid names.
Comment: I'm trying your sample right now and I can reproduce the behavior. I guess my question to you now is which part do you want to get working, deleting files that differ only in case or deleting files opened by ID?
Comment: Deleting files opened by ID, one benefit being able to delete files which differ only by case, as well as invalid filenames, such as those that contain `:`. `FILE_FLAG_POSIX_SEMANTICS` also does not work as described if the kernel is not currently case insensitive, which is the default. If you can form a code sample which you verify works, that might be useful.
Answer: Assume the files are XXX and xxx and you want to delete XXX.

MoveFile("XXX", "I think it's XXX")
If XXX got renamed, then DeleteFile("I think it's XXX")
Otherwise, DeleteFile("XXX"); MoveFile("I think it's XXX", "xxx")

As to OpenFileById, as you noted, there is a potential ambiguity with a file with multiple names (aka hard links). Allowing DELETE access could cause havoc with this, with an unexpected name being deleted (if it were left to the file system to select which one). I suspect they opted for the simple case of never letting DELETE access be granted.
A similar argument could be made for allowing hard links to directories.  Sure, you could do it some of the time correctly, but once you created a cycle, things get a lot tougher...

Deleting a file based on disk ID


How do I unlock Pichu and Mewtwo in Super Smash Bros. Melee?

Question: Hey I got SSBM for Christmas and I want to know how to unlock Pichu and Mewtwo! You may be thinking "Just google it, kid." but the reason I'm asking here is, I want to hear it from a trusted source!
The reason I want Mewtwo is, it's my favorite Pokemon! And I want Pichu so I could record the "1 Stock, Hardest Difficulty, as Pichu." Why not any other character you ask? Pichu is lowest on the Tier List, meaning I record the HARDEST THING IN MELEE!
Comment: Related: [Methods to unlocking Mewtwo in Melee](http://gaming.stackexchange.com/questions/211873/methods-to-unlocking-mewtwo-in-melee?rq=1). Explains in detail the unlocking of Mewtwo
Answer: For Pichu, complete event 37.
For Mewtwo, play VS for over 20 hours.
There are also a certain number of matches you can play that is an alternate condition for unlocking them.
Comment: Partially incorrect on Mewtwo. Unlocking Mewtwo requires 20 hours of *cumulative* human player time in VS matches. Additional players means less total time is necessary - with a full 4 human players in VS it only takes 5 hours.
Answer: For mewtwo You can simply start a 99 minute VS match and go eat something, then come back 99 minutes later.
Or if you have 2 controllers you can just start a stock match without time limit and go to sleep.
For pichu event 37 has to be completed. Use a heavy hard hitting character like ganondorf.
Answer: For Pichu, You can either Play 200 VS. Battles or Clear Event #37 Legendary Pokémon.
For Mewtwo, You can either Play 700 VS. Battles or Play VS. for a combined total of 20 hours. If you use 2 controllers 1p vs. 2p in a1 stock match, you have to wait 10 hours, for 3 controllers its around 6.5 hours. For 4 controllers it's 5 hours.


why shouldShowRequestPermissionRationale not work?

Question: how can use shouldShowRequestPermissionRationale before call permission and use in Activity.
because before ActivityCompat.requestPermissions this return false
if(ActivityCompat.shouldShowRequestPermissionRationale(context,permission)){
    // true
}else{
    // false (always false)
}

Comment: use this for request permission its awesome  https://stackoverflow.com/a/49201404/9130109
Answer: The method shouldShowRequestPermissionRationale returns true if it is required to explain the user why the permission is required. In the first time the permission is requested, this method returns false.
But if the user denies the permission once, when the permission is requested another time, this method returns true because it might be a good idea to explain the user why this permission is required for the app.
When the permission is already granted, this method will return false.
So a good practice would be to first check what this method returns and if it is required to explain to the user, explain it using a dialog or something followed by requesting the permission, otherwise ask the permission directly.
You can also have a look at my library which ease up this whole process and other processes regarding run-time permissions.
Answer: Addition info:
Some case must use correct mapping permission requested and permission use to check shouldShowRequestPermissionRationale.
In my case, I had used permission "granular media permissions" of Android 13 (READ_MEDIA_IMAGES/READ_MEDIA_AUDIO/READ_MEDIA_VIDEO) on device Android 10 and function shouldShowRequestPermissionRationale alway return false.
When i try use READ_EXTERNAL_STORAGE, it' working and return true when use not have choose "Never ask again"
So let try old basicly permission before try another permission.
Good luck!


Android TV Play Video from URL

Question: I would like to play a MP4 video from a URL in my Android TV app.
I couldn't find an example in the Sample code (https://github.com/googlesamples/androidtv-Leanback).
Does anyone know how to do that?
Do I need to create my own Activity or is there a standard one in the leanback support library?
Answer: The androidtv-Leanback example already includes video playback.
If you take a look at the PlaybackOverlayActivity, you will see that the VideoView class is used to play sample videos (you can find the documentation here).
However, there is no standard component in the Leanback support library, so you will have to define an Activity yourself.
Comment: Wow. That seems really complicated for just playing a video and some controls... Have you done any app with this kind of video playback?
Comment: I don't think it's that complicated (in terms of code quantity and complexity). Usually, video playback involves quite a lot of work. For the controls part, the `PlaybackOverlayFragment` widget does a great part of the heavy lifting for you (see here: https://developer.android.com/reference/android/support/v17/leanback/app/PlaybackOverlayFragment.html)
Comment: Yeah I was finally able to copy paste `PlaybackOverlayFragment` and `PlaybackOverlayActivity` and tweak it a little bit to make it work in my app. Thanks for the help.

Android TV Play Video from URL


Elasticsearch aggregations: how to get bucket with 'other' results of terms aggregation?

Question: I use aggregation to collect data from nested field and stuck a little
Example of document:
<code>{
  ...
  rectangle: {
    attributes: [
      {_id: 'some_id', ...}
    ]
}
</code>
ES allows group data by rectangle.attributes._id, but is there any way to get some 'other' bucket to put there documents that were not added to any of groups? Or maybe there is a way to create query to create bucket for documents by <code>{"rectangle.attributes._id": {$ne: "{currentDoc}.rectangle.attributes._id"}}</code>
I think bucket would be perfect because i need to do further aggregations with 'other' docs.
Or maybe there's some cool workaround
I use query like this for aggregation
<code>"aggs": {
  "attributes": {
    "nested": {
      "path": "rectangle.attributes"
    },
    "aggs": {
      "attributesCount": {
        "cardinality": {
          "field": "rectangle.attributes._id.keyword"
        }
      },
      "entries": {
        "terms": {
          "field": "rectangle.attributes._id.keyword"
        }
      }
    }
  }
}
</code>
And get this result
<code>"buckets" : [
  {
    "key" : "some_parent_id",
    "doc_count" : 27616,
    "attributes" : {
      "doc_count" : 45,
      "entries" : {
        "doc_count_error_upper_bound" : 0,
        "sum_other_doc_count" : 0,
        "buckets" : [
          {
            "key" : "some_id",
            "doc_count" : 45,
            "attributeOptionsCount" : {
              "value" : 2
            }
          }
        ]
      }
    }
  }
]
</code>
result like this would be perfect:
<code>"buckets" : [
  {
    "key" : "some_parent_id",
    "doc_count" : 1000,
    "attributes" : {
      "doc_count" : 145,
      "entries" : {
        "doc_count_error_upper_bound" : 0,
        "sum_other_doc_count" : 0,
        "buckets" : [
          {
            "key" : "some_id",
            "doc_count" : 45
          },
          {
            "key" : "other",
            "doc_count" : 100
          }
        ]
      }
    }
  }
]
</code>
Answer: You can make use of missing value parameter. Update aggregation as below:
<code>"aggs": {
  "attributes": {
    "nested": {
      "path": "rectangle.attributes"
    },
    "aggs": {
      "attributesCount": {
        "cardinality": {
          "field": "rectangle.attributes._id.keyword"
        }
      },
      "entries": {
        "terms": {
          "field": "rectangle.attributes._id.keyword",
          "missing": "other"
        }
      }
    }
  }
}
</code>


Selecting same item in 2 different Grid-Views

Question: I have 2 RadGridView.
GridView 1: short list has items from GridView2.
GridView 2: Long list has telerik:RadGridView.GroupDescriptors for group the items.
I want if I select one row in first GridView takes me to the same Row in the second GridView.
So, I put in Xaml
//XAML
    SelectedItem="{Binding SelectedDP}" For GridView1
    SelectedItem="{Binding SelectedDP1}" For GridView2
//CS
        private DataPermission mSelectedDP = new DataPermission();
        public DataPermission SelectedDP
        {
            get { return mSelectedDP; }
            set
            {
                mSelectedDP = value;

                    foreach (SecurityDataPermissions m in DisplayedDataPermissionsList)
                {
                    if (m.DataPermission.DataPointName == SelectedDP.DataPointName)
                        SelectedDP1 = m;
                }

                OnPropertyChanged("SelectedDP");
            }
        }

        private SecurityDataPermissions mSelectedDP1 = new SecurityDataPermissions();
        public SecurityDataPermissions SelectedDP1
        {
            get { return mSelectedDP1; }
            set
            {
                this.mSelectedDP1 = value;
                OnPropertyChanged("SelectedDP1");
            }
        }

The row in GridView2 is getting selected but it doesn't scroll to it. I mean if manually scrolled to the item I can see it gray (selected but not focused) but If not, I can't recognize which row is selected.
What I want is when I select row in GridView1 takes me to the same row in GridView2
Answer: You could handle the SelectionChanged event and call the ScrollIntoViewAsync method in the event handler as suggested in the official documentation.
private void gridView_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
{
    gridView.ScrollIntoViewAsync(gridView.SelectedItem, radgridView.Columns[0]);
}

You may of course wrap this functionality in an attached behaviour if you want to: https://www.telerik.com/forums/auto-scroll-to-the-selected-item


How to detect user has drawn a certain path using Javascript

Question: I want to create a small activity where user will be required to draw certain predefined shape using Javascript/Jquery.
But I am not able to figure out a way to validate what the user has drawn.
I will appreciate any help as to how to approach this problem. Thanks in advance.
Comment: Here's a possible starting point...You can hit-test if the mouse clicks (or drag-draws) are inside a predefined shape like this: http://stackoverflow.com/questions/26375877/hit-testing-against-text-shapes/26387527#26387527.  You can estimate how much of the shape has been clicked/drawn by using destination-out compositing to clear pixels within a radius of each click/dragpoint. Then compare the resulting pixel count with the original fully-pixeled shape and determine if they have cleared enough pixels to declare the shape officially "drawn".
Comment: Another way is to draw waypoints along the path of the shape. Then hit-test of the user is clicking/dragging along each sequential waypoint. You can hit-test by comparing the mouse position with a radius around each sequential waypoint.
Answer: Have you thought of the following jQuery commands: for .mousedown(), .mouseenter(), .mousemove(), .mouseup(), .mouseleave(), .mouseenter()? I assume that you will be monitoring the user's mouse movement especially the interaction between the mouse and a predefined space in the browser. Depending on that, you can place a listener that monitors their mouse movement from the user.
Hope this helps.
Thomas


SQL First row result in reverse

Question: SELECT item_description, item_variant, branch, GROUP_CONCAT(sum ORDER BY 'date') AS chartData
        FROM (
        SELECT item_description, item_variant, branch, SUM(sales) AS sum
        FROM inventory_branches
        WHERE (item_description = 'agapanthus') AND (date BETWEEN '2018-06' AND '2018-08')
        GROUP BY item_description, item_variant, branch, MONTH(date) DESC
        ) T
        GROUP BY item_description, item_variant, branch, MONTH('date')
        LIMIT 5

The code above returns all rows correctly except for the first one. The first group of data in chartData is in reverse
In the first row, the 20 should be after the 58
Thank you in advance!
Comment: See: [Why should I provide an MCVE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query)
Comment: Do you mean `GROUP_CONCAT(sum ORDER BY 'date' DESC) AS chartData`?
Comment: @Zack no matter how I add DESC or ASC in the code, the result in the first row of `chartData` is reversed
Answer: I assume there is a column named date in you table. To sort by it use ORDER BY date and not ORDER BY 'date', i.e. don't enclose the column name in single quotes. 'date' is just a string literal, sorting by it is like not sorting at all, as it is equal for all rows.
Comment: I don't know why but I get an error saying that it's an unknown column in field list when I take away the single quotes.
Comment: @lekendary: Include it in the column list of your inner query.
Comment: it works! I didn't realize that's what it needed. Thank you!

SQL First row result in reverse


Why this set is the pole set of $z$?

Question: Suppose $V\subset \mathbb P$ a projective variety, $z$ a rational function on $V$ and let's define $J_z=\{F\in k[X_1,\ldots, K_{n+1}\mid \overline Fz\in \Gamma_h(V)\}$ and $S_z$ the polo set of $z$, i.e., the set of those points where $z$ is not defined. I would like to prove $V(J_z)=S_z$.
I'm having problems to prove $S_z\subset V(J_z)$.
My attempt
Let $P\in S_z$, i.e., $P$ is a polo of $z$. We can write $z=\frac{\overline a}{\overline b}$, where $\overline a,\overline b$ are the images in $\Gamma_h(V)$ of the polynomials $a$ and $b$, resp. In this way, we have $\overline a(P)\neq \overline 0$ e $\overline b(P)=\overline 0$. In order to show $P\in V(I_z)$, we will show for every $F\in I_z$, we have $F(P)=0$.
If $F\in I_z$, then $\overline Fz\in \Gamma_h(V)$, i.e., there exists $G\in k[X_1,\ldots,X_{n+1}]$ such that $\overline a\overline F=\overline b \overline G$. Therefore, we have $aF-bg\in I(V)$. In this way, evaluating at $P$ in the classes of  $\Gamma_h(V)$, we have $\overline a(P)\overline F(P)-\overline b(P)\overline g(P)=\overline 0$. We know that $\overline b(P)=\overline 0$. Thus,  $\overline a(P)\overline F(P)=\overline 0$. Since $\overline a(P)\neq \overline 0$, we have $\overline F(P)=\overline 0$.
Troubles
The problem with this solution is I proved $\overline F(P)=\overline 0$, but I have to prove $F(P)=0$.
I don't know how to prove $F(P)=0$. I need help to finish this proof.
Thanks
Answer: I think your confusion boils down to this: what is the definition of $\overline{F}(P)$?  Now $\overline{F} \in \Gamma_h(V) = k[X_1, \ldots, X_{n+1}]/I(V)$ is not a polynomial; it is a coset, i.e., $\overline{F} = F + I(V)$.  So what does it mean to evaluate a coset at a point?  Well, the first idea that comes to mind is to choose a representative $f \in F + I(V)$, and define $\overline{F}(P) = f(P)$.  But what if we chose a different representative?  Well, if $f_1, f_2 \in F + I(V)$, then $f_1 - f_2 \in I(V)$.  Then $f_1 - f_2 = g$ for some $g \in I(V)$, so $g$ vanishes on $V$.  Since $P \in V$, then
$$
f_1(P) = (f_2 + g)(P) = f_2(P) + g(P) = f_2(P)
$$
so we can give a well-defined meaning to $\overline{F}(P)$.
Now, back to your original question.  We showed above that the definition of $\overline{F}(P)$ was independent of the choice of representative.  Well, we certainly have $F \in F + I(V)$, so $0 = \overline{F}(P) = F(P)$ by definition.  Or if you don't like that approach: Choose a representative $f \in F + I(V)$.  Then $F = f + g$ for some $g \in I(V)$.  Since $P \in V$, then
$$
0 = \overline{F}(P) = f(P) = F(P) - g(P) = F(P) \, .
$$
Here's how I might phrase a (very detailed) conclusion to your proof.  The evaluation map
\begin{align*}
\varphi = \text{eval}_P : k[X_1, \ldots, X_{n+1}] &\to k\\
G &\mapsto G(P)
\end{align*}
is a homomorphism.  Since $P \in V$, then $\varphi(I(V)) = \{0\}$, so $\varphi$ descends to a (well-defined) homomorphism $\overline{\varphi} : \Gamma_h(V) = k[X_1, \ldots, X_{n+1}]/I(V) \to k$.  Letting $\pi : k[X_1, \ldots, X_{n+1}] \to \Gamma_h(V)$ denote the quotient map, then $\varphi = \overline{\varphi} \circ \pi$.  Then
$$
0 = \overline{F}(P) = \overline{\varphi}\left(\overline{F}\right) = \overline{\varphi}(\pi(F)) = \varphi(F) = F(P) \, .
$$
Just as a remark: although the coordinate ring is defined as a quotient, it's probably better to just think of its elements as polynomial functions restricted to $V$, where $\overline{F}$ corresponds to $F|_V$.  Then all the above argument really amounts to is $F(P) = F|_V(P) = \overline{F}(P) = 0$.
Comment: So using your idea, I will add to my solution: "Since $\overline F(P)=\overline 0$, we have $F(P)\in I(V)$, then $F(P)=0$, as $P\in V$". Is that correct? Thank you very much for your answer!
Comment: Yes, you're right, I think it's better see the elements of the coordinate ring as polynomial functions restricted to $V$, it's simpler. Thank you for your answer again and for your kindness to add some remarks to your answer to solve my doubts.
Comment: I don't follow why $F(P) \in I(V)$ implies $F(P) = 0$...  Even writing $F(P) \in I(V)$ seems a bit strange to me (although not incorrect), since I think of $F(P)$ as an element of $k$.  I've added a remark to my answer to try to clarify things.
Comment: Yes, you're right. I think my mistake started saying $\overline F(P)=\overline 0$.

Why this set is the pole set of $z$?


Reinstall CUDA toolkit

Question: Okay, I've run this commands to install CUDA Toolkit version 10: (after downloading a .deb file )
sudo dpkg -i cuda-repo-ubuntu1704-10-0-local_10.0.176-1_amd64.deb
sudo apt-key add /var/cuda-repo-10-0-local/7fa2af80.pub
sudo apt-get update
sudo apt-get install cuda
but then I realized I wanted version 9.0 and now every time try to uninstall everything from version 10.0 I just can't...
When I run apt-cache madison cuda:
cuda | 10.0.130-1 | file:/var/cuda-repo-10-0-local-10.0.130-410.48  Packages
  cuda |  9.0.176-1 | file:/var/cuda-repo-9-0-local  Packages

even if I try to install only version 9.0 making: sudo apt-get install cuda=9.0.176-1 in the middle of the installation he tries to access 10.0 files
So I've tried everything! I just want complete removal of the 2 versions, the whole package, the key, everything so I can start from scratch
Thanks in advance
Answer: Try
sudo apt-get purge --autoremove cuda*
then you should be able to download your package of choice without interfering.

Reinstall CUDA toolkit


Is there a design pattern for an informational pane?

Question: What I'm picturing is a side panel that updates with region-specific information as I mouse over portions of the form. Is there a name for this pattern?
It's like a Two-panel Selector, but not selecting or navigating anything, just providing information. I seem to recall seeing it in some applications when I open help.
Comment: At least half of the name is "context sensitive".  I think you have options for what word you put after that (properties, information, data).
Answer: I believe i'd call that a detail pane layout.  Mouse over or focus on something in the left pane and get information regarding your selection in a pane on the right.
Answer: Well, imo its just a sort of tooltips, say static tooltip.
Nice working example to refer: http://register.wildapricot.com/
Tooltip on the right side is fixed, and changes text every time one of fields get hovered or got focus.
Comment: I like this as well, in fact better than my original idea, but it's not what I was trying to describe. Thanks though :)


Usernames - Sentence case or Normal case

Question:
Possible Duplicate:
Should first and last name be formatted?

Scene

User doesn't care how he/she types their name in "First name" &
   "Last name" text boxes.

What happens

If the user has not typed in their first name and last name in Sentence Case ("normal" capitalization) it might look like "jenifer lopez"
Or sometimes user enters their pen names like "JLO" or JlO or jlo
Sometimes JenIFER LoPeZ
And if user has used proper capitalization for pronouns: "Jenifer Lopez" - Which looks
absolutely fine.

My question

Should User names; First name & last name appear in sentence case with pronouns properly capitalized or should the application keep showing it in the same way it was input?
Comment: Keep the username as the user entered it!
Comment: The first name/last name part is a dupe; I hadn't read the comments saying it's also about usernames. I could see that as a slightly different answer, but IMO the answer on the duplicate applies equally well to usernames; since the answer is basically "don't format" and with usernames not formatting may be even more important
Comment: @Sachin Gawas: There's a distinction between username and regular name that needs to be made clear here. Which are you referring to?
Comment: If my application has a executive & rich look, I think it will benecessary to re-furnish first name & last name
Comment: @dhmholley I am referring to user's First name, last name as well as Usernames which becomes screen name for them.
Comment: @SachinGawas My username is dhmholley. My regular name is David Holley. Which are you referring to?
Comment: @dhmholley - I am referring to both "David Holley" & "dhmholley"
Answer: The Chicago Manual of Style suggests:

"If unconventional spelling is the strong preference of the bearer of the name, it should be respected in appropriate contexts."

I would apply this principle to unconventional capitalisation as well - it simply becomes a matter of determining appropriate contexts.
To start with, don't change user's usernames. Since usernames don't have a standard capitalisation format (or even standard structure) their capitalisation is an inherent quality, and users won't be happy if you automatically change "iNtErCaP" to "Intercap" without checking.
You'd think that since regular names have a more regular structure you could probably get away with it in the majority of cases. However, since it's almost impossible to account for all the edge cases, you should still probably not alter regular names automatically - or if you do, check with the user first.
Answer: This really depends on the app you're building. For example this kind of name: oR@j1337 is pretty common for games, forums, chats but I believe Oraj just works much better for more serious places like Stack Exchange or place that people need to identify you clearly, like Facebook or LinkedIn. There's also a third place in between these two: where people want to identified but with only a first name for example. It's really up to you to get that feeling right.
If the app in question would be a place that people would like to use nicknames instead of real aliases, shows the name entered in Sentence Case instead of the way the user has entered it, the user can get annoyed.
But it could have advantages in certain conditions such as if you don't let your users rename, it would fix the typo. If you could implement that right on the registration form for example, it would really look good - and it would mean no surprises for the most part.
In the end it really comes down to the feeling of the experience and the web app you're building.


Determine if a type is static

Question: Let's say I have a Type called type.
I want to determine if I can do this with my type (without actually doing this to each type):
If type is System.Windows.Point then I could do this:
Point point1 = new Point();

However if type is System.Environment then this will not fly:
Environment environment1 = new Environment(); //wrong

So if I am iterating through every visible type in an assembly how do I skip all the types that will fail to create an instance like the second one?  I'm kind of new to reflection so I'm not that great with the terminology yet.  Hopefully what I'm trying to do here is pretty clear.
Answer: static classes are declared abstract and sealed at the IL level. So, you can check IsAbstract property to handle both abstract classes and static classes in one go (for your use case).
However, abstract classes are not the only types you can't instantiate directly. You should check for things like interfaces (without the CoClass attribute) and types that don't have a constructor accessible by the calling code.
Answer: type.IsAbstract && type.IsSealed

This would be a sufficient check for C# since an abstract class cannot be sealed or static in C#.  However, you'll need to be careful when dealing with CLR types from other languages.
Answer: you can search for public contructors like this,
Type t = typeof(Environment);
var c = t.GetConstructors(BindingFlags.Public);
if (!t.IsAbstract && c.Length > 0)
{
     //You can create instance
}

Or if you only interested in parameterless constructor you can use
Type t = typeof(Environment);
var c = t.GetConstructor(Type.EmptyTypes);
if (c != null && c.IsPublic && !t.IsAbstract )
{
     //You can create instance
}

Comment: Note that an `abstract` class can have a `public` constructor. You can't necessarily create an instance of a class in the body of your `if` statement. You'll get `MemberAccessException`.
Answer: Type t = typeof(System.GC);
Console.WriteLine(t.Attributes);
TypeAttributes attribForStaticClass = TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class |
TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit;
Console.WriteLine((t.Attributes == attribForStaticClass));

I guess, this should work.
Comment: I believe the only one unique to static classes is the `TypeAttributes.BeforeFieldInit` -- this is what I use to determine static classes. Checking `IsAbstract` and `IsSealed` also guarantees only static types but it's a more involved check.
Answer: This is a way to get all public contstuctors of all types in an assembly.
    var assembly = AppDomain.CurrentDomain.GetAssemblies()[0]; // first assembly for demo purposes
var types = assembly.GetTypes();
foreach (var type in types)
{
    var constructors = type.GetConstructors();
}

Determine if a type is static


bootstrap fixed header when scrolling down

Question: I am working within bootstrap's core admin structure and have a main header at the top of the page and then a sub header beneath it. I am trying to allow that sub header to fix to the top of the page when the user scrolls down so they can always see that information, but I am having a bit of trouble.
The section I would like to stick to the top looks like this.

Dashbord

 Cover Designs 4

 Video Trailers 5

 Web Banners 5

and I have tried so far to wrap that in another div with the navbar navbar-fixed-top classes. But that shot it to the top right away and overlapped content that needs to be seen.
I have also tried using plain css by adding position:fixed; to the current div, but that messes up the breadcrubms I have laying underneath it because it takes it out of the flow.
Is there anyway to accomplish this with just css. I know I can do a hack with jquery, but in my team I am only in charge of the css.
Comment: If you use `navbar-fixed-top` you have to add padding to the  with the height of navbar. Eg: if you `navbar` `height` is `50p`x the  you have to add `50px` padding to body.
Comment: @AvinVarghese It still doesn't work for this situation because I don't want it to stretch across the entire page because it hides content and takes it out of the flow of the page. Plus this only happens on one page so I don't want to add padding globally.
Comment: Can you provide you sample code in http://bootply.com/new
Comment: @AvinVarghese it's in core admin so it won't show up right in that format. It's a paid template.
Answer: you can use below css to the sub header navbar.
css:
.sticky-top {
    position: -webkit-sticky;
    position: sticky;
    top: 0;
    z-index: 1020;
}

Add 'sticky-top' class to sub header.
for eg: you can see the fiddle below which is similar to the question.Here second menu fixed to top when user scrolls.
https://jsfiddle.net/raj_mutant/awknd20r/6/
Comment: Also useful to add an opaque colour to the background such as: background-color: white;
Answer: position:fixed is the way to go here. Can you apply a height to the div you want to be fixed and apply a margin to the breadcrumbs?
.area-top{ position:fixed; height:2em; }

.breadcrumbs { margin-top: 2.2em; }

Comment: This still lays the nav right on top of the breadcrumbs even though it has the margin top on it
Comment: Are the breadcrumbs being pushed down on the page at all? Either the style isn't being applied, or a larger margin should be specified.
Comment: the breadcrumbs are staying right underneath the heading and the heading is being pushed down the page. I put it inline styles so I could make sure it was being applied and in the web inspector added over 20em on margin to see if anything would happen, but they both moved down the page the breadcrumbs under the header.
Comment: Can you post the HTML / CSS for the breadcrumbs so we can see what other styles are in play?
Answer: My point of view is the following. When you ask for this :
to fix to the top of the page when the user scrolls down
It means that you need to detect when users are scrolling. Furthermore, there is no other way than js / jQuery to detect this kind of action. CSS can be a part of solution by creating a class for exemple which will stick your menu, but you'll always need a bit of js to detect when to put and to remove the class.
Here is an exemple on how to do this in jQuery :

Don't forget that every "advanced" action which need to detect a change in the DOM or which need an user interaction will require some JS or PHP to deal with it. By "advanced", i'm meaning all the things that can't be natively handle in HTML.


what version of AMDGPU -

Question: Which version of Amdgpu?
Is there a command line tool to get the list of content of current kernel used in my Ubuntu?
neither of these have answered the actual question...I dont mean to be rude, but i was in need of the same information....this is what i found
def@xeon:~$ apt list --installed | grep -i amdgpu-pro
amdgpu-pro/unknown,now 18.50-725072 amd64 [installed]
amdgpu-pro-core/unknown,now 18.50-725072 all [installed,automatic]
amdgpu-pro-lib32/unknown,now 18.50-725072 amd64 [installed]
amdgpu-pro-pin/unknown,now 18.50-725072 all [installed]
trimmed
I believe that would indicate that I have amdgpu version 18.50-725072
tested on another machine with 19.20:
def@mineshaft:~$ apt list --installed | grep -i amdgpu-pro
amdgpu-pro-core/now 19.20-812932 all [installed,local]
amdgpu-pro-pin/now 19.20-812932 all [installed,local]
clinfo-amdgpu-pro/now 19.20-812932 amd64 [installed,local]
trimmed
One correct answer to how to find your amdgpu version is:
    apt list --installed | grep -i amdgpu-pro
def
Answer: apt list --installed | grep -i amdgpu-pro

what version of AMDGPU -


How to get the raw mdx cellset back

Question: The cellset that is returned in Visual Studio or SSMS is within a grid. Is there a way to examine the raw data that is returned back from the MDX query? For example, returning the data that includes the font size, the color, etc. and reading that data directly?
If so, how can I examine that in SSMS or VS?
Answer: In SSMS double click the result grid, it will expose you the additional porperties. In VS you can use AdoMD, any results returned from a cube will be in CellSet Class.
Comment: ok, but how is the data actually passed back? I'm assuming it comes as an xml string?
Comment: Read about CellSet Class, the data is always returned in CellSet. There is no Xml involved. I hope i am able to explain?
Comment: this? https://learn.microsoft.com/en-us/dotnet/api/microsoft.analysisservices.adomdclient.cellset?view=sqlserver-2016 Is there a 'friendly serialization' where you can see the data?
Comment: Yes that is it. Unfortunatly i have not come across one.

How to get the raw mdx cellset back


How to read an external JSON file as a string in javascript?

Question: I have an external json file which I am using to initialize a js object in a web app (using webpack).
To read the file im doing this:
var myObject = require('json-loader!constants/myfile.json')

The application needs to modify the object over time and occasionally needs to return to the original state. Due to this, I've found this to be the most performant way to initialize and reinitialize (deep clone) the object:
var clonedObject = JSON.parse(JSON.stringify(myObject))

This approach seems redundant - First load a json object then stringify the object only to load it again.
Is there a way to read the JSON file as a string and then JSON.parse the object (thus omitting the JSON.stringify step)?
Comment: I'd just deep clone the object when you need to (although I'd use a library instead).
Comment: @Dave Newton, I am deep cloning the object when i need to. The issue is the most effective way I've found to deep clone (an object with nested objects) is to JSON.parse the string converted object. So my question is how to skip a step by reading the JSON in as a string.
Comment: By using a deep-cloning library that doesn't deal with strings. This can't possibly be the most important thing in your code though?
Answer: You can use raw-loader to read a file as string:
var jsonString = require('raw-loader!constants/myfile.json');
var obj1 = JSON.parse(jsonString);
var obj2 = JSON.parse(jsonString);

Answer: You'll want to read the file contents first using a blob perhaps.
Get the text content, then use  the JSON.parse(jsonString).
Answer: Honestly I am too ignorant to keep libraries in my head, and thus I read JSON files with fs like this:
var fs=require("fs");
var stuff=JSON.parse(fs.readFileSync("filename","utf8"));

And then it is pretty sure that someone could store the intermediate result of fs.readFileSync() if they wanted to:
var fs=require("fs");
var originaljson=fs.readFileSync("filename","utf8");
var stuff=JSON.parse(originaljson);


capistrano deploys wrong directory

Question: I am newbie in capistrano , i am able to deploy my ruby application from git to the server successfully , but instead of deploying the code directly it creates 2 directories namely current and releases . How to come out from it ?
Answer: That's normal. It's how capistrano works.
Each time you deploy a new release is created in the releases folder. Once the deploy is complete the current symlink is updated to point at the newly created release.
This way

you don't need to update webserver configurations on each release
inprogress deploys aren't used until they are ready
it's possible to switch back to an old release

capistrano deploys wrong directory


In a card style layout, do pin/unpin have the same meaning to the user as hide/unhide?

Question: I'm working on a card layout, where the user should have activities, such as pin / unpin a card, and hide / unhide a card. The first action can be done on a catalog page, where the user can choose cards they want to add to their page. Also the user can unpin a card from their page in an edit mode.
The question is: do I really need hide / unhide a card on the user's page? Or pin / unpin option is enough?
Answer: The question that needs an answer first; why would the user hide a card from the Users page in the first place - what is the purpose/advantage for the user?
I feel you're talking about simple add/remove functionality. Pin a card equals "add", while now you're looking for a way to offer "delete" as well.
If this is the case, I'd simply offer the user a way to delete the card... not hiding, or unpinning, which might confuse the user. Add/delete makes sense enough.


How do I use hashbrown data types with Rayon parallel iterators?

Question: I have a hashbrown::HashSet, and I am trying to use Rayon's par_iter with it, but I cannot figure out the right syntax.
Cargo.toml
[package]
name = "basic"
version = "0.1.0"
authors = ["Me <email@example.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

hashbrown = "0.9.1"
rayon = "1.5.0"

src/main.rs
use hashbrown::*;
use rayon::prelude::*;
// use hashbrown::hash_set::rayon::*;

fn main() {
    println!("Hello, world!");

    let hs = HashSet::new();
    for n in 1..100 {
        hs.insert(n);
    }

    hs.par_iter().for_each(|n| println!("n={}", n));
}

This fails to compile.
error[E0599]: no method named `par_iter` found for struct `hashbrown::HashSet<{integer}>` in the current scope
   --> src/main.rs:13:8
    |
13  |     hs.par_iter().for_each(|n| println!("n={}", n));
    |        ^^^^^^^^ method not found in `hashbrown::HashSet<{integer}>`
    |
   ::: /Users/me/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.9.1/src/set.rs:114:1
    |
114 | pub struct HashSet<T, S = DefaultHashBuilder> {
    | --------------------------------------------- doesn't satisfy `_: rayon::iter::IntoParallelRefIterator`
    |
    = note: the method `par_iter` exists but the following trait bounds were not satisfied:
            `&hashbrown::HashSet<{integer}>: IntoParallelIterator`
            which is required by `hashbrown::HashSet<{integer}>: rayon::iter::IntoParallelRefIterator`

warning: unused import: `rayon::prelude`
 --> src/main.rs:2:5
  |
2 | use rayon::prelude::*;
  |     ^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

The hashset-rayon docs suggest that hashbrown::hash_set::rayon has a Rayon-related data type, and I know that sometimes I need to use traits to make functionality available.  However, if I uncomment the import, it cannot even find the module:
error[E0432]: unresolved import `hashbrown::hash_set::rayon`
 --> src/main.rs:3:26
  |
3 | use hashbrown::hash_set::rayon::*;
  |                          ^^^^^ could not find `rayon` in `hash_set`

I am running Rust 1.49.0 on a Mac:
$ rustup show
Default host: x86_64-apple-darwin
rustup home:  /Users/tda0106/.rustup

installed toolchains
--------------------

stable-x86_64-apple-darwin (default)
nightly-x86_64-apple-darwin

active toolchain
----------------

stable-x86_64-apple-darwin (default)
rustc 1.49.0 (e1884a8e3 2020-12-29)

What is the problem?
Edit
As @E_net4 the curator pointed out in the comments, the rayon support is in a feature.  Changing the dependencies to
[dependencies]
hashbrown = { version = "0.9.1", features = ["rayon"] }
rayon = "1.5.0"

makes this work, without needing the extra use statement.
It's not clear to me where the documentation indicates this.
Comment: `rayon` support is behind the `rayon` Cargo feature, which you have to enable explicitly in Cargo.toml. Similar question: https://stackoverflow.com/q/55783064
Comment: That fixed the problem.  Is there someplace at https://docs.rs/hashbrown/0.9.1/hashbrown/index.html that tells me I need to do this?
Comment: The project is not yet 1.0, and its docs look incomplete (as is typical for pre-1.0 projects), you might add an issue via github where the source lives: https://github.com/rust-lang/hashbrown/issues
Answer: If you look inside of the hashbrown crate, you will see that rayon support is only present if the rayon feature is enabled. You can enable the feature in your Cargo.toml:
[dependencies]
hashbrown = { version = "0.9.1", features = ["rayon"] }


Can't add comment with ajax

Question: I'm trying to add comment using ajax.
Here is my ajax code:
$(document).ready(function(){
    $("#add_comment").click(function(event){
        event.preventDefault();
        var article_id = {{article.id}};
        $.ajax({
            url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
            type: "get",
            success: function(result){

                        if(result === "validation error"){
                            alert(result);
                        }else{
                            var data = JSON.parse(result);
                            $("#comment_block").append("
" + data['owner'] + "
" + data['comment_text'] + "

");
                        }
                    }
            });
    });

});

Here is my form of adding comment in django template:

    {% if username %}
    <form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
    {% csrf_token %}
    {{ form }}
    <input type="submit" class="button"  value="Добавить комментарий" id = "add_comment">
    </form>
    {% endif %}

Trying to debug, I noticed that it doesn't even step into ajax body. What am I doing wrong then?
I've done ajax query with counting likes and had success in that.
Comment: you have a syntax error in `var article_id = {{article.id}}` what are you trying to do here... just try `var article_id = article.id;`
Comment: and you have form action, by default it will trigger  form action not AJAX call
Comment: no, it's not syntax error. It's django template tag.
Comment: kartheek, what shoud I do then?
Comment: {{article.id}} and you have this too. what article.id is?
Comment: I pass article object to template. Then {{article.id}} returns id of that article, when I'm now at.
Answer: Try this
HTML

    {% if username %}
    <form action="#" method="post" id = "comment_form">
    {% csrf_token %}
    {{ form }}
    <input type="text" name = "article" value="{{ article.id }}" id = "article_id">
    <input type="text" name = "comment" value="comment goes here" id = "comment_text">
    <input type="submit" class="button"  value="???????? ???????????" id = "add_comment">
    </form>
    {% endif %}

 jQuery
  $(document).ready(function(){
    $("#add_comment").click(function(event){
        event.preventDefault();
        var article_id = $('#article_id').val();
        $.ajax({
            url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
            type: "POST", /*i belive you are posting data to BE api*/
            data:{'comment':"your comment goes here"}, /* use this get what given in input  $("#comment_text").val()*/
            success: function(result){
                        /*process data after success call*/
                    }
            });
    });

});

Answer: Change to the following:
JS Code:
$(document).ready(function(){
$("#comment_form").submit(function(event){
    event.preventDefault();
    var article_id = $(this).find('.article_id').value();
    $.ajax({
        url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
        type: "post",
        success: function(result){

                    if(result === "validation error"){
                        alert(result);
                    }else{
                        var data = JSON.parse(result);
                        $("#comment_block").append("
" + data['owner'] + "
" + data['comment_text'] + "

");
                    }
                }
        });
    return false;
});

});
Django Template:

{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="hidden" class="article_id" value="{{ article.id }}" />
<input type="submit" class="button"  value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}

Comment: When debugging, I noticed that program doesn't walk into ajax body.
Comment: Try replacing the django code of '{{article.id}}' with a static number, such a '2' and see if it runs the ajax body.
Comment: I'll give you the best way to proceed with this. Modifying my answer atm.
Comment: Basically, switched from `click` to `submit` event for the form.  Also, your ajax was doing a `GET`, while your form was doing a `POST` on the same URL. Which is which?

Can't add comment with ajax


Bootstrap-select Multi-select rendered wrongly

Question: What I have:

    Status
    <select className="selectpicker" multiple title="Choose one of the following...">
        <option>OK</option>
        <option>PENDING</option>
        <option>NEW</option>
    </select>

PROBLEM:
Values (OK, PENDING, NEW) are displayed separately in another scrolled field. Whereas the drop down select field is displayed as separate field beside it. The drop down select field has no value inside. Screenshot attached.

What I wanted is this kind of dropdown: (Taken from Bootstrap-select documentation)

The technology stack of my project:

Bootstrap-select 1.13.1
.Net
Bootstrap 3.x
ReactJs

Could this be compatibility issue?
EDIT
I'v given up. I had to choose to use bootstrap-multiselect instead. It is much less confusing. Recommend it!
Answer: Please check this:
I have used the https://jedwatson.github.io/react-select/ and it works great.
import React from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';

export default class SelectComponent extends React.Component {
  state = {
    selectedOption: '',
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        name="form-field-name"
        value={selectedOption}
        onChange={this.handleChange}
        multi
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
}

Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/19798251)
Comment: @fhdrsdg : I am not sure why you had to downvote because I had given the exact answer the user had asked.
Comment: You're assuming I downvoted, which I didn't. As the comment says, you haven't posted the solution. What you posted is directions to where someone may find the answer. If that link breaks, your answer becomes useless. Also read [this answer in the FAQ](https://meta.stackexchange.com/a/8259/276063)
Comment: :) thanks for the tip and thank you for correcting me.. noted. The reason I mentioned the npm package was, I used it and it worked.
Answer: is this what you are looking for??

    Status
    <select className="selectpicker">
        <option selected="selected">Choose one of the following</option>
        <option>OK</option>
        <option>PENDING</option>
        <option>NEW</option>
    </select>

Comment: Sorry. This is not what I wanted.