text:
Q: deploying django : error while importing settings, is it on sys.path? I'm trying to deploy a django website for the first time.
I'm using Django 1.5.1
I follow a tutorial, however I get an error in apache :
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183] mod_wsgi (pid=10767): Exception occurred processing WSGI script '/var/www/html/portail_public/geocameroun/geocameroun/wsgi.py'.
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183] Traceback (most recent call last):
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]   File "/usr/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 236, in __call__
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]     self.load_middleware()
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]   File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 45, in load_middleware
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]     for middleware_path in settings.MIDDLEWARE_CLASSES:
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]   File "/usr/lib/python2.6/site-packages/django/conf/__init__.py", line 53, in __getattr__
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]     self._setup(name)
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]   File "/usr/lib/python2.6/site-packages/django/conf/__init__.py", line 48, in _setup
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]     self._wrapped = Settings(settings_module)
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]   File "/usr/lib/python2.6/site-packages/django/conf/__init__.py", line 134, in __init__
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183]     raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
[Fri Aug 02 19:48:03 2013] [error] [client 109.8.106.183] ImportError: Could not import settings 'geocameroun.settings' (Is it on sys.path?): No module named settings

This error seems to be very frequent, I have a lot of responses but any of them solve my problem or maybe I don't understand something.
I check if geocameroun.settings is on sys.path, so I add in my geocameroun/wsgi.py :
print "path"
print sys.path

path = '/var/www/html/portail_public/geocameroun/'
if path not in sys.path:
    sys.path.insert(0, '/var/www/html/portail_public/geocameroun/')
path = '/var/www/html/portail_public/geocameroun/geocameroun'
if path not in sys.path:
    sys.path.insert(0, '/var/www/html/portail_public/geocameroun/geocameroun')
print sys.path

In apache I get this :
[Fri Aug 02 19:48:03 2013] [error] ['/var/www/html/portail_public/geocameroun/geocameroun', '/usr/lib/python2.6/site-packages/MapProxy-1.5.0-py2.6.egg', '/usr/lib/python2.6/site-packages/PyYAML-3.10-py2.6-linux-x86_64.egg', '/usr/lib64/python26.zip', '/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2', '/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old', '/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages', '/usr/lib64/python2.6/site-packages/PIL', '/usr/lib/python2.6/site-packages', '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info', '/var/www/html/portail_public/geocameroun']

So it's ok, no ? settings.py is in /var/www/html/portail_public/geocameroun/geocameroun/
In my wgsi.py I tried these two lines :
#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "geocameroun.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "geocameroun.settings"

About the development webserver, it doesn't work in this folder /var/www/html/portail_public
/geocameroun :Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 263, in fetch_command
    app_name = get_commands()[subcommand]
  File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 109, in get_commands
    apps = settings.INSTALLED_APPS
  File "/usr/lib/python2.6/site-packages/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/usr/lib/python2.6/site-packages/django/conf/__init__.py", line 48, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/lib/python2.6/site-packages/django/conf/__init__.py", line 134, in __init__
    raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'geocameroun.settings' (Is it on sys.path?): No module named settings

But it works in my real development version in /home/etienne/geocameroun.
Regards


text:
Q: Google Drive API - Get folders list I have some folders in Google Drive (lets assume, that I have them in the Root folder).
How can I parse them from Drive as folderName and driveId?
I'd like to do it with Google Drive API Google Drive API, not with REST.

A: You need to setup Google Drive API for Android in your project. Everything is in guides/documentation on Google Drive API site. Here is link to get started
Then you will do like this:

*

*Get root folder by calling  DriveApi.getRootFolder

*Get children of the root folder by calling method listChildren (Link to documentation) on folder returned in step 1

*Process result by getting Metadata from buffer

*Get file by calling DriveID object method asDriveFile() (Link to documentation)

A: If you have a bit of experience with rxjava I would suggest you to take a look at this library: https://github.com/francescocervone/RxDrive
Otherwise you could do the same things without rxjava, official documentation has some examples for basic operations, also this quickstart might help

redpajama_set_name: RedPajamaStackExchange


text:
Q: Question on Set Projection and its projected set's properties For an arbitrary set $E \subseteq R^{1}$, consider its projection $E_{1}$ on the x-axis, which is defined as follows:
$$x \in E_{1} \Leftrightarrow \exists y\in R^{1}$$ such that $(x,y) \in E$.
I am trying to justify whether the following statements are right or wrong.
a) If E is open in $R^{2}$, then $E_{1}$ is open in $R^{1}$.
b) If E is closed in $R^{2}$, then $E_{1}$ is closed in $R^{1}$.
c) If E is compact in $R^{2}$, then $E_{1}$ is compact in $R^{1}$.
What tools should I use to tackle this type of problem? Any tip is greatly helpful. Thank you!

A: Define the linear map $P(x) = x_1$, then $E_1 = P(E)$.
If we stick with the Euclidean norm we see that
$P(B(x,\epsilon)) = B(P(x), \epsilon)$ (The balls are in $\mathbb{R}^2$ and $\mathbb{R}$ respectively).
Consider the closed set $E = \{x | x_1 x_2 = 1 \}$. What is $P(E)$?
Note that $P$ is continuous, so if $E$ is compact, what can you say about $P(E)$?


text:
Q: How to grant an app administrator permissions with adb? Yea I just want a specific app on my samsung A10 to be undeletable.
if it's not possible by using adb I would like to hear some other possible ways to do that.
:D

A: hello There are quite a few apps in the Market which will lock certain apps behind a password, a search in the Market for "applock" should find most of them.


text:
Q: .NET Regex taking long time to find the match Why this innocent looking regex is killing my requests?
([\d\w-]+.){6}hi

Is this candidate for catastrophic backtracking?
Running this on .NET framework 4.5.2, C#

A: To match a literal dot, you must escape it.  If you do not, a quantified group ([\d\w-]+.){6} will lead to a catastrophic backtracking with longer inputs. Change to ([\w-]+\.){6}hi.
Note that [\d\w-]+ matches 1 or more (unknown number) letters, digits, _ or -. A . matches any char. When you apply a quantifier, the regex engine tries all possible ways to match a string before it fails. It is usually not a problem with a string where a match is found, it usually happens with strings where the match cannot be found since all possible ways are tried then (until the engine reports a crash).
Besides, the \d pattern matches digits, and \w matches digits, too, so there is no point using both inside a character class.


text:
Q: Can I integrate Chromedriver into a Maven Project where I don't need put it in my local machine? What I am doing now is I am putting my Chromedriver in my local machine C://Program Files/chromedriver. Is there a way to integrate/put chromedriver in my Java Maven Project for Automation testing using serenity cucumber so I don't have to manually put to my local machine?

A: Yes, look for webdrivermanager in maven from bonigarcia;
And instead of setting the path to the driver, just do:
WebDriverManager.chromedriver().setup();

This will download the appropriate driver and set the path to the driver.


text:
Q: Need help with the Formula Field in Salesforce. I must have not entered the formula properly. Need help For the purpose of having a prospect list as a report, I would like to show up in the report only leads/contacts in a campaign member list owned by the logged in User AND the leads owned by a queue. So I created a formula field as a checkbox and added it to the report as a filter. Here the formula:
AND( Lead.Owner:Queue.Id="3D00G50000002l3Sw",
    IF($User.Id=Contact.OwnerId, TRUE,
    IF($User.Id=Lead.Owner:User.Id, TRUE,
    IF($User.Id=Contact.Account.OwnerId, TRUE,
    FALSE
))))

A: Bartosz's advice about using the the Queue Developer Name is good, but there are a couple other issues here. (Incidentally, the problem with your Queue Id is that it has "3D" at the front, probably from copying it out of an encoded URL. "00G50000002l3Sw" is probably the Queue Id you're looking for, but, use the developer name.)
First, and most important, is that you are using AND(), which means that all of the conditions listed have to be TRUE for the checkbox to be TRUE. It's not possible for a Lead to be owned both by a queue and the current user, so your formula as written will always be FALSE. You want any one of the conditions to make the checkbox formula TRUE, so you need to use OR().
Another point, not really an error, is that checks for equality are inherently TRUE or FALSE; you don't need to wrap them in an IF() to determine that.
So, that gets us to:
OR(Lead.Owner:Queue.DeveloperName = "QueueDevName",
$User.Id=Contact.OwnerId,
$User.Id=Lead.Owner:User.Id,
$User.Id=Contact.Account.OwnerId)

A: First of all 3D00G50000002l3Sw is definetely not a Queue's Id, so probably that's where you are having issues. Also: as a general rule, try not to use hardcoded Ids anywhere in Salesforce because they may change (e.g. during deployment to another environment). Instead use DeveloperName or similar field. Try using this formula:
AND( Lead.Owner:Queue.DeveloperName="Developer_Name_Of_Your_Queue",
    IF($User.Id=Contact.OwnerId, TRUE,
    IF($User.Id=Lead.Owner:User.Id, TRUE,
    IF($User.Id=Contact.Account.OwnerId, TRUE,
    FALSE
))))

And change Developer_Name_Of_Your_Queue to whatever your Queue's Developer Name is.


text:
Q: Listing profiles and show related user email field in template Need to list my profilemodel-records. Would like to include the user.email field in the template.(The users email related to the profile...)
To get the users email is just
{{ user.email }}

I was sure I had done it like this before, but now nothing.....
{{ profile.user.email }}

This is my view:
def profileall(request):
    profilelist = Profile.objects.all()

    return render(request, 'docapp/profilelist.html',{'profilelist':profilelist})


text:
Q: method running on an object BEFORE the object has been initialised? #include <iostream>
using namespace std;

class Foo
{

public:

 Foo(): initialised(0)
 {
  cout << "Foo() gets called AFTER test() ?!" << endl;
 };

 Foo test()
 {
  cout << "initialised= " << initialised << " ?! - ";
  cout << "but I expect it to be 0 from the 'initialised(0)' initialiser on Foo()" << endl;
  cout << "this method test() is clearly working on an uninitialised object ?!" << endl;
  return Foo();
 }

 ~Foo()
 {};

private:

 int initialised;

};

int main()
{

 //SURE this is bad coding but it compiles and runs
 //I want my class to DETECT and THROW an error to prevent this type of coding
 //in other words how to catch it at run time and throw "not initialised" or something

 Foo foo=foo.test();

}

A: Yes, it is calling the function on a yet not constructed object, which is undefined behavior. You can't detect it reliable. I would argue you also should not try to detect it. It's nothing which would happen likely by accident, compared to for example calling a function on an already deleted object. Trying to catch every and all possible mistakes is just about impossible. The name declared is visible already in its initializer, for other useful purposes. Consider this:
Type *t = (Type*)malloc(sizeof(*t));

Which is a common idiom in C programming, and which still works in C++.
Personally, i like this story by Herb Sutter about null references (which are likewise invalid). The gist is, don't try to protect from cases that the language clearly forbids and in particular are in their general case impossible to diagnose reliably. You will get a false security over time, which becomes quite dangerous. Instead, train your understanding of the language and design interfaces in a way (avoid raw pointers, ...) that reduces the chance of doing mistakes.
In C++ and likewise in C, many cases are not explicitly forbidden, but rather are left undefined. Partially because some things are rather difficult to diagnose efficiently and partially because undefined behavior lets the implementation design alternative behavior for it instead of completely ignoring it - which is used often by existing compilers.
In the above case for example, any implementation is free to throw an exception. There are other situations that are likewise undefined behavior which are much harder to diagnose efficiently for the implementation: Having an object in a different translation unit accessed before it was constructed is such an example - which is known as the static initialization order fiasco.

A: The constructor is the method you want (not running before initialization but rather on initialization, but that should be OK). The reason it doesn't work in your case is that you have undefined behavior here.
Particularly, you use the not-yet-existent foo object to initialize itself (eg. the foo in foo.Test() doesn't exist yet). You can solve it by creating an object explicitly:
Foo foo=Foo().test()

You cannot check for it in the program, but maybe valgrind could find this type of bug (as any other uninitialized memory access).

A: You can't prevent people from coding poorly, really. It works just like it "should":

*

*Allocate memory for Foo (which is the value of the "this" pointer)

*Going to Foo::test by doing: Foo::test(this), in which,

*It gets the value by this->initialised, which is random junk, then it

*Calls Foo's default constructor (because of return Foo();), then

*Call Foo's copy constructor, to copy the right-handed Foo().

Just like it should. You can't prevent people from not knowing the right way to use C++.
The best you could do is have a magic number:
class A
{
public:
    A(void) :
    _magicFlag(1337)
    {
    }

    void some_method(void)
    {
        assert (_magicFlag == 1337); /* make sure the constructor has been called */
    }

private:
    unsigned _magicFlag;
}

This "works" because the chances _magicFlag gets allocated where the value is already 1337 is low.
But really, don't do this.

A: You're getting quite a few responses that basically say, "you shouldn't expect the compiler to help you with this". However, I'd agree with you that the compiler should help with this problem by with some sort of diagnostic. Unfortunately (as the other answers point out), the language spec doesn't help here - once you get to the initializer part of the declaration, the newly declared identifier is in scope.
A while back, DDJ had an article about a simple debugging class called "DogTag" that could be used as a debugging aid to help with:

*

*using an object after deletion

*overwriting an object's memory with garbage

*using an object before initializing it

I haven't used it much - but it did come in handly on an embedded project that was running into some memory overwrite bugs.
It's basically an elaboration of the "MagicFlag" technique that GMan described.


text:
Q: Many folders into one network share? Is it possible to migrate many folders into one network share in windows? (Server 2012 R2 standard) I only need read access
Example:
d:\pictures\
e:\pictures\
f:\pictures\

to
\\server\pictures\

I'm currently doing this on a linux machine with symlinks which works pretty well actually. I am running a cronjob that add symlinks to /media/share from each subfolder of each picture folder on each drive /media/driveX/pictures/. There are no duplicated names in the subfolders.
I need now a additional windows machine.
Actually my plan was to set-up a type 1 hypervisor to run windows and linux parallel. But while thinking about I get the idea to migrate the existing linux machine into windows.
Uhm yeah and when you are curious why:
I've distribute my files over many drives since I don't and won't use any kind of raid. When one drive crashes this would be annoying but OK.
Btw: I'm aware that windows can't read from / write to linux filesystems.
Oh and I don't want to use windows server drive pools / storage spacing

A: NTFS supports symbolic links too, it's pretty powerful filesystem.
From Wikipedia:

The mklink command is used to create a symbolic link. It is a built-in
  command of cmd.exe in Windows Vista and later.
In XP, junction utility by Mark Russinovich is capable of working with
  reparse points, now offered by Microsoft as a part of Sysinternals
  suite.

Full wikipedia article: link
You should also read windows help, just type mklink /? in command line.
By default - you need admin rights to create sybolic links, so your script in task sheduler must be set to run from account that belongs to Administrators group.
If for some reasons you want to create them as user who is not in "Administrators" group - read this: link.
(post was edited and cleaned after discussion below)


text:
Q: Why i get a NullPointerException when I try to get a fragment from fragmentManager in Android Test? Hello I'm a newbie in Android testing. I was trying to check if a button is visible in my app during the UI test. I write something:
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mRule = new ActivityTestRule<>(MainActivity.class);

@Before
public void setUp() {
}

@Test
public void clickOnProductTest() {
    if (isRegisterClosed()) {
        openRegister();
    }
    onView(withText("Food")).perform(click());
    onView(withText("Mineral water")).perform(click());
}

private boolean isRegisterClosed() {
    MainActivity activity = mRule.getActivity();
    FragmentManager fragmentManager = activity.getFragmentManager();

    Fragment f = fragmentManager.findFragmentById(R.id.current_order_fragment);

    View v = f.getView();

    Button b = (Button) v.findViewById(R.id.orderOpenRegister);
    return b.getVisibility() == View.VISIBLE;
}

private void openRegister() {
    onView(withId(R.id.orderOpenRegister)).perform(click());
}

On line

View v = f.getView(); //in method isRegisterClosed()

I get NullPointerException. It looks like a fragment didn't load. But i don't know why. But when I try to click on button in that Fragment, it works:

onView(withId(R.id.orderOpenRegister)).perform(click());

I want to do something like:
if (buttonIsVisible) {
      do smth;
}
else {
      do smth else;
}

This button is in current_order_fragment and its ID is orderOpenRegister.
Edit
I find out, that I should add the following line:

fragmentManager.executePendingTransactions();

so my method looks like:
private boolean isRegisterClosed() {
        FragmentManager fragmentManager = activity.getFragmentManager();
        fragmentManager.executePendingTransactions();
        Fragment f  = fragmentManager
                      .findFragmentById(R.id.current_order_fragment);
        View v = f.getView();
        Button b = (Button) v.findViewById(R.id.orderOpenRegister);
        return b.getVisibility() == View.VISIBLE;
}

but if I do that, i need to run this test in UI thread. Does anyone know how to run test on UI thread?

A: You can run the test in UI thread as below
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

instrumentation.runOnMainSync(new Runnable() {
  @Override
  public void run() { //your test
  }
});


text:
Q: Checking for and not printing JavaScript in generated data? In my php web app, suppose I want to go the extra mile and in addition to going gang-busters and being anal-retentive about sanitizing my inputs, I also want to ensure that no JavaScript is being output in strings I am inserting into html templates.
Is there a standard way to make sure I don't put JavaScript in the generated html content?

A: If you aren't opposed to external dependencies, the HTML Purifier library is a pretty good filter for a majority of XSS attacks.

A: not exactly a standard way; because what if you were doing:
, and ${path} expanded to
    http://p0wned.com/jpg.jpg" />


text:
Q: Why do we put exit(1) in the C code even knowing that it will terminate the program abnormally. Why are we putting exit(1) to terminate the program abnormally? Why do we want to terminate abnormally?
//Program exits itself
//Note that the example would terminate anyway
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    cout<<"Program will exit";
    exit(1); // Returns 1 to the operating system

   cout<<"Never executed";
}

A: I think I see the problem. Saying that exit(1) terminates the program abnormally is not a very accurate statement, and can lead to confusion. A better way to say it is that exit(1) indicates unsuccessful termination, i.e., it lets the user of the program know that something went wrong. It's simply a way to communicate the problem.
I don't actually think this is such a bad question, it just indicates the confusion of someone new to coding.

A: The number that is returned from a C executable is returned to the environment.
If the SHELL is bash, you can capture the exit status of an executable with 'echo $?' from the command prompt.
Here is an example of a C code:
 #include <stdio.h>
 #include <stdlib.h>

 int
 main(void)
 {
     FILE *fp;

     if( ( fp = fopen( "nonexistfile", "r" ) )== NULL ){
        exit(5);
     }

     if(fp) fclose(fp);

     return 0;
  }

This code is trying to open a file that does not exists.  So it will exit with status of 5.  Lets say the executable of this program is called "open_file".
When you run this executable and type "$?",
 >./open_file
 >echo $?
 >5

Here a bash script that runs this executable:
 #!/bin/bash

 ./open_file
 exit_status="$?"

 if [ $exit_status -eq 5 ]
 then
     echo "FILE not there"
 fi

Now lets say you have 10 C executable programs that are similar to above C program but trying to open different files.
And lets say you want to keep a log file of which of these programs failed opening a file.
As a programmer, you can exit with different exit status number for different programs.
e.g.  exit(1); for executable #1
      exit(2); for executable #2
                   ...
      exit(10); for executable #10
From bash script, it can keep track of  exactly which executable failed from return value of an executable.
This example was to illustrate how you can coordinate the exit(n); from a C program with bash script that runs this executable.  (n represents a decimal value)

A: The reason is usually to tell the operating system something unusual happened.  Typically, a program exits with a value of zero.  In Linux, you can use $? to see the value returned (i.e. 'echo $?').  You can use this value in scripts, etc. to check how your program terminated.


text:
Q: How to create a RangeAttribute for WindowsForms? I would like to create a metadata attribute called RangeAttribute without external tools like PostSharp as seen in this answer because it requires the paid version of the library.
The only official information that I've found about this is this MSDN documentation, but absurdly that page only explains how to declare the class and the inheritance... NOTHING more, so I'm more than lost.
My intention is to transform this code:
Public NotInheritable Class MyType

''' <summary>
''' Gets or sets the value.
''' </summary>
''' <value>The value.</value>
Public Property MyProperty As Integer
    Get
        Return Me._MyValue
    End Get
    Set(ByVal value As Integer)

        If value < Me._MyValueMin Then
            If Me._MyValueThrowRangeException Then
                Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
            End If
            Me._MyValue = Me._MyValueMin

        ElseIf value > Me._MyValueMax Then
            If Me._MyValueThrowRangeException Then
                Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
            End If
            Me._MyValue = Me._MyValueMax

        Else
            Me._MyValue = value

        End If

    End Set
End Property
Private _MyValue As Integer = 0I
Private _MyValueMin As Integer = 0I
Private _MyValueMax As Integer = 10I
Private _MyValueThrowRangeException As Boolean = True
Private _MyValueExceptionMessage As String = String.Format("The valid range is beetwen {0} and {1}",
                                                           Me._MyValueMin, Me._MyValueMax)

End Class

Into something reusable and simplified, like this:
Public NotInheritable Class MyType

    ''' <summary>
    ''' Gets or sets the value.
    ''' Valid range is between 0 and 10.
    ''' </summary>
    ''' <value>The value.</value>
    <RangeAttribute(0, 10, ThrowRangeException:=False, ExceptionMessage:="")>
    Public Property MyProperty As Integer

End Class

So to accomplish this task I've started writting the attribute, but is uncomplete due to an insufficient documentation or examples then I don't know how to procceed to evaluate the values in the setter of a property without adding manually the getter/setter in the property of the code above:
<AttributeUsage(AttributeTargets.Property Or
                AttributeTargets.Parameter Or
                AttributeTargets.ReturnValue Or
                AttributeTargets.Field,
                AllowMultiple:=False)>
Public Class RangeAttribute : Inherits Attribute

    ''' <summary>
    ''' Indicates the Minimum range value.
    ''' </summary>
    Public Minimum As Single

    ''' <summary>
    ''' Indicates the Maximum range value.
    ''' </summary>
    Public Maximum As Single

    ''' <summary>
    ''' Determines whether to throw an exception when the value is not in range.
    ''' </summary>
    Public ThrowRangeException As Boolean

    ''' <summary>
    ''' Indicates the exception message to show when the value is not in range.
    ''' </summary>
    Public ExceptionMessage As String

    ''' <summary>
    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class.
    ''' </summary>
    ''' <param name="Minimum">The minimum range value.</param>
    ''' <param name="Maximum">The maximum range value.</param>
    Public Sub New(ByVal Minimum As Single,
                   ByVal Maximum As Single)

        Me.New(Minimum, Maximum, ThrowRangeException:=False, ExceptionMessage:=String.Empty)

    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class.
    ''' </summary>
    ''' <param name="Minimum">The minimum range value.</param>
    ''' <param name="Maximum">The maximum range value.</param>
    ''' <param name="ThrowRangeException">
    ''' Determines whether to throw an exception when the value is not in range.
    ''' </param>
    Public Sub New(ByVal Minimum As Single,
                   ByVal Maximum As Single,
                   ByVal ThrowRangeException As Boolean,
                   Optional ByVal ExceptionMessage As String = "")

        Me.Minimum = Minimum
        Me.Maximum = Maximum
        Me.ThrowRangeException = ThrowRangeException

        If Not String.IsNullOrEmpty(ExceptionMessage) Then
            Me.ExceptionMessage = ExceptionMessage
        Else
            Me.ExceptionMessage = String.Format("The valid range is beetwen {0} and {1}", Minimum, Maximum)
        End If

    End Sub

End Class

The Attribute code above will ignore the values that are not in range, i understand this is because I'm not evaluating nothing, but I don't know how to do it.

A: Well there are other AOP frameworks/libraries available for .Net platform, Spring.net AOP, KingAOP, FluentAOP, Afterthought,... to name a few.
Here is a proposed solution using Afterthought.
NOTE: We can divide AOP frameworks to two major categories based on techniques used for interception, frameworks which inject the interception code during Compile-time (Compile-time IL weaving) and the ones which do the injection during run-time (run-time IL Weaving or Dynamic IL-weaving). PostSharp supports both methods in current version, each technique has its own pros and cons which is out of scope of this answer, for more information you can refer to http://www.postsharp.net/aop.net
In this sample we chose Compile-time IL-Weaving based on Afterthought framework (Afterthought only supports compile-time IL weaving)
1-Prepration
you can get Afterthought from https://github.com/r1pper/Afterthought/releases (you can download the binaries or you can get the source and compile it by yourself, I go the binary route here)
extract the package there are 2 files Afterthought.dll and Afterthought.Amender.exe, reference to afterthought.dll.
As I said before Afterthought uses compile-time IL weaving and this is exactly what Afterthought.Amender.exe does.
we should call Amender after each build to inject the interception code to our assembly:

Afterthought.Amender.exe "assembly"

we can automate the task by defining a new Post Build event for our project (this is exactly what PostSharp does) Here I copied Afterthought folder in my project's directory and this is my post build event(you may need to change the post event based on your folder location):

"$(ProjectDir)Afterthought\Afterthought.Amender.exe"  "$(TargetPath)"

OK, now we are ready to write our code
2- Sample Code with Range control for Integer numbers between [0,10]
In this sample we define a range control attribute and name it RangeAttribute an try to intercept properties setter method to check if our set value is within the range.
Interception Code and Injection:
Imports Afterthought
Imports System.Reflection

Public Class RangeAmendment(Of T)
    Inherits Amendment(Of T, T)
    Public Sub New()
        MyBase.New()
        Console.WriteLine("Injecting range check here!")

        Properties.AfterSet(Sub(instance As T, pName As String, pvOld As Object, pv As Object, pvNew As Object)

                                Dim p As PropertyInfo = instance.GetType().GetProperty(pName)
                                Dim att As RangeAttribute = p.GetCustomAttribute(Of RangeAttribute)()
                                If att Is Nothing Then Return

                                Dim v As Object = p.GetValue(instance)
                                Dim castedValue As Integer = Convert.ToInt32(v)
                                If (castedValue < att.Min OrElse castedValue > att.Max) Then
                                    Throw New RangeException(p.Name, att.Min, att.Max)
                                End If

                            End Sub)
    End Sub
End Class

Classes and Definitions:
Public Class RangeAttribute
    Inherits Attribute

    Public Property Max As Integer

    Public Property Min As Integer

    Public Sub New(ByVal min As Integer, ByVal max As Integer)
        MyBase.New()
        Me.Min = min
        Me.Max = max
    End Sub
End Class

Public Class RangeException
    Inherits ApplicationException
    Public Sub New(ByVal propertyName As String, ByVal min As Integer, ByVal max As Integer)
        MyBase.New(String.Format("property '{0}' value should be between [{1},{2}]", propertyName, min, max))
    End Sub
End Class

<Amendment(GetType(RangeAmendment(Of )))>
Public Class TestClass
    <Range(0, 10)>
    Public Property Value As Integer

    Public Sub New()
        MyBase.New()
    End Sub
End Class

Sample:
Module Module1

        Sub Main()
            Dim test = New TestClass()

            Try
                Console.WriteLine("try setting value to 5")
                test.Value = 5
                Console.WriteLine(test.Value)

                Console.WriteLine("try setting value to 20")
                test.Value = 20
                Console.WriteLine(test.Value)

            Catch ex As RangeException
                Console.WriteLine(ex.Message)
            End Try

            Console.ReadKey()
        End Sub

    End Module

now when you build your project you should see similar message in your build output:

Injecting range check here!
Amending AopVb3.exe (3.685 seconds)
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

and the output of the console should be :

try setting value to 5
5
try setting value to 20
property 'Value' value should be between [0,10]

A: New, revised, updated answer; also deleted my comments below:
Ok, here is something which can work and is not horribly intrusive.  First, a few words about what you have been looking at.
Attributes provide meta data for a Type or Property etc.  Since it is compiled into the final assembly, the only way to get at them is via Reflection. You cant just add an Attribute to something and have it magically do something without a some code somewhere to activate the methods etc in it.  The attribute itself then has to use Reflection to determine which Type and property it is associated with.  In some cases, there is an entire library to support these activities.
The NET Range you looked at a few days back is much more involved than it appears.  Note that there is no Validate or CheckValue type method, just a Boolean IsValid!  Aside from being a Web-Thing, it also appears to be related to databinding - there is also a RangeAttributeAdapter, a ValidationArttribute (Range inherits from this) and ValidationContext.  The RangeAttribute is simply where the values are specified and there is much, much more going on than just a simple attribute.
Other things, like PostSharp are "Weavers" - simple enough to use (kind of), but they rewrite your code to inject what amounts to wrappers to monitor property changes and call your range validation method(s).  Then more reflection to post the validated data back to the property.
The point: none of the things you have looked at are just Attributes, there is much more going on.
The following is a RangeManager which isn't as transparent as a Weaver but it is simpler.  At the heart is a Range Attribute where you can specify the valid min/max.   But there is also a RangeManager object you need to create which will do the heavy lifting of finding the property, converting from setter method, finding the valid range and then testing it.  It scours the type it is instanced in to find all the relevant properties.
It is frugal on the Reflection calls.  When instanced, the Manager finds all the tagged properties and saves a reference to the RangeAttribute instance so that every time you set a property there are not several new Reflection methods invoked.
If nothing else it shows a little of what is involved.
Imports System.Reflection
Imports System.Globalization

Public Class RangeManager

    <AttributeUsage(AttributeTargets.Property)>
    Public Class RangerAttribute
        Inherits Attribute

        Public Property Minimum As Object
        Public Property Maximum As Object
        Private min As IComparable
        Private max As IComparable

        ' converter: used by IsValid which is not overloaded
        Private Property Conversion() As Func(Of Object, Object)

        Public Property VarType As Type

        Public Sub New(n As Integer, x As Integer)
            Minimum = n
            Maximum = x
            VarType = GetType(Integer)
            min = CType(Minimum, IComparable)
            max = CType(Maximum, IComparable)
            Conversion = Function(v) Convert.ToInt32(v,
                         CultureInfo.InvariantCulture)
        End Sub

        Public Sub New(n As Single, x As Single)
            Minimum = n
            Maximum = x
            VarType = GetType(Single)
            min = CType(Minimum, IComparable)
            max = CType(Maximum, IComparable)
            Conversion = Function(v) Convert.ToSingle(v,
                         CultureInfo.InvariantCulture)
        End Sub

        Public Sub New(n As Double, x As Double)
            Minimum = n
            Maximum = x
            VarType = GetType(Double)
            min = CType(Minimum, IComparable)
            max = CType(Maximum, IComparable)
            Conversion = Function(v) Convert.ToDouble(v,
                         CultureInfo.InvariantCulture)
        End Sub

        ' overridable so you can inherit and provide more complex tests
        ' e.g. String version might enforce Casing or Length
        Public Overridable Function RangeCheck(value As Integer) As Integer
            If min.CompareTo(value) < 0 Then Return CInt(Minimum)
            If max.CompareTo(value) > 0 Then Return CInt(Maximum)
            Return value
        End Function

        Public Overridable Function RangeCheck(value As Single) As Single
            If min.CompareTo(value) < 0 Then Return CSng(Minimum)
            If max.CompareTo(value) > 0 Then Return CSng(Maximum)
            Return value
        End Function

        Public Overridable Function RangeCheck(value As Double) As Double
            If min.CompareTo(value) < 0 Then Return CDbl(Minimum)
            If max.CompareTo(value) > 0 Then Return CDbl(Maximum)
            Return value
        End Function

        ' rather than throw exceptions, provide an IsValid method
        ' lifted from MS Ref Src
        Public Function IsValid(value As Object) As Boolean
            ' dont know the type
            Dim converted As Object

            Try
                converted = Me.Conversion(value)
            Catch ex As InvalidCastException
                Return False
            Catch ex As NotSupportedException
                Return False

                ' ToDo: add more Catches as you encounter and identify them
            End Try

            Dim min As IComparable = CType(Minimum, IComparable)
            Dim max As IComparable = CType(Maximum, IComparable)

            Return min.CompareTo(converted) <= 0 AndAlso
                          max.CompareTo(converted) >= 0
        End Function

    End Class

    ' map of prop names to setter method names
    Private Class PropMap
        Public Property Name As String      ' not critical - debug aide
        Public Property Setter As String

        ' store attribute instance to minimize reflection
        Public Property Range As RangerAttribute

        Public Sub New(pName As String, pSet As String, r As RangerAttribute)
            Name = pName
            Setter = pSet
            Range = r
        End Sub
    End Class

    Private myType As Type             ' not as useful as I'd hoped
    Private pList As List(Of PropMap)

    Public Sub New()
        ' capture calling Type so it does not need to be specified
        Dim frame As New StackFrame(1)
        myType = frame.GetMethod.DeclaringType

        ' create a list of Props and their setter names
        pList = New List(Of PropMap)

        BuildPropMap()
    End Sub

    Private Sub BuildPropMap()
        ' when called from a prop setter, StackFrame reports
        ' the setter name, so map these to the prop name

        Dim pi() As PropertyInfo = myType.GetProperties

        For Each p As PropertyInfo In pi
            ' see if this prop has our attr
            Dim attr() As RangerAttribute =
                DirectCast(p.GetCustomAttributes(GetType(RangerAttribute), True),
                                    RangerAttribute())

            If attr.Count > 0 Then
                ' find it
                For n As Integer = 0 To attr.Count - 1
                    If attr(n).GetType = GetType(RangerAttribute) Then
                        pList.Add(New PropMap(p.Name, p.GetSetMethod.Name, attr(n)))
                        Exit For
                    End If
                Next
            End If

        Next

    End Sub

    ' can be invoked only from Setter!
    Public Function IsValid(value As Object) As Boolean
        Dim frame As New StackFrame(1)
        Dim pm As PropMap = GetPropMapItem(frame.GetMethod.Name)
        Return pm.Range.IsValid(value)
    End Function

    ' validate and force value to a range
    Public Function CheckValue(value As Integer) As Integer
        Dim frame As New StackFrame(1)
        Dim pm As PropMap = GetPropMapItem(frame.GetMethod.Name)

        If pm IsNot Nothing Then
            Return pm.Range.CheckValue(value)
        Else
            Return value      ' or something else
        End If

    End Function

    ' other types omitted for brevity:
    Public Function CheckValue(value As Double) As Double
       ...
    End Function

    Public Function CheckValue(value As Single) As Single
       ...
    End Function

    Private Function GetPropMapItem(setterName As String) As PropMap
        For Each p As PropMap In pList
            If p.Setter = setterName Then
                Return p
            End If
        Next
        Return Nothing
    End Function

End Class

As noted in the code comments, you could inherit RangerAttribute so you could provide more extensive range tests.
Sample usage:
Imports RangeManager

Public Class FooBar

    Public Property Name As String

    Private _IntVal As Integer
    <Ranger(1, 10)>
    Public Property IntValue As Integer
        Get
            Return _IntVal
        End Get
        Set(value As Integer)
            _IntVal = rm.CheckValue(value)
        End Set
    End Property

    ' this is a valid place to use Literal type characters
    ' to make sure the correct Type is identified
    Private _sngVal As Single
    <Ranger(3.01F, 4.51F)>
    Public Property SngValue As Single
        Get
            Return _sngVal
        End Get
        Set(value As Single)
            If rm.IsValid(value) = False Then
                Console.Beep()
            End If
            _sngVal = rm.CheckValue(value)
        End Set
    End Property

    Private rm As RangeManager

    Public Sub New(sName As String, nVal As Integer, dVal As Decimal)
        ' rm is mainly used where you want to validate values
        rm = New RangeManager

        ' test if this can be used in the ctor
        Name = sName
        IntValue = nVal * 100
        DblValue = dVal

    End Sub

End Class

Test Code:
Dim f As New FooBar("ziggy", 1, 3.14)

f.IntValue = 900
Console.WriteLine("val tried: {0} result: {1}", 900.ToString, f.IntValue.ToString)

f.IntValue = -23
Console.WriteLine("val tried: {0} result: {1}", (-23).ToString, f.IntValue.ToString)

f.SngValue = 98.6
Console.WriteLine("val tried: {0} result: {1}", (98.6).ToString, f.SngValue.ToString)

There you have it: 220 lines of code for an Attribute based range validator to replace the following in your setters:
If value < Minimum Then value = Minimum
If value > Maximum Then value = Maximum

To me, the only thing which gets it past my gag factor as far as offloading data validation to something outside the property and class is that the ranges used are listed right there above the property.

Attributes know nothing about the Properties they decorate.  It is up to Something Else to make that connection, and that Something Else will need to use Reflection to get at the Attribute data.
Likewise, Properties know nothing about the Attributes assigned to them because the Attributes are metadata intended for the compiler or Something Else like a serializer.  This Something Else must also use Reflection to make a connection between the two tiers (Type methods and meta data).
In the end, Something Else ends up being either a tool to rewrite your emitted assembly in order to provide the range checking service, or a library to provide the service via a method as shown above.
The hurdle to something being more transparent is that there is not something like a PropertyChanged event to hook onto (see PropertyInfo).

*

*Implement IComparable for use in RangeCheck


text:
Q: Is there an efficient way to calculate execution time in golang? I'm looking for the best way to calculate execution time in go.
func main() {
    start := time.Now()

    time.Sleep(time.Second * 2)

    //something doing here

    elapsed := time.Since(start)
    fmt.Printf("page took %s", elapsed)
}

The code above works fine.
But when I use templates, I have to write it again for each template function.
Is there an efficient way of calculating execution time, including with templates?

A: Use init function
package main

import (
    "fmt"
    "time"
)

var start time.Time

func init() {
    start = time.Now()
}

func getChars(s string) {
    for _, c := range s {
        fmt.Printf("%c at time %v\n", c, time.Since(start))
        time.Sleep(10 * time.Millisecond)
    }
}

func main() {
    fmt.Println("main execution started at time", time.Since(start))

    getChars("Hello")

    fmt.Println("\nmain execution stopped at time", time.Since(start))
}

A: The solution provided by Cerise Limón is perfect.

In addition, if you don't want to pass function name explicitly, you could  accomplish it like this:
func SomeFunction(list *[]string) {
    defer TimeTrack(time.Now())
    // Do whatever you want.
}

func TimeTrack(start time.Time) {
    elapsed := time.Since(start)

    // Skip this function, and fetch the PC and file for its parent.
    pc, _, _, _ := runtime.Caller(1)

    // Retrieve a function object this functions parent.
    funcObj := runtime.FuncForPC(pc)

    // Regex to extract just the function name (and not the module path).
    runtimeFunc := regexp.MustCompile(`^.*\.(.*)$`)
    name := runtimeFunc.ReplaceAllString(funcObj.Name(), "$1")

    log.Println(fmt.Sprintf("%s took %s", name, elapsed))
}

As a result, you would get:

SomeFunction took 15.483µs

For more information, Refer this article: Go Function Tracing
Share the knowledge. :)

A: Efficient way to calculate execution time in golang
You can easily get the execution time on your console using a defer function

defer functions execute even if the code get an error so you always get the execution time.
time package is used to get the time difference.

func main() {
    now := time.Now()
    defer func() {
        fmt.Println(time.Now().Sub(now))
    }()

    // Here you can do whatever you want
}

Or you can use this code
func main() {
        now := time.Now()
        defer func() {
            fmt.Println(time.Since(now))
        }()

        // Here you can do whatever you want
    }

check the code in Playground for more. I added some functionality to recover from an error at the same time print the execution time, even if in the case of a panic error.

A: If you are timing an entire function, then you can use defer to eliminate some of the repetitive code.
// timer returns a function that prints the name argument and
// the elapsed time between the call to timer and the call to
// the returned function. The returned function is intended to
// be used in a defer statement:
//
//   defer timer("sum")()
func timer(name string) func() {
    start := time.Now()
    return func() {
        fmt.Printf("%s took %v\n", name, time.Since(start))
    }
}

func main() {
    defer timer("main")()  // <-- The trailing () is the deferred call
    time.Sleep(time.Second * 2)
}   // prints: main took 2s

Run the example on the playground.
The specification says this about deferred calls:

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns,

The function value timer("main") is evaluated at the defer statement. The timer function records the current time and returns an anonymous function. The returned anonymous function is invoked immediately before the surrounding function returns. The anonymous function computes and prints the elapsed time.

Use runtime.Callers and runtime.CallersFrames to automatically get the name of the calling function.
// callerName returns the name of the function skip frames up the call stack.
func callerName(skip int) string {
    const unknown = "unknown"
    pcs := make([]uintptr, 1)
    n := runtime.Callers(skip+2, pcs)
    if n < 1 {
        return unknown
    }
    frame, _ := runtime.CallersFrames(pcs).Next()
    if frame.Function == "" {
        return unknown
    }
    return frame.Function
}

// timer returns a function that prints the name of the calling
// function and the elapsed time between the call to timer and
// the call to the returned function. The returned function is
// intended to be used in a defer statement:
//
//   defer timer()()
func timer() func() {
    name := callerName(1)
    start := time.Now()
    return func() {
        fmt.Printf("%s took %v\n", name, time.Since(start))
    }
}

func main() {
    defer timer()()
    time.Sleep(time.Second * 2)
}   // prints: main.main took 2s

Note that there is a runtime cost for getting the function name compared to using a string literal as in the first part of this answer.  To avoid measuring the cost of getting the function name, timer gets the name before recording the start time.
Run the example on the playground.

A: Use this as a side reference for an average computation time in Golang
(for 10,100,1000 elements accordingly).

*

*Accessing an element within an array      (1/1/1 sec)

*Binary/dictionary search                  (1/2/3 sec)

*Simple loop/linear search                 (10/100/1,000 sec)

*Quick Sort/Merge Sort/Heap Sort/Tim Sort  (10/200/3,000 sec)

*Bubble Sort/Insertion Sort/Selection Sort (100/10,000/1,000,000 sec)


text:
Q: For which $n \in \mathbb{N}$ do we have $\sum\limits^n_{k=0} k^3 = (\sum\limits^n_{k=0} k)^2$? I have a question that I don't know how to solve.

For which $n \in \mathbb{N}$ do we have $$\sum\limits^n_{k=0} k^3 = (\sum\limits^n_{k=0} k)^2\quad ?$$.

Here's what I've tried:
\begin{align*}\sum\limits^n_{k=0} k^3 = (\sum\limits^n_{k=0} k)^2 & \Leftrightarrow 1+8+27+\cdots+n^3 = (1+2+3+\cdots+n)^2\\ & \Leftrightarrow \sqrt{1+8+27+\cdots+n^3} = 1+2+3+\cdots+n \end{align*}

A: It holds for all $n\in\mathbb N$. Is this sufficiently convincing:
Note. This formula has been known for 2000 years. It is due to Nicomachus of Gerasa.

A: There is a formula for the LHS (sum of consecutive cubes -- proof here) that says it's equal to $\left(\frac{n(n+1)}{2}\right)^2$, which is therefore equal to the RHS for all $n \in \mathbb{N}$


text:
Q: How does $e^{\frac{\ln(t)}{4}} = t^{\frac14}$? $$e^{\frac{\ln(t)}{4}} =e^{\ln(4)} \cdot e^{\frac14} = t^4\cdot e^{\frac14}$$
But $t^4 \cdot e^{\frac14} \neq t^{\frac14}$, so why is the answer $t^{\frac14}$?

A: Suppose $t>0$. Then,
\begin{align}
e^{\frac{\ln(t)}{4}} &= e^{\ln(t^{1/4})} = t^{\frac{1}{4}}.
\end{align}
Also, your first equality is false. The correct rule is $e^{\alpha + \beta} = e^{\alpha} \cdot e^{\beta}$, NOT $e^{\alpha \beta} = e^{\alpha} e^{\beta}$.

A: Note: $x^{a + b} = x^a \times x^b$
then
$\mathrm{Apply\:log\:rule}:\quad \:a^{\log _a\left(b\right)}=b$

A: Let $x=e^{\frac{\ln t}{4}}\quad \forall \ \ x>0$
Taking logarithms on both sides,
$$\ln x=\ln e^{\frac{\ln t}{4}}$$
$$\ln x=\frac{\ln t}{4}\ln e$$
$$\ln x=\frac{\ln t}{4}$$
$$\ln x=\ln t^{1/4}$$
$$x=t^{1/4}$$
$$\therefore e^{\frac{\ln t}{4}}=t^{1/4} $$

A: You are misusing the rules of powers (indices).
The correct rule is $x^{a+b} = x^ax^b$.
But the rule you need to use here is $x^{ab} = (x^a)^b = (x^b)^a$
So here, $e^{\frac{\ln t}{4}} = e^{\ln t \cdot \frac 14} = (e^{\ln t})^{\frac 14} = t^{\frac 14}$.
In the last step, we apply $e^{\ln x} = x$ in the simplification.
Note that you can also equivalently write $e^{\frac{\ln t}{4}} = e^{\ln t \cdot \frac 14} = (e^{\frac 14})^{\ln t}$ but that's not very useful since you can't simplify further.


text:
Q: Jmeter how to find the difference in two time which is stored in string I have below values
String CurrentTime1=${__groovy(${__groovy(Date.parse('yyyy-MM-dd hh:mm:ss.SSS','${Modified_date_1}').getTime(),)},)}
log.info("Current time1 ----> "+CurrentTime1);
String beforetime=vars.get("beforetime");
log.info(" after time -->"+beforetime);
Result:
Current time1 ----> 1611495406402
after time -->1611495402100
As there are stored in string, i am not able to get the difference between these values. Can you please help.
I need to get the difference between current time and before time which are dynamic values.

A: If you want to do this in Groovy - you need to convert the string to Long like:
def before = vars.get('beforetime') as long
def current =  vars.get('CurrentTime1') as long

def delta = current - before
def deltaAsString = delta as String

If you prefer using JMeter Functions - you can go for __longSum()
${__longSum(${CurrentTime1},-${beforetime},)}

More information on this and other JMeter Functions: How to Use JMeter Functions - Part III
But don't mix both approaches like inlining JMeter functions in Groovy code, as per JSR223 Sampler documentation:

When using this feature, ensure your script code does not use JMeter variables or JMeter function calls directly in script code as caching would only cache first replacement. Instead use script parameters.


text:
Q: Javascript clearInterval and setInterval() acting not as expected var timer = 0
var startInterval = function( value ) {
    timer = setInterval( "checkNewPost();", value );
}
var stopInterval = function() {
    clearInterval( timer );
}

jQuery("#centerColumn a").click(function() {
    var a_id = jQuery(this).attr("id");
    var splitValue = a_id.split("-");
    var newValue = splitValue[1];

    if( newValue == "30" ) {
        stopInterval;
        startInterval( 10000 );
    }
    else if( newValue == "1" ) {
        stopInterval;
        startInterval( 20000 );
    }
    else if( newValue == "5" ) {
        stopInterval;
        startInterval( 30000 );
    }
    else if( newValue == "pause" )
        stopInterval;
});

As you can see in my code, the logic is pretty straight forward, when newvalue is equal to 30 it will stop the current interval and restart it with a 10000 seconds on the setInterval. And when newValue is equal to pause, it will stop all the setInterval.
The problem here is it does not act correctly, i'm not sure why? Can someone guide me on this. Your help would be greatly appreciated!
Thanks! :)

A: you need to call the stopInterval function
stopInterval();

I think it won't work without the parentheses

A: Replace
 stopInterval; // fonction simply put on stack

with
 stopInterval(); // fonction call

A: Your calls to stopInterval are missing the parentheses after them so you're currently not actually calling that method.
Try using stopInterval();

A: Everybody else is right, you should use stopInterval(). Also here's a more compact and IMO more readable version of your code:
$('#centerColumn a').click(function () {
    var id = this.id.split('-')[1];
    var value = {
        30: 10000,
        1: 20000,
        5: 30000
    };
    id ==== 'pause' && stopInterval();
    if (value[id]) {
        stopInterval();
        startInterval(value[id]);
    }
});


text:
Q: How to boot Windows from Clover UEFI shell How to boot Windows from Clover UEFI shell.
I don't have access to anything but it. When I normally boot it gives
error : unknown file system
entering rescue mode
grub rescue>_

May be that's because, I deleted a Linux partition.
I had an USB with Clover on it. Now I can access the HDD with the Clover shell. Clover is not showing any boot entries.
Is there any way to boot Windows through it?

A: If you have installed Windows in UEFI mode, you can call the windows loader loader directly typing FS0:\EFI\Microsoft\Boot\bootmgfw.efi Enter into the EFI shell.  If this isn't found try FS0:\EFI\BOOT\BOOTX64.EFI (case doesn't matter).
If you don't find either on volume FS0: then you can try looking for it on other filesystems until you find the one which contains the EFI partition with the Microsoft loader.
Volumes are in the format FS0:,  FS1:, FS2:, FS3: etc.  As the commands cd and ls work in EFI shell (see EFI SHELL COMMANDS - quick reference) to see what is on a volume type:

*

*FS1: Enter do change to volume FS1: (note the :)

*ls Enter to list files and directories in root of the filesystem

*cd EFI Enter to change to directory EFI

*ls Enter to list files and directories in EFI directory

When you find your bootloader you run it by just typing the name (including the .efi suffix) into the shell prompt.

If you have legacy BIOS installation then Clover will not boot it.  You could download rEFInd-flashdrive an put this on a USB key as described in its documentation.  If you then boot that it should be able to automatically detect and boot legacy Windows installations.


text:
Q: Why does 'cal' use weird 08 / ^H / \b terminal code for highlighting and how does that work? When you run cal on Linux, the output for the current month will reverse video highlight the current day.  When I send that output to hexdump -c, I get some interesting results:
0000000               N   o   v   e   m   b   e   r       2   0   1   6
0000010                          \n   S   u       M   o       T   u
0000020   W   e       T   h       F   r       S   a          \n
0000030                       1           2       _  \b       _  \b   3
0000040           4           5          \n       6           7
0000050   8           9       1   0       1   1       1   2          \n
0000060   1   3       1   4       1   5       1   6       1   7       1
0000070   8       1   9          \n   2   0       2   1       2   2
0000080   2   3       2   4       2   5       2   6          \n   2   7
0000090       2   8       2   9       3   0
00000a0                  \n
00000b0                                              \n
00000bc

As you can see, there is an invisible sequence being printed of _\b _\b before the '3' that is highlighted for today. _ being underscore (5F in ascii hex) and \b being Ctrl-H or 08 in ASCII hex. What is this? I know there are a lot of obscure terminal codes, but I would expect it to use something more standard like \e[7m. What is even stranger is that I can't reproduce the same behavior of cal by printing out the same characters using standard printf functions like one of these commands:
/usr/bin/printf "1 2 _\b _\b3 4 5\n"
/usr/bin/printf "1 2 _^H _^H3 4 5\n"

Where ^H is made by pressing Ctrl-V Ctrl-H. But neither of these produce the same inverse video output that cal does. I even tried writing a little C program to do it too. I've also tried with echo -e. The interesting thing is that while it doesn't reverse the video in the terminal, if I pipe the output from less -R, it changes its color to yellow and underlines it. On other terminals I tried it just underlines it. It almost seems like overstriking, but if I use a character other than _ it doesn't work, which makes me think that _\b is a single code sequence. And how does the video for that character then get inversed?
Any insight into this?
The man page says that the output of cal is supposed to be a bit for bit compatible version to the original Unix cal command. So I can only assume this is some ancient code.

A: Ctrl-H is backspace, it moves the cursor one step to the left. Sending an underscore, a backspace, and some other character was the way to underline something on a hard-copy ("paper") terminal back in the good old days. This was used to highlight the current day in the output of cal.
My cal program, when run in konsole does not output this sequence. If I run script -c cal and examine the resulting typescript file, I can see the cal program uses the escape sequence <esc>[7m to switch to inverse mode video.

A:
It almost seems like overstriking

That's exactly what it is.  As at https://superuser.com/a/711019/38062 it helps to think of the action of mechanical typewriters when it comes to Unix terminals.  In this case, the sequence _ BS (the backspace character) before a character is a convention that is used to indicate underlining of that character, because on some terminals that's how one underlined text.  An alternative control sequence is BS _ after the character.  On the original terminals it didn't matter what overstruck what, of course.
FreeBSD ncal, which is what this program is, has two modes of operation when it comes to highlighting.

*

*If its output is a terminal, it looks up the so and se sequences for the current terminal type in the termcap database and emits those either side of the highlighted text.  (There's actually a bug in the code that does this, to do with a buffer on the stack going out of scope and its contents being used later, that no-one seems to have spotted.)

*If its output is not a terminal, it emits the text with each character to be highlighted preceded by a _ BS sequence.

You cannot replicate this by emitting a _ BS sequence to your terminal, unless (of course) your terminal is one of the terminals where this is how one underlines stuff.  This isn't the case for terminal emulators, and almost certainly isn't the case for whatever terminal(s) or terminal emulator(s) you are using here.
You can however filter text that uses this convention, through the ul program, which recognizes this and several other typewriter-like conventions and translates them to whatever the control sequences for one's terminal actually are, looking them up in the termcap database.  You can filter the outputs of your printf commands through ul, too.

On other terminals I tried it just underlines it.

Ironically, filtering the non-terminal-mode output of ncal through the ul program is in fact slightly superior to letting ncal write terminal control sequences itself.  Whereas ncal uses the terminal's standout mode, ul will attempt to use the terminal's actual underline mode (if it has one) when translating the _ BS sequence.  As the termcap manual explains, standout mode can be whatever is suitable to the terminal (including boldface, reverse video, or colours) and isn't necessarily underlining.  On one of your terminals it is clearly a combination of underlining and a colour change.
Moreover, ul also copes with terminals that don't have underline start/end sequences but that do have underline last character sequences.  Ironically, ul will cope if your terminal really is one that underlines by having BS _ after each character, whereas ncal will not cope.
And of course ul doesn't have ncal's buffer handling bug.  ☺

If I pipe the output into less -R, it changes its color to yellow and underlines it.

As you've spotted, the less program understands _ BS sequences and handles them somewhat as the ul program does.  It's not completely the same.  ul can handle sequences involving multiple _ and BS characters, and can also handle similar sequences for boldface.  less cannot.  Contrast what you see from these two:

*

*/usr/bin/printf "1 2 ______\b\b\b\b\b\b 3 _\b4. \b\b\b45 6\n"|ul

*/usr/bin/printf "1 2 ______\b\b\b\b\b\b 3 _\b4. \b\b\b45 6\n"|less

back in the good old days

Sadly, these still are "the good old days".  Don't let people fool you into believing that this is rarely used nowadays.
It's not in the manual, but the source code for ul points out that it is attempting to implement the control sequence processing of a Teletype Model 37 because "that's what nroff outputs".  The GNU replacement for the original Unix nroff program, written long after terminals had gained fancy features like colours, boldface, and italics, is capable of generating ECMA-48 control sequences for colours, boldface, and italics.  It actually does so in the normal case.
nroff, and its GNU replacement, are used for formatting manual pages for display on your terminal.  Sadly, and ironically, starting about 10 years after it was written people proceeded to hobble the GNU tool so that it generated the old Teletype Model 37 sequences from 1968 instead of the "new" ECMA-48 control sequences from 1976 (sic!).  They made man invoke groff with options that modified its default behaviour, and added undocumented files that forced extra ditroff output.
Every time that you read a manual page on your terminal, the manual system is running groff which is dutifully converting the manual source text into an output character stream with these old Teletype Model 37 control sequences, which less or more are converting into your terminal's control sequences.
Further reading

*

*Jonathan de Boyne Pollard (2016). Italics and colour in manual pages on a nosh user-space virtual terminal.  The nosh package.

*Jonathan de Boyne Pollard (2017). An improved manual page for ul.  Proposals.


text:
Q: Problems with jQuery Animating At Click - Twice needed + Wrong effect So I'm trying to make a navigation bar with when you click on a button / span, there appears a div, from the top, to just below the navigation bar.
But, when I click 'Homer', First nothing happens, but the second time I click, then it appears WITH ANOTHER EFFECT, which I didn't use anywhere. [I don't know the effect's name, but the div appears from it's own left top corner.]
This is what I want that's going to happen:
When I click on 'Homer' in the navigation bar, a div comes from off the body to on the body. The div has to move to 0px under the navigation bar, so no space between the navigation bar's bottom, and the div(hidden-homer)'s top. When I click again on Homer, the div(hidden-homer) has to go off the screen again, so moving up.
In JSFiddle, it doesn't work at all...

*

*No errors in Firefox Console, 1 warning: "Use of getPreventDefault() is deprecated.  Use defaultPrevented instead."

*No errors in JSHint (JSFiddle)

So 2 problems:

*

*When I click on 'Homer', nothing happens.

*When I click a second time on 'Homer' -without reloading the page- the div appears with a wrong effect at the wrong position(underneath the navigation bar, so you can't see a part of it).

HTML:
<!DOCTYPE html>

    <link rel="stylesheet" href="main.css">

    <title></title>
    <meta charset="UTF-8">

        Homer
        Marge
        Bart
        Lisa
        Maggie

Homer

Text

Marge

Text

Bart

Text

Lisa

Text

Maggie

Text

jQuery:

CSS:
    body {
    background-color: #0040FF;
    padding: 0px;
    margin: 0px;
}

a {
    outline: none;
}

#nav {
    height: 70px;
    line-height: 70px;
    background-color: #FFBF00;
    font-size: 0px;
    text-decoration: none;
    width: 100%;
    text-align: center;
    font-family: sans-serif;
    margin-bottom: none;
    z-index: 1;
}

#nav span {
    display: inline-block;
    font-size: 35px;
    padding-left: 10px;
    padding-right: 10px;
    text-align: center;
    border-right: 3px solid #0040FF;
    height: 70px;
    cursor: pointer;
    color: #0040FF;
    text-decoration: none;
    font-weight: bold;
}

#nav span:first-child {
    border-left: 3px solid #0040FF;
}

#nav span:hover {
    background-color: #0040FF;
    color: #FFBF00;
}

.hidden {
    width: 100%;
    height: 200px;
    padding-left: 30px;
    background-color: #1C1C1C;
    color: red;
    font-size: 10px;
    top: -250px;
    position: absolute;
    z-index: -1;
    border: 2px solid black;
}

img {
    height: 200px;
    width: 400px;
    transform: rotate(10deg);
}

A: Use a variable to keep track of which direction the DIV has to move each time you click on the element in the nav bar.
var up = true;
$("#nav span:nth-child(1)").click(function() {
    $("#hidden-homer").animate({
        top: up ? "-70px" : "70px"
    }, 100);
    up = !up;
});


text:
Q: JavaFX TableView NullPointerException I have application that display database result in JavaFX TreeView. I made it exactly as mentioned in this Answer.
But when i run the program i get an error like below. The error is pointing to the tblView.setItems(data) method in controller.
how may i solve this..?
java.lang.NullPointerException
    at demofx.FXMLDocumentController.buildData(FXMLDocumentController.java:105)
    at demofx.FXMLDocumentController.initialize(FXMLDocumentController.java:85)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at demofx.DemoFX.start(DemoFX.java:23)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)

This is My .fxml Document
<AnchorPane id="AnchorPane" prefHeight="537.0" prefWidth="736.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="demofx.FXMLDocumentController">
   <children>

      <TableView fx:id="tblVehicle" layoutX="38.0" layoutY="142.0" prefHeight="200.0" prefWidth="660.0">
        <columns>
          <TableColumn fx:id="c_reg" prefWidth="71.0" text="Reg no" />
          <TableColumn fx:id="c_make" prefWidth="79.0" text="Make" />
            <TableColumn fx:id="c_model" prefWidth="75.0" text="Model" />
            <TableColumn fx:id="c_year" prefWidth="75.0" text="year" />
            <TableColumn fx:id="c_color" prefWidth="75.0" text="color" />
            <TableColumn fx:id="c_odo" prefWidth="75.0" text="odo" />
            <TableColumn fx:id="c_status" prefWidth="75.0" text="status" />
            <TableColumn fx:id="c_fuel" prefWidth="75.0" text="fuel" />
            <TableColumn fx:id="c_type" prefWidth="75.0" text="type" />
        </columns>
      </TableView>
      <ComboBox fx:id="cmbVehicleType" layoutX="30.0" layoutY="85.0" onAction="#handleButtonAction" prefWidth="150.0" />
   </children>
</AnchorPane>

This is Controller
public class FXMLDocumentController implements Initializable {

    @FXML
    private Label lblAuto_id;
    @FXML
    private ComboBox cmbVehicleType;
    @FXML
    private Label lblVtype;

    @FXML private TableView<Veh> tblView;

    @FXML private TableColumn <Veh,String>  c_reg;
    @FXML private TableColumn <Veh,String>  c_make;
    @FXML private TableColumn <Veh,String>  c_model;
    @FXML private TableColumn <Veh,String>  c_year;
    @FXML private TableColumn <Veh,String>  c_color;
    @FXML private TableColumn <Veh,String>  c_odo;
    @FXML private TableColumn <Veh,String>  c_status;
    @FXML private TableColumn <Veh,String>  c_fuel;
    @FXML private TableColumn <Veh,String>  c_type;

    private ObservableList<Veh> data;

    DBConnection db = new DBConnection();

    @FXML
    private void handleButtonAction(ActionEvent event) {

    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        c_reg.setCellValueFactory(new PropertyValueFactory<Veh, String>("regno"));
        c_make.setCellValueFactory(new PropertyValueFactory<Veh, String>("make"));
        c_model.setCellValueFactory(new PropertyValueFactory<Veh, String>("model"));
        c_year.setCellValueFactory(new PropertyValueFactory<Veh, String>("type"));
        c_color.setCellValueFactory(new PropertyValueFactory<Veh, String>("status"));
        c_odo.setCellValueFactory(new PropertyValueFactory<Veh, String>("color"));

       buildData();
    }

    public void buildData() {

        try {
            Connection con = db.get_connection();
            data = FXCollections.observableArrayList();
            PreparedStatement stat = con.prepareStatement("SELECT * FROM Vehicle_tbl WHERE Status= 'IN' and V_type='CAR'");
            ResultSet rs = stat.executeQuery();
             while (rs.next()) {
                 Veh ve = new Veh();
                ve.regno.set(rs.getString(1));
                ve.make.set(rs.getString(2));
                ve.model.set(rs.getString(3));
                ve.color.set(rs.getString(4));
                ve.status.set(rs.getString(5));
                ve.type.set(rs.getString(6));
                data.add(ve);
            }
            tblView.setItems(data);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
}

}

This is the POJO Class
public class Veh {

   public SimpleStringProperty regno = new SimpleStringProperty();
   public SimpleStringProperty make = new SimpleStringProperty();
   public SimpleStringProperty model = new SimpleStringProperty();
   public SimpleStringProperty type = new SimpleStringProperty();
   public SimpleStringProperty status = new SimpleStringProperty();
   public SimpleStringProperty color = new SimpleStringProperty();

   public String getRegno(){
       return regno.get();
   }

   public String getMake(){
       return make.get();
   }

   public String getModel(){
       return model.get();
   }

   public String getType(){
       return type.get();
   }

   public String getStatus(){
       return status.get();
   }

   public String getColor(){
       return color.get();
   }

}

A: Problem Solved, in controller i have declared a TableView tblView but in .fxml it is tblVehicle.  both name should be the same, so i changed controller to tblVehicle. now it's working


text:
Q: Force website to allow selection of text? I paid for a language learning website, only to find that I can't even select text throughout the site.
They have an "upgrade" account that will let you download the text in the lesson, and I guess the ability to select text is something they're trying to monetize. That's pretty uncool especially for paying customers.
I don't think I'm in moral gray area trying to select the text.
So can anyone help me figure out how? I've tried a bunch of things, but nothing has worked yet.
The website is Fluent U
Update:
They seem to be using basically this and I'm trying to figure out how to reverse it:
$('bunch-of-things').
 .attr('unselectable', 'on')
 .css('user-select', 'none')
 .on('selectstart', false);
};

A: Ok, figured it out. This seems to do the trick:
$('[unselectable=on]').css('user-select', 'inherit').off('selectstart')

May be useful for others...
Thanks for the input folks :)
Credit Note: @zerkms helped refine my rather broad selector (*) to '[unselectable=on]'


text:
Q: How to make listview to work with itemBuilder i can't seem to solve this problem, for me the code it's correct, but i can't see where the error is. What do i need to return for the listview? Should i put the listview.builder in another place? the listbuild is returning the _buildTitleSection and the _buildCreditCard so i can't seem to understand it.
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            ListView.builder(
               itemCount: users == null ? 0 : users.length,
              itemBuilder: (context, index) { //This is giving me "error" ***
                _buildTitleSection(
                    title: "Names", subTitle: "User informations");
                _buildCreditCard(
                    url: users[index].imageURL,
                    color: Color(0xFF1E90FF),
                    cardExpiration: users[index].cardExpiration,
                    cardHolder: users[index].cardHolder,
                    cardNumber: users[index].cardNumber);
                SizedBox(
                  height: 15,
                );
              },
            ),
          ],
        ),
      ),
    );
  }

***This function has a return type of 'Widget', but doesn't end with a return statement.
Try adding a return statement, or changing the return type to 'void'.

A: Builder methods need to return an object of type Widget so in order to get your code working you need to return your widgets, you have more than one widget, you have to wrap them in a Column or a Row..
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            ListView.builder(
               itemCount: users == null ? 0 : users.length,
              itemBuilder: (context, index) {
                return Column(
                   children: [
                        _buildTitleSection(
                            title: "Names", subTitle: "User informations"),
                        _buildCreditCard(
                            url: users[index].imageURL,
                            color: Color(0xFF1E90FF),
                            cardExpiration: users[index].cardExpiration,
                            cardHolder: users[index].cardHolder,
                            cardNumber: users[index].cardNumber),
                        SizedBox(
                            height: 15,
                        ),
                    ]
                );
              },
            ),
          ],
        ),
      ),
    );
  }


text:
Q: How can I get Merged Cell Range and Next Column Name in Google Apps Script I've merged cells C5:Z5. Now I want to get the column Z5 using GAS as the merge cell boundary. And another thing I've tried to get the next column using GAS. For example, the next column of Z is AA. How can I get the next column using GAS.

A: From what I understood,

*

*If you want to get the Z5 value after merge, simply copy the  z5 value to c5 before  mergeAcross(). So it saves the z5 value to resulting merge cell.

*For getting the next column value, you can access the column values as numericals. simply get the last column value and increment it.

Hope that helps!


text:
Q: Android - Navigation Drawer to implement activity changing I've been reading a lot of questions and tutorials in regards to implementing a Navigation Drawer to change between Fragments. For this question, these implementations are not wanted as I wish to change from one activity, to the next.
I've implemented a custom Sidebar Adaptor with extends ArrayAdapter<String>. This allows to to implement my own styling to my navigation drawer. See the first code snippet below.
public class SidebarAdaptor extends ArrayAdapter<String> {

    Context context;
    int layoutResourceId;
    String data[] = null;

    public SidebarAdaptor(Context context, int layoutResourceId, String[] data)
    {
        // Initiate the ArrayAdapter
        super(context, layoutResourceId, data);

        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ControlHolder holder;

        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ControlHolder();
            TextView control = (TextView)row.findViewById(R.id.textItem);
            holder.control = control;

            row.setTag(holder);
        }
        else
        {
            holder = (ControlHolder)row.getTag();
        }

        String text = data[position];
        holder.control.setText(text);

        return row;
    }

    static class ControlHolder
    {
        TextView control;
    }

}

This adapter is then set in the onCreate function in my MainActivity class. See below.
private void customiseSidebar() {
        SidebarAdaptor sidebarAdaptor = new SidebarAdaptor(
                this,
                R.layout.side_bar_custom_row,
                new String[]{"Login", "Offline Access", "Register", "Forgotten Password"}
        );

        ListView listView1 = (ListView) findViewById(R.id.navList);

        listView1.setAdapter(sidebarAdaptor);
        listView1.setOnItemClickListener(new DrawerItemClickListener());
}

The DrawerItemClickListener class then holds what activity to switch to once the user pressed any of the options in the Navigation Drawer. See the final code snippet below.
package ap.classes;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import ap.ForgottenPassword;
import apMainActivity;
import ap.OfflineAccess;
import ap.RegisterAccount;

public class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);

        }

            /** Swaps fragments in the main content view */
        private void selectItem(int position) {

            switch(position)
            {
                case 0:
                Intent intent = new Intent(MainActivity.this, OfflineAccess.class);
                startActivity(intent);
                break;
            case 1:
                Intent intent = new Intent(MainActivity.this, RegisterAccount.class);
                startActivity(intent);
                break;
            case 2:
                Intent intent = new Intent(MainActivity.this, ForgottenPassword.class);
                startActivity(intent);
                break;

        }
    }

Now I seem to be having three quite substantial issues:

*

*The first being the following error message: MainActivity is not an enclossing class

*The second states that it; Cannont resolve method startActivity in android.content.Intent

*The final issue is, as soon as I click anything in the NavigationDrawer, the drawer then closes without any keypresses being registered.

Thank you Stackoverflow.

A: First fix first two issues:

The first being the following error message: MainActivity is not an enclossing class
The second states that it; Cannont resolve method startActivity in android.content.Intent

According to code you provided you are not in the scope of the Activity class when making call
Intent intent = new Intent(MainActivity.this, OfflineAccess.class);
startActivity(intent);

above tells compiler to call method DrawerItemClickListener.startActivity(Intent intent), and there is no such method. Instead you should pass instance of an activity and call its startActivty method.
Second one MainActivity is not an enclossing class error is thrown because of usage MainActivity.this instead of passing instance of context.
To sum up you could do:
public class DrawerItemClickListener implements ListView.OnItemClickListener {

    private Activity mActivity;
    public DrawerItemClickListener(Activity activity){
        mActivity = activity;
    }

        /** Swaps fragments in the main content view */
    private void selectItem(int position) {

        switch(position)
        {
            case 0:
            Intent intent = new Intent(mActivity, OfflineAccess.class);
            mActivity.startActivity(intent);
            break;
        /.../

    }
}

A: Yes i had faced similar problem.While Fragments with navigation drawer it will be easy but using Activity. You must create a Custom Navigation Drawer. I give my idea.enter code here
public class DrawerItemClickListener extends AppCompatActivity{

    private ListView mDrawerList;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private String mActivityTitle;
    private List<DrawerList> drawerListList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        drawerListList = new ArrayList<>();
        mDrawerList = (ListView) findViewById(R.id.navList);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mActivityTitle = getTitle().toString();

        addDrawerItems();
        setupDrawer();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

    }

    protected abstract int getContentView();

    private void addDrawerItems() {
        drawerListList.add(new DrawerList("1", R.drawable.1));
        drawerListList.add(new DrawerList("2", R.drawable.2));
        drawerListList.add(new DrawerList("3", R.drawable.3));
        drawerListList.add(new DrawerList("4", R.drawable.4));
        drawerListList.add(new DrawerList("5", R.drawable.5));

        CustomDrawerAdapter adapter = new CustomDrawerAdapter(this, R.layout.list_view_menu, drawerListList);
        mDrawerList.setAdapter(adapter);

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    if (id == 0) {
                        intent = new Intent(DrawerItemClickListener .this, FirstActivity.class);

                        startActivity(intent);
                        onDrawerClose();
                    } else if (id == 1) {
                        intent = new Intent(DrawerItemClickListener .this, SecondActivity.class);
                        startActivity(intent);
                        onDrawerClose();
                    } else if (id == 2) {

                        intent = new Intent(DrawerItemClickListener .this, ThirdActivity.class);

                        startActivity(intent);
                        onDrawerClose();
                    } else if (id == 3) {
                        intent = new Intent(DrawerItemClickListener .this, FouthActivity.class);
                        startActivity(intent);
                        onDrawerClose();
                    }
                }
            }
        });
    }

    private void setupDrawer() {
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle("Navigation!");
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mActivityTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        mDrawerToggle.setDrawerIndicatorEnabled(true);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    public void onDrawerClose() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            onBackPressed();
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        // Activate the navigation drawer toggle
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

And Custom Adapter is below
public class CustomDrawerAdapter extends ArrayAdapter<DrawerList> {
    private Context context;
    private List<DrawerList> drawerItemList;
    private int layoutResID;

    public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerList> listItems) {
        super(context, layoutResourceID, listItems);
        this.context = context;
        this.drawerItemList = listItems;
        this.layoutResID = layoutResourceID;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        DrawerItemHolder drawerHolder;
        View view = convertView;

        if (view == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            drawerHolder = new DrawerItemHolder();

            view = inflater.inflate(layoutResID, parent, false);
            drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_itemName);
            drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);

            view.setTag(drawerHolder);

        } else {
            drawerHolder = (DrawerItemHolder) view.getTag();
        }

        DrawerList dItem = this.drawerItemList.get(position);
        drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(dItem.getMenuImage()));
        drawerHolder.ItemName.setText(dItem.getMenuName());

        return view;
    }

    private static class DrawerItemHolder {
        TextView ItemName;
        ImageView icon;
    }
}

And you extend it from each activity like
public class FirstActivity extends DrawerItemClickListener {
..
}

And also Listview Added in each xml layout.
Hope It will be helpful.


text:
Q: Extracting value from nested hashes and arrays in Ruby I have a hash that looks like this:
h = {
  a: [ ["c", "1"],["d","2"],["e","3"],["f","4"] ],
  b: [ ["g","5"],["h","6"],["i","7"],["j","8"] ],
  c: [ ["k","9"],["l","10"],["m","11"],["n","12"] ]
}

What is the best way to extract the numbers from it so it looks like this?
[1,2,3,4,5,6,7,8,9,10,11,12]

I tried a few different things but it always required an external array that I have to push into from a chain of each commands.

A: I would do:
h.values.flatten(1).map{|x,y| y.to_i }

A: This can be done with regular expressions.
hash.values.flatten.select { |v| v.match(/\d/) }.map(&:to_i)

*

*To get the values, use the values method

*To make the array one-dimensional, use the flatten method.

*To filter, use the select method, and find the strings that match a regular-expression for a number.

*Finally, map this array to convert the elements to integers.

A: Use a combination of flatten, select and regexp for digit \d:
=> a = {
  a: [ ["c", "1"],["d","2"],["e","3"],["f","4"] ],
  b: [ ["g","5"],["h","6"],["i","7"],["j","8"] ],
  c: [ ["k","9"],["l","10"],["m","11"],["n","12"] ]
}
=> a.values.flatten.select { |x| x =~ /\d/ }.map(&:to_i)
#> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Other way flat_map, map and ( ):

reach inside the structure with parentheses to make things more explicit

=> a = {
  a: [ ["c", "1"],["d","2"],["e","3"],["f","4"] ],
  b: [ ["g","5"],["h","6"],["i","7"],["j","8"] ],
  c: [ ["k","9"],["l","10"],["m","11"],["n","12"] ]
}
=> a.flat_map { |_, (n, z, i, x)| [n, z, i, x] }.map { |_, i| i.to_i }
#> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

A: Code
def pull_numbers(h)
  h.values.flat_map { |a| a.map { |_,e| Integer(e) } }
end

Example
Your hash, with h[:a][0][0] modified slightly:
h = {
  a: [["8c", "1"],["d","2"],["e","3"],["f","4"]],
  b: [["g","5"],["h","6"],["i","7"],["j","8"]],
  c: [["k","9"],["l","10"],["m","11"],["n","12"]]
}

pull_numbers(h)
  #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Explanation
The steps, for the example above:
c = h.values
  #=> [[["8c", "1"], ["d", "2"], ["e", "3"], ["f", "4"]],
  #    [["g", "5"], ["h", "6"], ["i", "7"], ["j", "8"]],
  #    [["k", "9"], ["l", "10"], ["m", "11"], ["n", "12"]]]

Enumerable#flat_map passes the first element of c and sets the block variable a:
a = [["8c", "1"],["d","2"],["e","3"],["f","4"]]

Then:
a.map { |_,e| Integer(e) }
  #=> [1, 2, 3, 4]

I chose to use Integer(e) rather than e.to_i so that an exception is raised if e is not the string representation of an integer :
Integer("cat")
  #=> ArgumentError: invalid value for Integer(): "cat"

whereas:
"cat".to_i
   #=> 0

In effect, Integer performs a data check before making the conversion.
The other two elements of c are processed similarly.
Variant
One could instead write:
def pull_numbers(h)
  h.values.flatten.each_slice(2).map { |_,e| Integer(e) }
end

A: Here is one way of doing this:
h = {
  a: [ ["c", "1"],["d","2"],["e","3"],["f","4"] ],
  b: [ ["g","5"],["h","6"],["i","7"],["j","8"] ],
  c: [ ["k","9"],["l","10"],["m","11"],["n","12"] ]
}

h.values.flatten(1).collect(&:last).map(&:to_i)
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Or you can do this:
h.to_a.flatten.select { |x| x =~ /\d/ }.map(&:to_i)

A: Short alternative way using Array#transpose method:
> h.values.flatten(1).transpose.last
=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

# with to number conversion
> h.values.flatten(1).transpose.last.map(&:to_i)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Benchmarks
require 'benchmark'

h = {
  a: [ ["c", "1"],["d","2"],["e","3"],["f","4"] ],
  b: [ ["g","5"],["h","6"],["i","7"],["j","8"] ],
  c: [ ["k","9"],["l","10"],["m","11"],["n","12"] ]
}

Benchmark.bm(10) do |x|
  x.report("transpose") do
    1000.times { h.values.flatten(1).transpose.last.map(&:to_i) }
  end
  x.report("collect/map") do
    1000.times { h.values.flatten(1).collect(&:last).map(&:to_i) }
  end
  x.report("regexp") do
    1000.times { h.values.flatten.select { |v| v.match(/\d/) }.map(&:to_i) }
  end
  x.report("Integer") do
    1000.times { h.values.flat_map { |a| a.map { |_,e| Integer(e) } } }
  end
end

Results
                 user     system      total        real
transpose    0.000000   0.000000   0.000000 (  0.006971)
collect/map  0.010000   0.000000   0.010000 (  0.007490)
regexp       0.030000   0.010000   0.040000 (  0.031939)
Integer      0.010000   0.000000   0.010000 (  0.006832)


text:
Q: Is `indefinitely` an equivalence of `endless`? The Wiktionary uses endless and forever to explain indefinitely.
The oxford dictionary defines indefinitely as "for an unlimited or unspecified period of time", I think unlimited just means not sure, which might be a short time, or a long time.
Any comments?

A: Endless and indefinite are slightly different.

*

*An endless state will (of course) never end, under any circumstances. It goes on forever.

*An indefinite state is a state that has no known end point, but could end eventually (or may not). Its end time is not known or not defined (thus, in-definite).

Once the sun goes out, there will be endless darkness in the sky.

The will never be light in the sky again, without the sun. This darkness will go on forever.

I don't know when I will get money to fix my car, so I need to use your car indefinitely.

There is no fixed end point to borrowing your car. I need your car until I get more money, which may or may not happen at some unknown point in the future. I might need to borrow your car forever, or I might need it for a limited time. I don't know, and cannot define the length of time I will need it.
In short, indefinitely allows the possibility of an end (at an unknown time), but it does not promise an end.