Rectangle 27 81

Check if any user logged in (regardless of role)

As answered, you can use app.user to check if any user is logged in.

{% if app.user %}
    # user is logged in (any and all users, regardless of ROLE_*)
{% elseif not app.user %}
    # user is not logged in (note the `not` in the `elseif` statement)
{% endif %}

You can use the is_granted() method to check for ROLES, (The below are all roles assigned by symfony, You may also have you own roles (more below))

{% if is_granted('IS_AUTHENTICATED_FULLY') %}
    # This user entered their credentials THIS session
{% elseif is_granted('IS_AUTHENTICATED_REMEMBERED') %}
    # User logged in via a cookie (ie: Auth again before doing sensitive things)
{% elseif is_granted('IS_AUTHENTICATED_ANONYMOUSLY') %}
    # This is a `guest` or anonymous user
{% endif %}

IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.

IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.

IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.

is_granted()
ROLE_SUPER_ADMIN
ROLE_ADMIN
ROLE_USER
{% if is_granted('ROLE_SUPER_ADMIN') -%}
    # You're `ROLE_SUPER_ADMIN`
{% elseif is_granted('ROLE_ADMIN') -%}
    # You're `ROLE_ADMIN`
{% elseif is_granted('ROLE_USER') -%}
    # You're `ROLE_USER`
{% else %}
    # You're a `nobody` ;P
{%- endif %}

I'm just curious... what -%} and {%- stands for ? why not %} and {% ?

The - removes all trailing whitespace so that it's more readable in the browser source source. More info here: twig.sensiolabs.org/doc/templates.html#whitespace-control

Forgive me for bringing this old question to live again, but I think I read somewhere that app.user will not be null for anonymous users, isn't that correct? Wouldn't that mean that check for app.user is not sufficient?

app.user
The value stored in this variable can be a UserInterface object, any other object which implements a __toString() method or even a regular string.

@user1970395 The first line in the docs read The representation of the current user or null if there is none., so it will be null. A third party bundle could return a string if it's custom UserInterface implementation has a __toString() method which is called when anonymous.

authentication - Symfony 2: How do I check if a user is not logged in ...

authentication symfony twig
Rectangle 27 38

Sort strings as the user wants

When you sort strings to present to the user, you should not use the simple compare: method. Instead, you should always use localized comparison methods such as localizedCompare: or localizedCaseInsensitiveCompare:.

When you sort strings to present to the user, you should not use the simple compare: method. Instead, you should always use localized comparison methods such as localizedCompare: or localizedCaseInsensitiveCompare:.

iphone - What are best practices that you use when writing Objective-C...

iphone objective-c cocoa cocoa-touch ios
Rectangle 27 1326

Only works if the user takes an action

The JavaScript document.execCommand('copy') support has grown, see the links below for browser updates:

  • IE10+ (although this document indicates some support was there from IE5.5+).
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.js-copytextarea');
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
<p>
  <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
  <textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>

The above simple example works great if there is a textarea or input element visible on screen.

In some cases you might wish to copy text to the clipboard without displaying an input / textarea element. This is one example of a way to work around this (basically insert element, copy to clipboard, remove element):

Tested with Google Chrome 44, Firefox 42.0a1 and IE 11.0.8600.17814.

function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");

  //
  // *** This styling is an extra step which is likely not required. ***
  //
  // Why is it here? To ensure:
  // 1. the element is able to have focus and selection.
  // 2. if element was to flash render it has minimal visual impact.
  // 3. less flakyness with selection and copying which **might** occur if
  //    the textarea element is not visible.
  //
  // The likelihood is the element won't even render, not even a flash,
  // so some of these are just precautions. However in IE the element
  // is visible whilst the popup box asking the user for permission for
  // the web page to copy to the clipboard.
  //

  // Place in top-left corner of screen regardless of scroll position.
  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;

  // Ensure it has a small width and height. Setting to 1px / 1em
  // doesn't work as this gives a negative w/h on some browsers.
  textArea.style.width = '2em';
  textArea.style.height = '2em';

  // We don't need padding, reducing the size if it does flash render.
  textArea.style.padding = 0;

  // Clean up any borders.
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';

  // Avoid flash of white box if rendered for any reason.
  textArea.style.background = 'transparent';


  textArea.value = text;

  document.body.appendChild(textArea);

  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }

  document.body.removeChild(textArea);
}


var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
  copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
  <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
  <button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
  <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
  
  </textarea>
</div>

All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the users clipboard when they don't expect it.

Note the full Clipboard API draft specification can be found here: https://w3c.github.io/clipboard-apis/

true
  • and document.queryCommandEnabled('copy') return true if the document.execCommand('copy') will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.

However as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned true from document.queryCommandSupported('copy') if the command was called from a user-initiated thread.

Whilst a simple call to document.execCommand('copy') wrapped in a try/catch block called as a result of a user click will get you the most compatibility use the following has some provisos:

document.execCommand
document.queryCommandSupported
document.queryCommandEnabled
try
catch

Different browser implementations are still in flux and the Clipboard API is still in draft, so remember to do your testing.

how to copy directly from a variable data .i.e.: var str = "word"; ?

@BubuDaba Create a dummy hidden <textarea> with JS, append it to document.body, set the its value to the variable, and use it in pace of copyTextarea, then remove it right after the content is copied.

Is there anything for Safari or any indicators that it will be implemented in Safari?

@AyaSalama the key point is that the "copy" action cannot take place unless it appears to the browser the user is taking the action. The user would not be able to take the action if the element is styled with "display:none" as they would not be able to see it, nor interact with it.

How do I copy to the clipboard in JavaScript? - Stack Overflow

javascript clipboard copy-paste
Rectangle 27 1302

Only works if the user takes an action

The JavaScript document.execCommand('copy') support has grown, see the links below for browser updates:

  • IE10+ (although this document indicates some support was there from IE5.5+).
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.js-copytextarea');
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
<p>
  <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
  <textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>

The above simple example works great if there is a textarea or input element visible on screen.

In some cases you might wish to copy text to the clipboard without displaying an input / textarea element. This is one example of a way to work around this (basically insert element, copy to clipboard, remove element):

Tested with Google Chrome 44, Firefox 42.0a1 and IE 11.0.8600.17814.

function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");

  //
  // *** This styling is an extra step which is likely not required. ***
  //
  // Why is it here? To ensure:
  // 1. the element is able to have focus and selection.
  // 2. if element was to flash render it has minimal visual impact.
  // 3. less flakyness with selection and copying which **might** occur if
  //    the textarea element is not visible.
  //
  // The likelihood is the element won't even render, not even a flash,
  // so some of these are just precautions. However in IE the element
  // is visible whilst the popup box asking the user for permission for
  // the web page to copy to the clipboard.
  //

  // Place in top-left corner of screen regardless of scroll position.
  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;

  // Ensure it has a small width and height. Setting to 1px / 1em
  // doesn't work as this gives a negative w/h on some browsers.
  textArea.style.width = '2em';
  textArea.style.height = '2em';

  // We don't need padding, reducing the size if it does flash render.
  textArea.style.padding = 0;

  // Clean up any borders.
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';

  // Avoid flash of white box if rendered for any reason.
  textArea.style.background = 'transparent';


  textArea.value = text;

  document.body.appendChild(textArea);

  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }

  document.body.removeChild(textArea);
}


var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
  copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
  <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
  <button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
  <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
  
  </textarea>
</div>

All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the users clipboard when they don't expect it.

Note the full Clipboard API draft specification can be found here: https://w3c.github.io/clipboard-apis/

true
  • and document.queryCommandEnabled('copy') return true if the document.execCommand('copy') will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.

However as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned true from document.queryCommandSupported('copy') if the command was called from a user-initiated thread.

Whilst a simple call to document.execCommand('copy') wrapped in a try/catch block called as a result of a user click will get you the most compatibility use the following has some provisos:

document.execCommand
document.queryCommandSupported
document.queryCommandEnabled
try
catch

Different browser implementations are still in flux and the Clipboard API is still in draft, so remember to do your testing.

how to copy directly from a variable data .i.e.: var str = "word"; ?

@BubuDaba Create a dummy hidden <textarea> with JS, append it to document.body, set the its value to the variable, and use it in pace of copyTextarea, then remove it right after the content is copied.

Is there anything for Safari or any indicators that it will be implemented in Safari?

Where it the textarea.select() coming from?

@AyaSalama the key point is that the "copy" action cannot take place unless it appears to the browser the user is taking the action. The user would not be able to take the action if the element is styled with "display:none" as they would not be able to see it, nor interact with it.

How do I copy to the clipboard in JavaScript? - Stack Overflow

javascript clipboard copy-paste
Rectangle 27 1299

Only works if the user takes an action

The JavaScript document.execCommand('copy') support has grown, see the links below for browser updates:

  • IE10+ (although this document indicates some support was there from IE5.5+).
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.js-copytextarea');
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
<p>
  <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
  <textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>

The above simple example works great if there is a textarea or input element visible on screen.

In some cases you might wish to copy text to the clipboard without displaying an input / textarea element. This is one example of a way to work around this (basically insert element, copy to clipboard, remove element):

Tested with Google Chrome 44, Firefox 42.0a1 and IE 11.0.8600.17814.

function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");

  //
  // *** This styling is an extra step which is likely not required. ***
  //
  // Why is it here? To ensure:
  // 1. the element is able to have focus and selection.
  // 2. if element was to flash render it has minimal visual impact.
  // 3. less flakyness with selection and copying which **might** occur if
  //    the textarea element is not visible.
  //
  // The likelihood is the element won't even render, not even a flash,
  // so some of these are just precautions. However in IE the element
  // is visible whilst the popup box asking the user for permission for
  // the web page to copy to the clipboard.
  //

  // Place in top-left corner of screen regardless of scroll position.
  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;

  // Ensure it has a small width and height. Setting to 1px / 1em
  // doesn't work as this gives a negative w/h on some browsers.
  textArea.style.width = '2em';
  textArea.style.height = '2em';

  // We don't need padding, reducing the size if it does flash render.
  textArea.style.padding = 0;

  // Clean up any borders.
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';

  // Avoid flash of white box if rendered for any reason.
  textArea.style.background = 'transparent';


  textArea.value = text;

  document.body.appendChild(textArea);

  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }

  document.body.removeChild(textArea);
}


var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
  copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
  <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
  <button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
  <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
  
  </textarea>
</div>

All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the users clipboard when they don't expect it.

Note the full Clipboard API draft specification can be found here: https://w3c.github.io/clipboard-apis/

true
  • and document.queryCommandEnabled('copy') return true if the document.execCommand('copy') will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.

However as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned true from document.queryCommandSupported('copy') if the command was called from a user-initiated thread.

Whilst a simple call to document.execCommand('copy') wrapped in a try/catch block called as a result of a user click will get you the most compatibility use the following has some provisos:

document.execCommand
document.queryCommandSupported
document.queryCommandEnabled
try
catch

Different browser implementations are still in flux and the Clipboard API is still in draft, so remember to do your testing.

how to copy directly from a variable data .i.e.: var str = "word"; ?

@BubuDaba Create a dummy hidden <textarea> with JS, append it to document.body, set the its value to the variable, and use it in pace of copyTextarea, then remove it right after the content is copied.

Is there anything for Safari or any indicators that it will be implemented in Safari?

Where it the textarea.select() coming from?

@AyaSalama the key point is that the "copy" action cannot take place unless it appears to the browser the user is taking the action. The user would not be able to take the action if the element is styled with "display:none" as they would not be able to see it, nor interact with it.

How do I copy to the clipboard in JavaScript? - Stack Overflow

javascript clipboard copy-paste
Rectangle 27 115

Sign in the user before accessing the database

By default the database in a project in the new Firebase Console is only readable/writeable by authenticated users:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.

The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This makes your new database readable and writeable by everyone. Be certain to secure your database again before you go into production, otherwise somebody is likely to start abusing it.

For a (slightly) more time-consuming, but more secure, solution, call one of the signIn... methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:

firebase.auth().signInAnonymously().catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

And then attach your listeners when the sign-in is detected

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var userRef = app.dataInfo.child(app.users);

    var useridRef = userRef.child(app.userid);

    useridRef.set({
      locations: "",
      theme: "",
      colorScheme: "",
      food: ""
    });

  } else {
    // User is signed out.
    // ...
  }
  // ...
});

Thanks - used the insecure fix and quoted your answer in a reply to a similar question to progress past Firebase permission issues in this Ember tutorial. But where do we add the (secure) anonymous auth code?

javascript - Firebase Permission Denied - Stack Overflow

javascript firebase firebase-database firebase-security
Rectangle 27 303

To list all of the screen sessions for a user, run the following command as that user:

screen -ls

To see all screen sessions on a specific machine you can do:

ls -laR /var/run/screen/
gentle ~ # ls -laR /var/run/screen/

/var/run/screen/:
total 1
drwxrwxr-x  4 root utmp   96 Mar  1  2005 .
drwxr-xr-x 10 root root  840 Feb  1 03:10 ..
drwx------  2 josh users  88 Jan 13 11:33 S-josh
drwx------  2 root root   48 Feb 11 10:50 S-root

/var/run/screen/S-josh:
total 0
drwx------ 2 josh users 88 Jan 13 11:33 .
drwxrwxr-x 4 root utmp  96 Mar  1  2005 ..
prwx------ 1 josh users  0 Feb 11 10:41 12931.pts-0.gentle

/var/run/screen/S-root:
total 0
drwx------ 2 root root 48 Feb 11 10:50 .
drwxrwxr-x 4 root utmp 96 Mar  1  2005 ..

This is a rather brilliantly Unixy use of Unix Sockets wrapped in filesystem permissions to handle security, state, and streams.

I wonder why this answer, one that answered the question perfectly, got a downvote...

linux - How to list running screen sessions? - Stack Overflow

linux bash command-line gnu-screen
Rectangle 27 1503

Settings.Secure#ANDROID_ID returns the Android ID as an unique for each user 64-bit hex string.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

It's known to be null sometimes, it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone.

I think we need to be careful about using ANDROID_ID in hash in first answer about because it may not be set when app is first run, may be set later, or may even change in theory, hence unique ID may change

ANDROID_ID no longer uniquely identifies a device (as of 4.2): stackoverflow.com/a/13465373/150016

Is there a unique Android device ID? - Stack Overflow

android device uniqueidentifier
Rectangle 27 261

Is the ??? free define by the user?

or it is general from the HTML?

If you want to send the following data to the web server:

name = John
age = 12
application/x-www-form-urlencoded
name=John&age=12

As you might see, the server knows that parameters are separated by &, and if & is required as a parameter value, it will be encoded.

Now, how does the server knows where a parameter value starts and ends when it receives an HTTP request using multipart/form-data? Using the boundary, similar to &.

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data sent.

  • Use a value that won't appear in the HTTP data sent to the server.
  • Be consistent and use the same value all over the request.

Yout have to add an extra "--" in the end of boundary.

You can read it in documentation. Boundary ending have to have extra two hypens "--" Link: w3.org/TR/html401/interact/forms.html#h-17.13.4.2

Great answer. A boundary is just the 'key' to separate the multiple "parts" of a multipart payload. Normally something like '&' is enough to separate the variables but you need something more unique to separate the payloads within the payload.

I think that the boundary value as declared in the Content-Type header will actually be -XXX--- because an extra "--" should be written when separating the parts (hence the ---XXX---)

html - What is the boundary in multipart/form-data? - Stack Overflow

html http forms
Rectangle 27 258

Is the ??? free define by the user?

or it is general from the HTML?

If you want to send the following data to the web server:

name = John
age = 12
application/x-www-form-urlencoded
name=John&age=12

As you might see, the server knows that parameters are separated by &, and if & is required as a parameter value, it will be encoded.

Now, how does the server knows where a parameter value starts and ends when it receives an HTTP request using multipart/form-data? Using the boundary, similar to &.

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data sent.

  • Use a value that won't appear in the HTTP data sent to the server.
  • Be consistent and use the same value all over the request.

Yout have to add an extra "--" in the end of boundary.

You can read it in documentation. Boundary ending have to have extra two hypens "--" Link: w3.org/TR/html401/interact/forms.html#h-17.13.4.2

Great answer. A boundary is just the 'key' to separate the multiple "parts" of a multipart payload. Normally something like '&' is enough to separate the variables but you need something more unique to separate the payloads within the payload.

I think that the boundary value as declared in the Content-Type header will actually be -XXX--- because an extra "--" should be written when separating the parts (hence the ---XXX---)

html - What is the boundary in multipart/form-data? - Stack Overflow

html http forms
Rectangle 27 542

I am not a fan of User Agent sniffing, but here is how you would do it:

var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

Another way, relying on the deprecated navigator.platform:

var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
iOS

Microsoft injected the word iPhone in IE11's userAgent in order to try and fool Gmail somehow. Therefore we need to exclude it. More info about this here and here.

userAgent

Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 930) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537

function iOS() {

  var iDevices = [
    'iPad Simulator',
    'iPhone Simulator',
    'iPod Simulator',
    'iPad',
    'iPhone',
    'iPod'
  ];

  if (!!navigator.platform) {
    while (iDevices.length) {
      if (navigator.platform === iDevices.pop()){ return true; }
    }
  }

  return false;
}
iOS()
true
false
navigator.userAgent
navigator.platform
history API
matchMedia API
webAudio API
WebSpeech API

Note: The following code is not reliable and will break if any of these HTML5 features is deprecated in a newer iOS version. You have been warned!

function iOSversion() {

  if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
    if (!!window.indexedDB) { return 'iOS 8 and up'; }
    if (!!window.SpeechSynthesisUtterance) { return 'iOS 7'; }
    if (!!window.webkitAudioContext) { return 'iOS 6'; }
    if (!!window.matchMedia) { return 'iOS 5'; }
    if (!!window.history && 'pushState' in window.history) { return 'iOS 4'; }
    return 'iOS 3 or earlier';
  }

  return 'Not an iOS device';
}

Thanks Pierre - this code seems simpler though, I just wonder whether I can just specify 'iOS' rather than having to type out all the separate iDevices.... if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) { // Do something }

document.write("Browser Version: " + navigator.appVersion)

What you're doing in the second snippet is feature inference, not feature detection. Feature detection is testing features that you're actually going to use, whereas what you're doing is testing features that you happen to know were introduced in a particular version of the OS and inferring the OS version from them. This is fragile because future versions of iOS could remove these features.

var iOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);

Just a note - the navigator.platform array doesn't work on the iPad Simulator because it has the entire phrase "iPad Simulator" in the platform string.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Detect if device is iOS - Stack Overflow

javascript ios browser browser-feature-detection
Rectangle 27 541

I am not a fan of User Agent sniffing, but here is how you would do it:

var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

Another way, relying on the deprecated navigator.platform:

var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
iOS

Microsoft injected the word iPhone in IE11's userAgent in order to try and fool Gmail somehow. Therefore we need to exclude it. More info about this here and here.

userAgent

Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 930) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537

function iOS() {

  var iDevices = [
    'iPad Simulator',
    'iPhone Simulator',
    'iPod Simulator',
    'iPad',
    'iPhone',
    'iPod'
  ];

  if (!!navigator.platform) {
    while (iDevices.length) {
      if (navigator.platform === iDevices.pop()){ return true; }
    }
  }

  return false;
}
iOS()
true
false
navigator.userAgent
navigator.platform
history API
matchMedia API
webAudio API
WebSpeech API

Note: The following code is not reliable and will break if any of these HTML5 features is deprecated in a newer iOS version. You have been warned!

function iOSversion() {

  if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
    if (!!window.indexedDB) { return 'iOS 8 and up'; }
    if (!!window.SpeechSynthesisUtterance) { return 'iOS 7'; }
    if (!!window.webkitAudioContext) { return 'iOS 6'; }
    if (!!window.matchMedia) { return 'iOS 5'; }
    if (!!window.history && 'pushState' in window.history) { return 'iOS 4'; }
    return 'iOS 3 or earlier';
  }

  return 'Not an iOS device';
}

Thanks Pierre - this code seems simpler though, I just wonder whether I can just specify 'iOS' rather than having to type out all the separate iDevices.... if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) { // Do something }

document.write("Browser Version: " + navigator.appVersion)

What you're doing in the second snippet is feature inference, not feature detection. Feature detection is testing features that you're actually going to use, whereas what you're doing is testing features that you happen to know were introduced in a particular version of the OS and inferring the OS version from them. This is fragile because future versions of iOS could remove these features.

var iOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);

Just a note - the navigator.platform array doesn't work on the iPad Simulator because it has the entire phrase "iPad Simulator" in the platform string.

javascript - Detect if device is iOS - Stack Overflow

javascript ios browser browser-feature-detection
Rectangle 27 159

Starting end August 2012, the API has been updated to allow you to retrieve user's profile pictures in varying sizes. Add the optional width and height fields as URL parameters:

where WIDTH and HEIGHT are your requested dimension values.

This will return a profile picture with a minimum size of WIDTH x HEIGHT while trying to preserve the aspect ratio. For example,

{
      "data": {
        "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/c0.19.180.142/s148x148/2624_134501175351_4831452_a.jpg",
        "width": 148,
        "height": 117,
        "is_silhouette": false
      }
   }

To get a user's profile picture, call

https://graph.facebook.com/USER_ID/picture

where USER_ID can be the user id number or the user name.

To get a user profile picture of a specific size, call

where SIZE should be replaced with one of the words

square
small
normal
large

depending on the size you want.

This call will return a URL to a single image with its size based on your chosen type parameter.

https://graph.facebook.com/USER_ID/picture?type=small

returns a URL to a small version of the image.

The API only specifies the maximum size for profile images, not the actual size.

maximum width and height of 50pixels.

maximum width of 50pixels and a maximum height of 150pixels.

maximum width of 100pixels and a maximum height of 300pixels.

maximum width of 200pixels and a maximum height of 600pixels.

If you call the default USER_ID/picture you get the square type.

If you call (as per above example)

it will return a JSON response if you're using one of the Facebook SDKs request methods. Otherwise it will return the image itself. To always retrieve the JSON, add:

&redirect=false
https://graph.facebook.com/redbull/picture?width=140&height=110&redirect=false

I still get the same response as in my answer. You can try it out in the Graph Explorer on Facebook Developers at developers.facebook.com/tools/explorer. Enter 'redbull/picture?width=140&height=110' and see the response. My answer assumes you're calling this using one of the Facebook SDKs API / request methods, which will return a JSON response.

@GunnarKarlsson you are missing the &redirect=false to return the JSON data instead of redirect to the image

@andrewtweber thanks a lot. I've added a clarification to the answer.

It's July 2015 and this no longer works. (error: "Cannot query users by their username")

php - Facebook API - How do I get a Facebook user's profile image thro...

php facebook
Rectangle 27 1503

Settings.Secure#ANDROID_ID returns the Android ID as an unique for each user 64-bit hex string.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

It's known to be null sometimes, it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone.

I think we need to be careful about using ANDROID_ID in hash in first answer about because it may not be set when app is first run, may be set later, or may even change in theory, hence unique ID may change

ANDROID_ID no longer uniquely identifies a device (as of 4.2): stackoverflow.com/a/13465373/150016

Is there a unique Android device ID? - Stack Overflow

android device uniqueidentifier
Rectangle 27 1503

Settings.Secure#ANDROID_ID returns the Android ID as an unique for each user 64-bit hex string.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

It's known to be null sometimes, it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone.

I think we need to be careful about using ANDROID_ID in hash in first answer about because it may not be set when app is first run, may be set later, or may even change in theory, hence unique ID may change

ANDROID_ID no longer uniquely identifies a device (as of 4.2): stackoverflow.com/a/13465373/150016

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Is there a unique Android device ID? - Stack Overflow

android device uniqueidentifier
Rectangle 27 1503

Settings.Secure#ANDROID_ID returns the Android ID as an unique for each user 64-bit hex string.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

It's known to be null sometimes, it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone.

I think we need to be careful about using ANDROID_ID in hash in first answer about because it may not be set when app is first run, may be set later, or may even change in theory, hence unique ID may change

ANDROID_ID no longer uniquely identifies a device (as of 4.2): stackoverflow.com/a/13465373/150016

Is there a unique Android device ID? - Stack Overflow

android device uniqueidentifier
Rectangle 27 1497

Settings.Secure#ANDROID_ID returns the Android ID as an unique for each user 64-bit hex string.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

It's known to be null sometimes, it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone.

I think we need to be careful about using ANDROID_ID in hash in first answer about because it may not be set when app is first run, may be set later, or may even change in theory, hence unique ID may change

ANDROID_ID no longer uniquely identifies a device (as of 4.2): stackoverflow.com/a/13465373/150016

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Is there a unique Android device ID? - Stack Overflow

android device uniqueidentifier
Rectangle 27 223

Read-Host is a simple option for getting string input from a user.

$name = Read-Host 'What is your username?'

To hide passwords you can use:

$pass = Read-Host 'What is your password?' -AsSecureString
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))

As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].

To access information without invoking a method, leave the parentheses off:

PS> $Host.UI.Prompt

MemberType          : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
                    ompt(string caption, string message, System.Collections.Ob
                    jectModel.Collection[System.Management.Automation.Host.Fie
                    ldDescription] descriptions)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Collections.Generic.Dictionary[string,psobject] Pro
                    mpt(string caption, string message, System.Collections.Obj
                    ectModel.Collection[System.Management.Automation.Host.Fiel
                    dDescription] descriptions)
Name                : Prompt
IsInstance          : True
$Host.UI.Prompt.OverloadDefinitions
<Return Type> <Method Name>(<Parameters>)

Thanks, @Rynant. Accepted answer for being the only one who actually answered my main question! ;) All the other information is really helpful too, especially as I'm still groping my way in PS.

No problem, @AJ. Another way to get information about a method is to leave off the parentheses. I'll add an example to my answer.

FYI you can also use Get-Credential if you're getting usernames and passwords.

Prompt for user input in PowerShell - Stack Overflow

powershell
Rectangle 27 114

Create a column called is_active for the User model.

Then add the code below to the User model:

class User < ActiveRecord::Base
  #this method is called by devise to check for "active" state of the model
  def active_for_authentication?
    #remember to call the super
    #then put our own check to determine "active" state using 
    #our own "is_active" column
    super and self.is_active?
  end
end

thanks! that is what i have needed.

the method is now called active_for_authentication?
active_for_authentication?
active?

ruby on rails - Devise - How do I forbid certain users from signing in...

ruby-on-rails devise
Rectangle 27 32

You can add a method to the User

from django.contrib import auth
auth.models.User.add_to_class('get_related_foo_models', get_related_foo_models)

Make sure, you have this code within the models.py or some other file which gets imported in the startup of django.

I'm pretty sure this is monkey patching is is generally frowned upon. See discussion here: stackoverflow.com/a/965859/406157

@DerekAdair We're talking about adding a method to the class. Using a OneToOneField entails modifying the database, which is 100% unnecessary to attain the goal of adding a method.

@Louis Just because you can does not mean you should, there are many side effects to this type of approach. In certain situations those side effects are negligible, but the OneToOneField is the "proper" way to achieve this. I suppose my comment would be better worded like, "Its almost always the way to do it".

@DerekAdair You would be hard pressed to find any writing of mine where I have an argument that goes "you should, because you can".

Django User model, adding function - Stack Overflow

django django-models django-users