Programs & Examples On #Facebook

Facebook Platform lets developers integrate their apps directly into the Facebook social networking service. Use this tag for questions which may arise when developing FOR Facebook. This tag is NOT for support questions about using the Facebook website or the official Facebook app. It is also NOT for questions of the “I want to implement a feature similar to what Facebook has” variety.

Facebook user url by id

The marked answer seems outdated and it won't work.

Facebook now only gives unique ID related to app which isn't equal to userId and profileUrl and username will come out to be empty.

Doing me?fields=id,name,links is also depreciated after Graph Version 2.4

The only option now is to request for user_links permission from your developer console.

enter image description here

and the pass it in scope when doing facebook login

scope: ['user_link'] }

or by doing an api call

Facebook Graph API : get larger pictures in one request

You can use full_picture instead of picture key to get full size image.

How to clear Facebook Sharer cache?

I just posted a simple solution that takes 5 seconds here on a related post here - Facebook debugger: Clear whole site cache

short answer... change your permalinks on a worpdress site in the permalinks settings to a custom one. I just added an underscore.
/_%postname%/
then facebook scrapes them all as new urls, new posts.

The developers of this app have not set up this app properly for Facebook Login?

Okay - sandbox is off, domain has to be correct because 99% of the users can reach the app, and "all its live features available to the general public" is set to yes.

Running Facebook application on localhost

I wrote a tutorial about this a while ago.

The most important point is the "Site URL":

Site URL: http://localhost/app_name/

Where the folder structure is something like:

app_name
¦   index.php
¦
+---canvas
¦   ¦   index.php
¦   ¦
¦   +---css
¦           main.css
¦           reset.css
¦
+---src
        facebook.php
        fb_ca_chain_bundle.crt

EDIT:
Kavya: how does the FB server recognize my localhost even without an IP or port??

I don't think this has anything to do with Facebook, I guess since the iframe src parameter is loaded from client-side it'll treat your local URL as if you put it directly on your browser.

For example have a file on your online server with content (e.g. online.php):

<iframe src="http://localhost/test.php" width="100%" height="100%">
    <p>Not supported!</p>
</iframe>

And on your localhost root directory, have the file test.php:

<?php echo "Hello from Localhost!"; ?>

Now visit http://your_domain.com/online.php you will see your localhost file's content!

This is why realtime subscriptions and deauthorize callbacks (just to mention) won't work with localhost URLs! because Facebook will ping (send http requests) to these URLs but obviously Facebook server won't translate those URLs to yours!

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.

  • this is against Facebook policy, so depending on the country where you live, this may not be legal
  • you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
  • when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
  • this is bypassing the OAuth concept
  • on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API

Sample implementation using WatiN:

class FacebookUser
{
  public string Name { get; set; }
  public long Id { get; set; }
}

public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
  var users = new List<FacebookUser>();
  Settings.Instance.MakeNewIeInstanceVisible = false;
  using (var browser = new IE("https://www.facebook.com"))
  {
    try
    {
      browser.TextField(Find.ByName("email")).Value = email;
      browser.TextField(Find.ByName("pass")).Value = password;
      browser.Form(Find.ById("login_form")).Submit();
      browser.WaitForComplete();
    }
    catch (ElementNotFoundException)
    {
      // We're already logged in
    }
    browser.GoTo("https://www.facebook.com/friends");
    var watch = new Stopwatch();
    watch.Start();

    Link previousLastLink = null;
    while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
    {
      var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
                       && l.GetAttributeValue("data-hovercard").Contains("user.php")
                       && l.Text != null
                     ).LastOrDefault();

      if (lastLink == null || previousLastLink == lastLink)
      {
        break;
      }

      var ieElement = lastLink.NativeElement as IEElement;
      if (ieElement != null)
      {
        var htmlElement = ieElement.AsHtmlElement;
        htmlElement.scrollIntoView();
        browser.WaitForComplete();
      }

      previousLastLink = lastLink;
    }

    var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
      && l.GetAttributeValue("data-hovercard").Contains("user.php")
      && l.Text != null
    ).ToList();

    var idRegex = new Regex("id=(?<id>([0-9]+))");
    foreach (var link in links)
    {
      string hovercard = link.GetAttributeValue("data-hovercard");
      var match = idRegex.Match(hovercard);
      long id = 0;
      if (match.Success)
      {
        id = long.Parse(match.Groups["id"].Value);
      }
      users.Add(new FacebookUser
      {
        Name = link.Text,
        Id = id
      });
    }
  }
  return users;
}

Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.

FB OpenGraph og:image not pulling images (possibly https?)

OK... I realize this thread is old and overcrowded, but in case someone comes in like I did struggling to get their og:image tag to work right in Facebook, here's the trick that worked for me:

do NOT use this link:

https://developers.facebook.com/tools/debug/sharing/?q=https%3A%2F%2Fwww.google.com

to work through your problem. Or if you do, immediately scroll down to the bottom and click on Scrape VIA API.

https://developers.facebook.com/tools/explorer/?method=POST&path=%3Fscrape%3Dtrue%26id%3Dhttps%3A%2F%2Fwww.google.com&version=v5.0

There are errors displayed in the explorer tool that are NOT shown in the "debug" tool. Maddening!!! (in my case, a space in the image filename knocked my image out silently in the debug tool, but it showed the error in the explorer tool).

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

Seems like both the conditions are met, perhaps key('contact') is the issue

 if(store.telefon) {
    detailItems.push( new DetailItem('contact', store.telefon, 'Anrufen', 'fontawesome|phone') );
}
if(store.email) {
    detailItems.push( new DetailItem('contact', store.email, 'Email', 'fontawesome|envelope') );
}

Facebook share button and custom text

We use something like this [use in one line]:

<a title="send to Facebook" 
  href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
  target="_blank">
  <span>
    <img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook 
  </span>
</a>

Redirecting to authentication dialog - "An error occurred. Please try again later"

The issue resolved after I updated the 'appID' and 'secret' and then pushed the change back to heroku (i.e. - 'git push heroku master')

The key is not to forget to push the changes back to heroku master. Very easy to overlook if you're use to testing on localhost.

Hope this helps.

IOS - How to segue programmatically using swift

What you want to do is really important for unit testing. Basically you need to create a small local function in the view controller. Name the function anything, just include the performSegueWithIndentifier.

func localFunc() {
    println("we asked you to do it")
    performSegueWithIdentifier("doIt", sender: self)
}

Next change your utility class FBManager to include an initializer that takes an argument of a function and a variable to hold the ViewController's function that performs the segue.

public class UtilClass {

    var yourFunction : () -> ()

    init (someFunction: () -> ()) {
        self.yourFunction = someFunction
        println("initialized UtilClass")
    }

    public convenience init() {
        func dummyLog () -> () {
            println("no action passed")
        }
        self.init(dummyLog)
    }

    public func doThatThing() -> () {
        // the facebook login function
        println("now execute passed function")
        self.yourFunction()
        println("did that thing")
    }
}

(The convenience init allows you to use this in unit testing without executing the segue.)

Finally, where you have //todo: segue to the next view???, put something along the lines of:

self.yourFunction()

In your unit tests, you can simply invoke it as:

let f = UtilClass()
f.doThatThing()

where doThatThing is your fbsessionstatechange and UtilClass is FBManager.

For your actual code, just pass localFunc (no parenthesis) to the FBManager class.

How to get the Facebook user id using the access token

If you want to use Graph API to get current user ID then just send a request to:

https://graph.facebook.com/me?access_token=...

Facebook database design?

This recent June 2013 post goes into some detail into explaining the transition from relationship databases to objects with associations for some data types.

https://www.facebook.com/notes/facebook-engineering/tao-the-power-of-the-graph/10151525983993920

There's a longer paper available at https://www.usenix.org/conference/atc13/tao-facebook’s-distributed-data-store-social-graph

How can I display the users profile pic using the facebook graph api?

Knowing the user id the URL for their profile picture is:-

http://graph.facebook.com/[UID]/picture

where in place of [UID] you place your $uid variable, and that URL can be passed to flash

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

function amiLoadedInIFrame() {
    try {
         // Introduce a new propery in window.top
         window.top.dummyAttribute = true;
         // If window.dummyAttribute is there.. then window and window.top are same intances
         return !window.dummyAttribute;
    } catch(e) {
         // Exception will be raised when the top is in different domain
         return true;
    }
}

Facebook Open Graph Error - Inferred Property

You need a space after the final set of quote marks

<meta property="og:url" content="http://www.mywebaddress.com"/>

Should be..likes this one

<meta property="og:url" content="http://www.mywebaddress.com" />

Getting list of Facebook friends with latest API

If you want to use the REST end point,

$friends = $facebook->api(array('method' => 'friends.get'));

else if you are using the graph api, then use,

$friends = $facebook->api('/me/friends');

Facebook OAuth "The domain of this URL isn't included in the app's domain"

As of 2017-10.

Solution that solved my issue.

Currently that FB renders this surprise.

...app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on...

enter image description here

The settings to adjust are located here https://developers.facebook.com/apps/[your_app_itentifier]/fb-login/.

The trailing slash is important. They must match in your app code and in FB admin settings. So this is a config somewhere in your code (see below how to get any domain name for a dev app):

{
    callbackURL: `http://my_local_app.com:3000/callback/`, // trailing slash
}

and here

enter image description here

To get any domain name for an app on a local Windows machine, edit host file. Custom names are good in order to get rid of all those localhost:8080, 0.0.0.0:30303, 127.0.0.0:8000, so forth. Because some third party services like FB sometimes fail to let you use 127.0.0.0 names.

On Windows 10 hosts file is here:

C:\Windows\System32\drivers\etc\hosts

Backup initial file, create a copy with different name (Doesn't work in native Windows CMD. I use Git for Windows, it has many Unix commands)

$ cp hosts hosts.bak

Add this in hosts

127.0.0.1  myfbapp.com # you can access it in a browser http://myfbapp.com:3000
127.0.0.1  www.myotherapp.io # In a browser http://www.myotherapp.io:2020

In order to get rid of port part :3000 set up NGINX, for example.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Add another option, maybe not the most lightweight.

_x000D_
_x000D_
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
_x000D_
_x000D_

Creating a Facebook share button with customized url, title and image

Crude, but it works on our system:

<div class="block-share spread-share p-t-md">
  <a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!" 
     target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span> 
      Share on Facebook
    </button>
  </a>

  <a href="https://www.facebook.com/FarmersForBritain" target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span>
      Like  on Facebook
    </button>
  </a>
</div>

Has Facebook sharer.php changed to no longer accept detailed parameters?

Starting from July 18, 2017 Facebook has decided to disregard custom parameters set by users. This choice blocks many of the possibilities offered by this answer and it also breaks buttons used on several websites.

The quote and hashtag parameters work as of Dec 2018.


Does anyone know if there have been recent changes which could have suddenly stopped this from working?

The parameters have changed. The currently accepted answer states:

Facebook no longer supports custom parameters in sharer.php

But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:

  • URL (of course) ? u
  • custom image ? picture
  • custom title ? title
  • custom quote ? quote
  • custom description ? description
  • caption (aka website name) ? caption

For instance, you can share this very question with the following URL:

https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fstackoverflow.com%2Fq%2F20956229%2F1101509&picture=http%3A%2F%2Fwww.applezein.net%2Fwordpress%2Fwp-content%2Fuploads%2F2015%2F03%2Ffacebook-logo.jpg&title=A+nice+question+about+Facebook&quote=Does+anyone+know+if+there+have+been+recent+changes+which+could+have+suddenly+stopped+this+from+working%3F&description=Apparently%2C+the+accepted+answer+is+not+correct.

Try it!

I've built a tool which makes it easier to share URLs on Facebook with custom parameters. You can use it to generate your sharer.php link, just press the button and copy the URL from the tab that opens.

Find Facebook user (url to profile page) by known email address

Facebook has a strict policy on sharing only the content which a profile makes public to the end user.. Still what you want is possible if the user has actually left the email id open to public domain.. A wild try u can do is send batch requests for the maximum possible batch size to ids..."http://graph.facebook.com/ .. and parse the result to check if email exists and if it does then it matches to the one you want.. you don't need any access_token for the public information ..

in case you want email id of a FB user only possible way is that they authorize ur app and then you can use the access_token thus generated for the required task.

Use Device Login on Smart TV / Console

Implement Login for Devices

Facebook Login for Devices is for devices that directly make HTTP calls over the internet. The following are the API calls and responses your device can make.

1. Enable Login for Devices

Change Settings > Advanced > OAuth Settings > Login from Devices to 'Yes'.

2. Generate a Code which is required for facebook device identification

When the person clicks Log in with Facebook, you device should make an HTTP POST to:

POST https://graph.facebook.com/oauth/device?
       type=device_code
       &amp;client_id=<YOUR_APP_ID>
       &amp;scope=<COMMA_SEPARATED_PERMISSION_NAMES> // e.g.public_profile,user_likes

The response comes in this form:

{
  "code": "92a2b2e351f2b0b3503b2de251132f47",
  "user_code": "A1NWZ9",
  "verification_uri": "https://www.facebook.com/device",
  "expires_in": 420,
  "interval": 5
}

This response means:

  • Display the string “A1NWZ9” on your device
  • Tell the person to go to “facebook.com/device” and enter this code
  • The code expires in 420 seconds. You should cancel the login flow after that time if you do not receive an access token
  • Your device should poll the Device Login API every 5 seconds to see if the authorization has been successful

3. Display the Code

Your device should display the user_code and tell people to visit the verification_uri such as facebook.com/device on their PC or smartphone. See the Design Guidelines.

4. Poll for Authorization

Your device should poll the Device Login API to see if the person successfully authorized your application. You should do this at the interval in the response to your call in Step 1, which is every 5 seconds. Your device should poll to:

POST https://graph.facebook.com/oauth/device?
       type=device_token
       &amp;client_id=<YOUR_APP_ID> 
       &amp;code=<LONG_CODE_FROM_STEP_1> //e.g."92a2b2e351f2b0b3503b2de251132f47"

You will get 200 HTTP code i.e User has successfully authorized the device. The device can now use the access_token value to make authenticated API calls.

5. Confirm Successful Login

Your device should display their name and if available, a profile picture until they click Continue. To get the person's name and profile picture, your device should make a standard Graph API call:

GET https://graph.facebook.com/v2.3/me?
      fields=name,picture&amp;
      access_token=<USER_ACCESS_TOKEN>

Response:

{
  "name": "John Doe", 
  "picture": {
    "data": {
      "is_silhouette": false, 
      "url": "https://fbcdn.akamaihd.net/hmac...ile.jpg"
    }
  }, 
  "id": "2023462875238472"
}

6. Store Access Tokens

Your device should persist the access token to make other requests to the Graph API.

Device Login access tokens may be valid for up to 60 days but may be invalided in a number of scenarios. For example when a person changes their Facebook password their access token is invalidated.

If the token is invalid, your device should delete the token from its memory. The person using your device needs to perform the Device Login flow again from Step 1 to retrieve a new, valid token.

How to get a json string from url?

Use the WebClient class in System.Net:

var json = new WebClient().DownloadString("url");

Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:

using (WebClient wc = new WebClient())
{
   var json = wc.DownloadString("url");
}

Getting the Facebook like/share count for a given URL

For latest 2.1 Graph API, an example to get likes for imdb.com will be

Using this to get the id https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%253A%252F%252Fwww.imdb.com%3Ffields%3Dlikes&version=v2.1

and then get the likes

https://developers.facebook.com/tools/explorer/?method=GET&path=414652589771%2Flikes&version=v2.1

Document

URL /?id={url}

Represents an external URL as it relates to the Facebook social graph - shares and comments from the URL on Facebook, and any Open Graph objects associated with the URL.

Reference http://harshtechtalk.com/how-get-likes-count-posts-comments-facebook-graph-api/

Want custom title / image / description in facebook share link from a flash app

I have a Joomla Module that displays stuff... and I want to be able to share that stuff on facebook and not the Page's Title Meta Description... so my workaround is to have a secret .php file on the server that gets executed when it detects the FB's

$_SERVER['HTTP_USER_AGENT']

if($_SERVER['HTTP_USER_AGENT'] != 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)') {
    echo 'Direct Access';
} else {
    echo 'FB Accessed';
}

and pass variables with the URL that formats that particular page with the title and meta desciption of the item I want to share from my joomla module...

a name="fb_share" share_url="MYURL/sharer.php?title=TITLE&desc=DESC"

hope this helps...

Facebook key hash does not match any stored key hashes

In the right side of Android Studio go to Gradle -> Tasks -> android -> signingReport and run it. Copy the SHA-1 key and transform it into base64 using this, and then add the converted base64 hash to your app in the Facebook Developer Console. If you want to use a release hash run this in the command line:keytool -exportcert -alias YOUR_KEYSTORE_ALIAS -keystore YOUR_KEYSTORE | openssl sha1 -binary | openssl base64 Where YOUR_KEYSTORE is the path to the .keystore or .jks that you used as signinConfig for your release variant and YOUR_KEYSTORE_ALIAS is the alias which you gave when you created the keystore. If you do not remember the alias you can run keytool -v -list -keystore YOUR_KEYSTORE and see all the info about the keystore

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

For me it was fixed by just removing the static property in the DialogHelper.class methods (resposble for creating & hiding the dialog), as I have properties related to Window in those methods

Invisible characters - ASCII

Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.

            '\u2060', // Word Joiner
            '\u2061', // FUNCTION APPLICATION
            '\u2062', // INVISIBLE TIMES
            '\u2063', // INVISIBLE SEPARATOR
            '\u2064', // INVISIBLE PLUS
            '\u2066', // LEFT - TO - RIGHT ISOLATE
            '\u2067', // RIGHT - TO - LEFT ISOLATE
            '\u2068', // FIRST STRONG ISOLATE
            '\u2069', // POP DIRECTIONAL ISOLATE
            '\u206A', // INHIBIT SYMMETRIC SWAPPING
            '\u206B', // ACTIVATE SYMMETRIC SWAPPING
            '\u206C', // INHIBIT ARABIC FORM SHAPING
            '\u206D', // ACTIVATE ARABIC FORM SHAPING
            '\u206E', // NATIONAL DIGIT SHAPES
            '\u206F', // NOMINAL DIGIT SHAPES
            '\u200B', // Zero-Width Space
            '\u200C', // Zero Width Non-Joiner
            '\u200D', // Zero Width Joiner
            '\u200E', // Left-To-Right Mark
            '\u200F', // Right-To-Left Mark
            '\u061C', // Arabic Letter Mark
            '\uFEFF', // Byte Order Mark
            '\u180E', // Mongolian Vowel Separator
            '\u00AD'  // soft-hyphen

Facebook share link - can you customize the message body text?

NOTE: @azure_ardee solution is no longer feasible. Facebook will not allow developers pre-fill messages. Developers may customize the story by providing OG meta tags, but it's up to the user to fill the message.

This is only possible if you are posting on the user's behalf, which requires the user authorizing your application with the publish_actions permission. AND even then:

please note that Facebook recommends using a user-initiated sharing modal.


Have a look at this answer.

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

How to get share counts using graph API

There is a ruby gem for it - SocialShares

Currently it supports following social networks:

  • facebook
  • twitter
  • google plus
  • reddit
  • linkedin
  • pinterest
  • stumbleupon
  • vkontakte
  • mail.ru
  • odnoklassniki

Usage:

:000 > url = 'http://www.apple.com/'
  => "http://www.apple.com/"
:000 > SocialShares.facebook url
  => 394927
:000 > SocialShares.google url
  => 28289
:000 > SocialShares.twitter url
  => 1164675
:000 > SocialShares.all url
  => {:vkontakte=>44, :facebook=>399027, :google=>28346, :twitter=>1836, :mail_ru=>37, :odnoklassniki=>1, :reddit=>2361, :linkedin=>nil, :pinterest=>21011, :stumbleupon=>43035}
:000 > SocialShares.selected url, %w(facebook google linkedin)
  => {:facebook=>394927, :google=>28289, :linkedin=>nil}
:000 > SocialShares.total url, %w(facebook google)
  => 423216
:000 > SocialShares.has_any? url, %w(twitter linkedin)
  => true

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

@NaturalBornCamper,

Nice code! Here is a clean-cut code function for such process!

function get_raw_facebook_avatar_url($uid)
{
    $array = get_headers('https://graph.facebook.com/'.$uid.'/picture?type=large', 1);
    return (isset($array['Location']) ? $array['Location'] : FALSE);
}

This will return the raw Facebook avatar image URL. Feel free to do whatever you want with it then!

App not setup: This app is still in development mode

2020 UPDATE

Visit https://developers.facebook.com/apps/ and select your application.

Go to Settings -> Basic. Add a Contact Email and a Privacy Policy URL. The Privacy Policy URL should be a webpage where you have hosted the terms and conditions of your application and data used.

Toggle the button in the top of the screen, as seen below, in order to switch from Development to Live.

enter image description here

Android Facebook integration with invalid key hash

What Facebook used is not the default password and alias for debug. You need to change it following and it will work.

/usr/lib/jvm/jdk1.8.0_66/bin/keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

If you have not changed anything with the default password it should be "android".

You can also configure it in the build.gradle file. But the same alias password should be used for generating the hash:

android {
    signingConfigs {
        release {
            storeFile file("~/.android/debug.keystore")
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }
    }
}

How to change facebook login button with my custom image

It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.

From facebook:

size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/

Set the login iframe opacity to 0 and show a background image in the parent div

.fb_iframe_widget iframe {
    opacity: 0;
}

.fb_iframe_widget {
  background-image: url(another-button.png);
  background-repeat: no-repeat; 
}

If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.

Facebook Callback appends '#_=_' to Return URL

Using Angular 2 (RC5) and hash-based routes, I do this:

const appRoutes: Routes = [
  ...
  {path: '_', redirectTo: '/facebookLoginSuccess'},
  ...
]

and

export const routing = RouterModule.forRoot(appRoutes, { useHash: true });

As far as I understand, the = character in the route is interpreted as part of optional route parameters definition (see https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters), so not involved in the route matching.

How can I find and run the keytool

Few observations while I was getting the same problem (Windows). 1. Shell pipe is important. 2. If you are using OpenSSL or Cygwin, definitely you have to install it. 3. keytool comes with JDK so either you have to point to it in the command or you have cd to the JDK/bin folder (where the exe resides) 4. The debug keystore is typically located at ~/.android/debug.keystore 5. password is "android" whether you -keypass it or type it when prompted. 6. For the alias name, you can open (DO NOT SAVE, just open and close) the keystore file with any editor and read it. 7. MOST IMPORTANT - There is a difference is specifying the keystore path within quotes and without. I got it working by using the keystore path within the double quotes. As remix090378 said and as per the instruction, this command indeed worked - cd C:\Program Files\Java\jdk1.7.0_09\bin

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\userName.android\debug.keystore" -list -v

Get user profile picture by Id

As per the current latest Facebook API version 3.2, For users you can use this generic method for getting profile picture is https://graph.facebook.com/v3.2/{user-id}/picture?type=square you can visit documentation for user picture here. The possible values for type parameter in URL can be small, normal, album, large, square

For Groups and Pages, the profile picture is not available directly. You have to get them using access token. For Groups you have to use User Access Token and for Pages you can use both User Access Token and Page Access Token.

You can get Group's or Page's Profile Picture using the generic URL: https://graph.facebook.com/v3.2/{user-id}/picture?access_token={access-token}&type=square

I hope this is helpful for people who are looking for Page or Group Profile picture.

How to check if a user likes my Facebook Page or URL using Facebook's API

You can do it in JavaScript like so (Building off of @dwarfy's response to a similar question):

<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <style type="text/css">
      div#container_notlike, div#container_like {
        display: none;
      }
    </style>
  </head>
  <body>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : 'YOUR_APP_ID', // App ID
          channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
          status     : true, // check login status
          cookie     : true, // enable cookies to allow the server to access the session
          xfbml      : true  // parse XFBML
        });

        FB.getLoginStatus(function(response) {
          var page_id = "YOUR_PAGE_ID";
          if (response && response.authResponse) {
            var user_id = response.authResponse.userID;
            var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
            FB.Data.query(fql_query).wait(function(rows) {
              if (rows.length == 1 && rows[0].uid == user_id) {
                console.log("LIKE");
                $('#container_like').show();
              } else {
                console.log("NO LIKEY");
                $('#container_notlike').show();
              }
            });
          } else {
            FB.login(function(response) {
              if (response && response.authResponse) {
                var user_id = response.authResponse.userID;
                var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
                FB.Data.query(fql_query).wait(function(rows) {
                  if (rows.length == 1 && rows[0].uid == user_id) {
                    console.log("LIKE");
                    $('#container_like').show();
                  } else {
                    console.log("NO LIKEY");
                    $('#container_notlike').show();
                  }
                });
              } else {
                console.log("NO LIKEY");
                $('#container_notlike').show();
              }
            }, {scope: 'user_likes'});
          }
        });
      };

      // Load the SDK Asynchronously
      (function(d){
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
      }(document));
    </script>

    <div id="container_notlike">
      YOU DON'T LIKE ME :(
    </div>

    <div id="container_like">
      YOU LIKE ME :)
    </div>

  </body>
</html>

Where the channel.html file on your server just contains the line:

 <script src="//connect.facebook.net/en_US/all.js"></script>

There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.

Sharing url link does not show thumbnail image on facebook

Your meta tag should look like this:

<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>

And it has to be placed on the page you want to share (this is unclear in your question).

If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.

using facebook sdk in Android studio

using facebook sdk in android studio is quite simple , just add the following line in your gradle

  compile 'com.facebook.android:facebook-android-sdk:[4,5)'

and make sure that you have updated Android support repository , if not then update it using stand alone sdk manger

When do I need a fb:app_id or fb:admins?

To use the Like Button and have the Open Graph inspect your website, you need an application.

So you need to associate the Like Button with a fb:app_id

If you want other users to see the administration page for your website on Facebook you add fb:admins. So if you are the developer of the application and the website owner there is no need to add fb:admins

Getting the "real" Facebook profile picture URL from graph API

$url = 'http://graph.facebook.com/100000771470028/picture?type=large';
$rray=get_headers($url);
$hd = $rray[4];
echo(substr($hd,strpos($hd,'http')));

This will return the url that you asked, and the problem of changing the url by facebook doesn't matter because you are dynamically calling the url from the original url.

Android - Share on Facebook, Twitter, Mail, ecc

I think you want to give Share button, clicking on which the suitable media/website option should be there to share with it. In Android, you need to create createChooser for the same.

Sharing Text:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is the text that will be shared.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Sharing binary objects (Images, videos etc.)

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);

sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

FYI, above code are referred from Sharing content in Android using ACTION_SEND Intent

Facebook Open Graph not clearing cache

Had a similar experience. Website link was showing a 404 in the preview that facebook generated. Turns out the og:url metadata was wrong. We had already fixed it a few days back but were still seeing a 404 on the preview. We used the tool at https://developers.facebook.com/tools/debug/ and that forced the refresh (didn't have to append any parameters by the way) In our case, Facebook didn't refresh the cache after 24 hours but the tool helped force it.

How to show particular image as thumbnail while implementing share on Facebook?

The easiest way I found to set Facebook Open Graph to every Joomla article, was to place in com_content/article/default.php override, next code:

$app    = JFactory::getApplication();
$path   = JURI::root();

$document = JFactory::getDocument();
$document->addCustomTag('<meta property="og:title" content="YOUR SITE TITLE" />');
$document->addCustomTag('<meta property="og:name" content="YOUR SITE NAME" />');
$document->addCustomTag('<meta property="og:description" content="YOUR SITE DESCRIPTION" />');
$document->addCustomTag('<meta property="og:site_name" content="YOUR SITE NAME" />');
if (isset($images->image_fulltext) and !empty($images->image_fulltext)) : 
    $document->addCustomTag('<meta property="og:image" content="'.$path.'<?php echo htmlspecialchars($images->image_fulltext); ?>" />');
else :
    $document->addCustomTag('<meta property="og:image" content="'.$path.'images/logo.png" />');
 endif;

This will place meta og tags in the head with details from current article.

Safari 3rd party cookie iframe trick no longer working?

Some context that I haven't seen clearly stated in the existing answers (and also a lot has changed since 2012!):

If you can control both the 3rd party iframe and the parent page (i.e. you are able to insert JavaScript on the parent page), then several workarounds are available. I would suggest the most elegant of these is making use of the postMessage API as described by @Frank's answer, as a) this does not require any redirects and b) does not require any user interactions.

If you do NOT control both the 3rd party iframe and the parent page, e.g. you have a widget hosted on a site you do not control, then most of the answers posted here will not work in Safari as of May 2020, and will stop working in Chrome around 2022. That is, unless a user has already visited your domain or interacts with the iframe, you are not able to set cookies. However, there are some commercial services offering solutions to solve this problem, such as CloudCookie.io

Facebook API error 191

This is just because of a URL mistake.

Whatever website URL is specified should be correct.

I mentioned website URL as http://localhost:3000/ and domain as localhost, but in my browser I was running http://0.0.0.0:3000/.

When I ran server as localhost:3000 it solved the problem.

As I mentioned, the site URL as localhost Facebook will redirect to the same, if we are running 0.0.0.0:3000, it will rise error that "Given URL is not allowed by the Application configuration".

How do I customize Facebook's sharer.php

Facebook sharer.php parameters for sharing posts.

<a href="javascript: void(0);"
   data-layout="button"
   onclick="window.open('https://www.facebook.com/sharer.php?u=MyPageUrl&summary=MySummary&title=MyTitle&description=MyDescription&picture=MyYmageUrl', 'ventanacompartir', 'toolbar=0, status=0, width=650, height=450');"> Share </a>

Don't use spaces, use &nbsp.

Getting fb.me URL

You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

Open Facebook Page in Facebook App (if installed) on Android

Here's a solution that mixes the code by Jared Rummler and AndroidMechanic.

Note: fb://facewebmodal/f?href= redirects to a weird facebook page that doesn't have the like and other important buttons, which is why I try fb://page/. It works fine with the current Facebook version (126.0.0.21.77, June 1st 2017). The catch might be useless, I left it just in case.

public static String getFacebookPageURL(Context context)
{
    final String FACEBOOK_PAGE_ID = "123456789";
    final String FACEBOOK_URL = "MyFacebookPage";

    if(appInstalledOrNot(context, "com.facebook.katana"))
    {
        try
        {
            return "fb://page/" + FACEBOOK_PAGE_ID;
            // previous version, maybe relevant for old android APIs ?
            // return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
        }
        catch(Exception e) {}
    }
    else
    {
        return FACEBOOK_URL;
    }

}

Here's the appInstalledOrNot function which I took (and modified) from Aerrow's answer to this post

private static boolean appInstalledOrNot(Context context, String uri)
{
    PackageManager pm = context.getPackageManager();
    try
    {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    }
    catch(PackageManager.NameNotFoundException e)
    {
    }

    return false;
}

How to get the Facebook ID of a page:

  1. Go to your page
  2. Right-click and View Page Source
  3. Find in page: fb://page/?id=
  4. Here you go!

How does Facebook Sharer select Images and other metadata when sharing my URL?

This is what worked for me: I placed the desired thumbnail image on the page right after the tag and making it too small to see..

<img src="imagename.jpg" width="1" height="1" />

I have not tested it with height 0 and width 0 but it probably will still work.. This does not guarantee the user will select this image..

ALSO it seems like Facebook caches the thumbnails on your page and doesnt always check it for new ones.. try adding this to another page on your site and you'll see that it works.

How to get access token from FB.login method in javascript SDK

https://developers.facebook.com/docs/facebook-login/login-flow-for-web/

{
    status: 'connected',
    authResponse: {
        accessToken: '...',
        expiresIn:'...',
        signedRequest:'...',
        userID:'...'
    }
}


FB.login(function(response) {
    if (response.authResponse) {
        // The person logged into your app
    } else {
        // The person cancelled the login dialog
    }
});

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

Facebook Graph API, how to get users email?

To get the user email, you have to log in the user with his Facebook account using the email permission. Use for that the Facebook PHP SDK (see on github) as following.

First check if the user is already logged in :

require "facebook.php";
$facebook = new Facebook(array(
    'appId'  => YOUR_APP_ID,
    'secret' => YOUR_APP_SECRET,
));

$user = $facebook->getUser();
if ($user) {
    try {
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        $user = null;
    }
}

If he his not, you can display the login link asking for the email permission :

if (!$user) {
    $args = array('scope' => 'email');
    echo '<a href="' . $facebook->getLoginUrl() . '">Login with Facebook</a>';
} else {
    echo '<a href="' . $facebook->getLogoutUrl() . '">Logout</a>';
}

When he is logged in the email can be found in the $user_profile array.

Hope that helps !

Key hash for Android-Facebook app

Official Documentation on facebook developer site:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.facebook.samples.hellofacebook", 
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

Facebook Oauth Logout

it's simple just type : $facebook->setSession(null); for logout

What are App Domains in Facebook Apps?

it stands for your website where your app is running on. like you have made an app www.xyz.pqr then you will type this www.xyz.pqr in App domain the site where your app is running on should be secure and valid

React-Native: Application has not been registered error

In my case i have got a different solution in case any one need

yarn remove react-native-material-dropdown

Install new packages react-native-material-dropdown-v2

yarn add react-native-material-dropdown-v2

Replace react-native-material-dropdown with react-native-material-dropdown-v2 in your code

e.g. import { Dropdown } from 'react-native-material-dropdown' to import { Dropdown } from 'react-native-material-dropdown-v2'

another thing ==========

  1. Open node_modules and then search for react-native-material-textfield open the file and go to src folder
  2. Under src you will see affix, helper, label folder - under each folder, there is an index.js
  3. open the index.js of the mentioned folders one by one (all 3 folders) and search for the text style: Animated.Text.propTypes.style, and replace it by style: Text.propTypes
  4. And import text form react-native like this import { Animated , Text} from 'react-native';

How does Facebook disable the browser's integrated Developer Tools?

I would go along the way of:

Object.defineProperty(window, 'console', {
  get: function() {

  },
  set: function() {

  }
});

Facebook page automatic "like" URL (for QR Code)

The answers above seem partly outdated.

The URL builder on https://developers.facebook.com/docs/plugins/like-button/ worked nicely for me.

You can configure, preview and the get the code/URL in different flavors: HTML5, XFBML, IFRAME, URL

Facebook Android Generate Key Hash

I. Create key hash debug for facebook

Add code to print out the key hash for facebook

    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.google.shoppingvn", PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("KeyHash:",
                    Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

II. Create key hash release for facebook

  1. Download openssl-0.9.8e_X64

  2. Make a openssl folder in C drive

  3. Extract Zip files into openssl folder

  4. Start -> Run: cmd (press enter)

  5. (press) cd C:\Program Files\Java\jdk1.6.0_45\bin. Note: C:\Program Files\Java\jdk1.6.0_45\bin: is path to jdk folder in your computer

  6. (press) keytool -exportcert -alias gci -keystore D:\folder\keystorerelease | C:\openssl\bin\openssl sha1 -binary | C:\openssl\bin\openssl base64. Note: D:\folder\keystorerelease: is path to your keystorerelease

  7. Enter keystore password: This is password when your register keystorerelease.

    Then you will have a key hash: jDehABCDIQEDWAYz5Ow4sjsxLSw=

  8. Login facebook. Access to Manage Apps. Paste key hash to your app on developers.facebook.com

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

For me the problem was invalid permissions - I was requesting "birthday" instead of "user_birthday". It's a shame the error message isn't at least minimally descriptive - just saying "permissions invalid" rather than ERROR CODE 2 would have saved me so much time.

Facebook api: (#4) Application request limit reached

The Facebook "Graph API Rate Limiting" docs says that an error with code #4 is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:

This rate limiting is applied globally at the app level. Ads api calls are excluded.

  • Rate limiting happens real time on sliding window for past one hour.
  • Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
  • There is a limit for each resource multiplied by monthly active users of a given app.
  • When the app uses more than its allowed resources the error is thrown.
  • Error, Code: 4, Message: Application request limit reached

The docs also give recommendations for avoiding the rate limits. For app level limits, they are:

Recommendations:

  • Verify the error code (4) to confirm the throttling type.
  • Do not make burst of calls, spread out the calls throughout the day.
  • Do smart fetching of data (important data, non duplicated data, etc).
    • Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
    • Don't fetch users feed twice (in the case that two App users have a specific friend in common)
    • Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
  • Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
  • For page related calls use realtime updates to subscribe to changes in data.
  • Field expansion allows ton "join" multiple graph queries into a single call.
  • Etags to check if the data querying has changed since the last check.
  • For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.

Finally, the docs give the following informational tips:

  • Batching calls will not reduce the number of api calls.
  • Making parallel calls will not reduce the number of api calls.

Getting full-size profile picture

For Angular:

getUserPicture(userId) {   
FB.api('/' + userId, {fields: 'picture.width(800).height(800)'}, function(response) {
  console.log('getUserPicture',response);
});
}

Open a facebook link by native Facebook app on iOS

Here are some schemes the Facebook app uses, there are a ton more on the source link:

Example

NSURL *url = [NSURL URLWithString:@"fb://profile/<id>"];
[[UIApplication sharedApplication] openURL:url];

Schemes

fb://profile – Open Facebook app to the user’s profile

fb://friends – Open Facebook app to the friends list

fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)

fb://feed – Open Facebook app to the News Feed

fb://events – Open Facebook app to the Events page

fb://requests – Open Facebook app to the Requests list

fb://notes – Open Facebook app to the Notes page

fb://albums – Open Facebook app to Photo Albums list

If before opening this url you want to check wether the user fas the facebook app you can do the following (as explained in another answer below):

if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
    [[UIApplication sharedApplication] openURL:nsurl];
}
else {
    //Open the url as usual
}

Source

http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Facebook Like-Button - hide count?

My solution is a little hood but it works. What I do is just basically detect where the number is going to be and use css to have a box cover over it. I guess you can also cheat the system and add more hits if you want. Here is my code using jquery but it will be different than others depending on where you place the like button on your page.

Not the most glamorous but hey the security is to tight to manipulate content in side of a frame.

<script type="text/javascript">
    var facebook_load = '';
    $(document).ready(function() {
        facebook_load = setInterval('checkIframeFacebookLoad()',100);
    });

    function checkIframeFacebookLoad() {
        if($('iframe.fb_ltr').length) {
            var parent = $('iframe.fb_ltr').parent();
            var hide_counter = $('<div></div>').attr('id', 'hide_count');
            parent.append(hide_counter);
            clearInterval(facebook_load);
        }
    }
</script>
<style type="text/css">
    #hide_count {
        position:absolute;
        top:-8px;
        left:122px;
        background:#becdd5;
        padding:5px 10px; 
    }
</style>

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

To check whether the frame have been loaded, use onload function. Or put your main function in load: I recommend to use load when creating the iframe by js

 $('<iframe />', {
   src: url,
   id:  'receiver',
   frameborder: 1,
   load:function(){
     //put your code here, so that those code can be make sure to be run after the frame loaded
   }
   }).appendTo('body');

Share Text on Facebook from Android App via ACTION_SEND

It appears that it's a bug in the Facebook app that was reported in April 2011 and has still yet to be fixed by the Android Facebook developers.

The only work around for the moment is to use their SDK.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Since Facebook's Android SDK v4.0 (see changelog) you need to execute the following:

LoginManager.getInstance().logOut();

How to add facebook share button on my website?

You can read more about share button here on Facebook developers website

Working JSFIDDLE

Also take a look at custom Facebook Share button JSFIDDLE

Include Facebook JavaScript SDK code right after the opening <body> tag

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

And place below code wherever you want to show Facebook Share button

<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-width="200" data-type="button_count"></div>

enter image description here

Check working JSFIDDLE

Open Facebook page from Android app?

this is the simplest code for doing this

public final void launchFacebook() {
        final String urlFb = "fb://page/"+yourpageid;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlFb));

        // If a Facebook app is installed, use it. Otherwise, launch
        // a browser
        final PackageManager packageManager = getPackageManager();
        List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() == 0) {
            final String urlBrowser = "https://www.facebook.com/"+pageid;
            intent.setData(Uri.parse(urlBrowser));
        }

        startActivity(intent);
    }

How to workaround 'FB is not defined'?

Assuming FB is a variable containing the Facebook object, I'd try something like this:

if (typeof(FB) != 'undefined'
     && FB != null ) {
    // run the app
} else {
    // alert the user
}

In order to test that something is undefined in plain old JavaScript, you should use the "typeof" operator. The sample you show where you just compare it to the string 'undefined' will evaluate to false unless your FB object really does contain the string 'undefined'!

As an aside, you may wish to use various tools like Firebug (in Firefox) to see if you can work out why the Facebook file is not loading.

Facebook login "given URL not allowed by application configuration"

I was getting this problem while using a tunnel because I:

  1. had the tunnel url:port set in the FB app settings
  2. but was accessing the local server by pointing my browser to "http://localhost:3000"

once i started punching the tunnel url:port into the browser, i was good to go.

i'm using Rails and Facebooker, but might help others just the same.

How to create Android Facebook Key Hash?

For Windows:

  1. open command prompt and paste below command

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%.android\debug.keystore | openssl sha1 -binary | openssl base64

  1. Enter password : android --> Hit Enter

  2. Copy Generated Hash Key --> Login Facebook with your developer account

  3. Go to your Facebook App --> Settings--> Paste Hash key in "key hashes" option -->save changes.

  4. Now Test your android app with Facebook Log-in/Share etc.

Given URL is not allowed by the Application configuration

This can also happen when the redirect_uri submitted with the https://www.facebook.com/dialog/oauth request is not present in the list of Valid OAuth redirect URIs under:

  • Settings >> Advanced >> Security

After much trial and error, when I added the redirect_uri that I was using (https://www.facebook.com/connect/login_success.html in my case), I suddenly got to the step past this error.

How do you post to the wall on a facebook page (not profile)

You can make api calls by choosing the HTTP method and setting optional parameters:

$facebook->api('/me/feed/', 'post', array(
    'message' => 'I want to display this message on my wall'
));

Submit Post to Facebook Wall :

Include the fbConfig.php file to connect Facebook API and get the access token.

Post message, name, link, description, and the picture will be submitted to Facebook wall. Post submission status will be shown.

If FB access token ($accessToken) is not available, the Facebook Login URL will be generated and the user would be redirected to the FB login page.

Post to facebook wall php sdk

<?php
//Include FB config file
require_once 'fbConfig.php';

if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['facebook_access_token'] = (string) $accessToken;

        // OAuth 2.0 client handler helps to manage access tokens
        $oAuth2Client = $fb->getOAuth2Client();

        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

    //FB post content
    $message = 'Test message from CodexWorld.com website';
    $title = 'Post From Website';
    $link = 'http://www.codexworld.com/';
    $description = 'CodexWorld is a programming blog.';
    $picture = 'http://www.codexworld.com/wp-content/uploads/2015/12/www-codexworld-com-programming-blog.png';

    $attachment = array(
        'message' => $message,
        'name' => $title,
        'link' => $link,
        'description' => $description,
        'picture'=>$picture,
    );

    try{
        //Post to Facebook
        $fb->post('/me/feed', $attachment, $accessToken);

        //Display post submission status
        echo 'The post was submitted successfully to Facebook timeline.';
    }catch(FacebookResponseException $e){
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    }catch(FacebookSDKException $e){
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
}else{
    //Get FB login URL
    $fbLoginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);

    //Redirect to FB login
    header("Location:".$fbLoginURL);
}

Refrences:

https://github.com/facebookarchive/facebook-php-sdk

https://developers.facebook.com/docs/pages/publishing/

https://developers.facebook.com/docs/php/gettingstarted

http://www.pontikis.net/blog/auto_post_on_facebook_with_php

https://www.codexworld.com/post-to-facebook-wall-from-website-php-sdk/

Facebook how to check if user has liked page and show content?

UPDATE 21/11/2012 @ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here


Hi So as promised here is my answer using only javascript :

The content of the BODY of the page :

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  FB.init({
    appId  : 'YOUR APP ID',
    status : true, 
    cookie : true, 
    xfbml  : true  
  });
</script>

<div id="container_notlike">
YOU DONT LIKE
</div>

<div id="container_like">
YOU LIKE
</div>

The CSS :

body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}

#container_notlike, #container_like {
    display:none
}

And finally the javascript :

$(document).ready(function(){

    FB.login(function(response) {
      if (response.session) {

          var user_id = response.session.uid;
          var page_id = "40796308305"; //coca cola
          var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
          var the_query = FB.Data.query(fql_query);

          the_query.wait(function(rows) {

              if (rows.length == 1 && rows[0].uid == user_id) {
                  $("#container_like").show();

                  //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

              } else {
                  $("#container_notlike").show();
                  //and here you could get the content for a non liker in ajax...
              }
          });


      } else {
        // user is not logged in
      }
    });

});

So what what does it do ?

First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid with YOUR_USER_ID (from your rails app for example)

After that it makes a FQL query on the page_fan table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.

Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/

It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...

Finally some related docs :

FQL page_fan table

FBJS FB.Data.query

Don't hesitate if you have any question ..

Cheers

UPDATE 2

As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).

For the document.ready, you could wrap your code in a function and use body onload="your_function" or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.

And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block" and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm

But jQuery is so easy :)

UPDATE

Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.

In your action controller :

decoded_request = Canvas.parse_signed_request(params[:signed_request])

And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)

decoded_request['page']['liked']

And here is the related Canvas Class (from fbgraph ruby library) :

 class Canvas

    class << self
      def parse_signed_request(secret_id,request)
        encoded_sig, payload = request.split('.', 2)
        sig = ""
        urldecode64(encoded_sig).each_byte { |b|
          sig << "%02x" % b
        }
        data = JSON.parse(urldecode64(payload))
          if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
          raise "Bad signature algorithm: %s" % data['algorithm']
        end
        expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
        if expected_sig != sig
          raise "Bad signature"
        end
        data
      end

      private

      def urldecode64(str)
        encoded_str = str.gsub('-','+').gsub('_','/')
        encoded_str += '=' while !(encoded_str.size % 4).zero?
        Base64.decode64(encoded_str)
      end
    end  

 end

How to Test Facebook Connect Locally

Facebook has added test versions feature.

First, add a test version of your application: Create Test App

Create Test App

Then, change the Site URL to "http://localhost" under Website, and press Save Changes

enter image description here

That's all, but be careful: App ID and App Secret keys are different for the application and its test versions!

custom facebook share button

Well, I use this method on my site:

<a class="share-btn" href="https://www.facebook.com/sharer/sharer.php?app_id=[your_app_id]&sdk=joey&u=[full_article_url]&display=popup&ref=plugin&src=share_button" onclick="return !window.open(this.href, 'Facebook', 'width=640,height=580')">

Works perfectly.

facebook: permanent Page Access Token?

If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.

Facebook development in localhost

Latest update: You don't have to give any urls if you are testing it in development. You can leave the fields empty. Make sure your app is in development mode. If not turn off status from live.

No need to provide site url, app domains or valid redirect oauth uri.

enter image description here

How to detect when facebook's FB.init is complete

You can subscribe to the event:

ie)

FB.Event.subscribe('auth.login', function(response) {
  FB.api('/me', function(response) {
    alert(response.name);
  });
});

New og:image size for Facebook share?

What size this image should be depends on where it is to be used.

It is up to applications, eg WhatsApp, Facebook Messenger, Reddit, etc etc to decide what to do with the image. Some use it as a square image, some as a 1:19.1 rectangle, and some use different sizes when the display environment is of different sizes even for the same application. There are no rules, and there is no way to control what applications do with the image.

So you should test out the image on your intended target application(s) and find a compromise. That applications tend to cache the image makes it a pain on the trial and error approach.

Where can I find my Facebook application id and secret key?

Dashboard -> [your app] -> [View Details] -> Settings -> Basic

source

Facebook Javascript SDK Problem: "FB is not defined"

Try to load your scripts in Head section. Moreover, it will be better if you define your scripts under some call like: document.ready, if you defined these scripts in body section

How to pass a parameter like title, summary and image in a Facebook sharer URL

Looks like Facebook disabled passing parameters to the sharer.

We have changed the behavior of the sharer plugin to be consistent with other plugins and features on our platform.

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Here's the URL to the post: https://developers.facebook.com/x/bugs/357750474364812/

The calling thread must be STA, because many UI components require this

Just mark your program with the [STAThread] attribute and the error goes away! it's magic :)

How do I get a HttpServletRequest in my spring beans?

Better way is to autowire with a constructor:

private final HttpServletRequest httpServletRequest;

public ClassConstructor(HttpServletRequest httpServletRequest){
      this.httpServletRequest = httpServletRequest;
}

How can I set a website image that will show as preview on Facebook?

1. Include the Open Graph XML namespace extension to your HTML declaration

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:fb="http://ogp.me/ns/fb#">

2. Inside your <head></head> use the following meta tag to define the image you want to use

<meta property="og:image" content="fully_qualified_image_url_here" />

Read more about open graph protocol here.

After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time

Android and Facebook share intent

In Lollipop (21), you can use Intent.EXTRA_REPLACEMENT_EXTRAS to override the intent for Facebook specifically (and specify a link only)

https://developer.android.com/reference/android/content/Intent.html#EXTRA_REPLACEMENT_EXTRAS

private void doShareLink(String text, String link) {
  Intent shareIntent = new Intent(Intent.ACTION_SEND);
  shareIntent.setType("text/plain");
  Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via));

  // for 21+, we can use EXTRA_REPLACEMENT_EXTRAS to support the specific case of Facebook
  // (only supports a link)
  // >=21: facebook=link, other=text+link
  // <=20: all=link
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    shareIntent.putExtra(Intent.EXTRA_TEXT, text + " " + link);
    Bundle facebookBundle = new Bundle();
    facebookBundle.putString(Intent.EXTRA_TEXT, link);
    Bundle replacement = new Bundle();
    replacement.putBundle("com.facebook.katana", facebookBundle);
    chooserIntent.putExtra(Intent.EXTRA_REPLACEMENT_EXTRAS, replacement);
  } else {
    shareIntent.putExtra(Intent.EXTRA_TEXT, link);
  }

  chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(chooserIntent);
}

What port is a given program using?

On Vista, you do need elevated privileges to use the -b option with netstat. To get around that, you could run "netstat -ano" which will show all open ports along with the associated process id. You could then use tasklist to lookup which process has the corresponding id.

C:\>netstat -ano

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  ...
  TCP    [::]:49335             [::]:0                 LISTENING       1056
  ...

C:\>tasklist /fi "pid eq 1056"

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
sqlservr.exe                  1056 Services                   0     66,192 K

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Which version of Python do I have installed?

You can get the version of Python by using the following command

python --version

You can even get the version of any package installed in venv using pip freeze as:

pip freeze | grep "package name"

Or using the Python interpreter as:

In [1]: import django
In [2]: django.VERSION
Out[2]: (1, 6, 1, 'final', 0)

Facebook Oauth Logout

With PHP I'm doing:

<a href="?action=logout">logout.</a>

if(isset($_GET['action']) && $_GET['action'] === 'logout'){
    $facebook->destroySession();
    header(WHERE YOU WANT TO REDIRECT TO);
    exit();
}

Works and is nice and easy am just trying to find a logout button graphic now!

How to call webmethod in Asp.net C#

Here is your answer. use

                   jquery.json-2.2.min.js 
                      and
                   jquery-1.8.3.min.js

Javascript :

function CallAddToCart(eitemId, equantity) {
   var itemId = Number(eitemId);
   var quantity = equantity;
   var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
    $.ajax({
           url: "AddToCart.aspx/AddTo_Cart",
           type: "POST",
           dataType: "json",
           data: dataValue,
           contentType: "application/json; charset=utf-8",
           success: function (msg) {
                alert("Success");
           },
           error: function () { alert(arguments[2]); }      
        });
 }

and your C# web method should be

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
   SpiritsShared.ShoppingCart.AddItem(itemId, quantity);      
  return "Item Added Successfully";
}

From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

Using SVG as background image

With my solution you're able to get something similar:

svg background image css

Here is bulletproff solution:

Your html: <input class='calendarIcon'/>

Your SVG: i used fa-calendar-alt

fa-calendar-alt

(any IDE may open svg image as shown below)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>

To use it at css background-image you gotta encode the svg to address valid string. I used this tool

As far as you got all stuff you need, you're coming to css

.calendarIcon{
      //your url will be something like this:
      background-image: url("data:image/svg+xml,***<here place encoded svg>***");
      background-repeat: no-repeat;
    }

Note: these styling wont have any effect on encoded svg image

.{
      fill: #f00; //neither this
      background-color: #f00; //nor this
}

because all changes over the image must be applied directly to its svg code

<svg xmlns="" path="" fill="#f00"/></svg>

To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:

.calendarIcon{
      background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
      background-repeat: no-repeat;
      padding-right: calc(1.5em + 0.75rem);
      background-position: center right calc(0.375em + 0.1875rem);
      background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
    }

How to get integer values from a string in Python?

Iterator version

>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]

Creating a .dll file in C#.Net

To create a DLL File, click on New project, then select Class Library.

Enter your code into the class file that was automatically created for you and then click Build Solution from the Debug menu.

Now, look in your directory: ../debug/release/YOURDLL.dll

There it is! :)

P.S. DLL files cannot be run just like normal applciation (exe) files. You'll need to create a separate project (probably a win forms app) and then add your dll file to that project as a "Reference", you can do this by going to the Solution explorer, right clicking your project Name and selecting Add Reference then browsing to whereever you saved your dll file.

For more detail please click HERE

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Casting objects in Java

In this example your superclass variable is telling the subclass object to implement the method of the superclass. This is the case of the java object type casting. Here the method() function is originally the method of the superclass but the superclass variable cannot access the other methods of the subclass object that are not present in the superclass.

How to parse a query string into a NameValueCollection in .NET

    private void button1_Click( object sender, EventArgs e )
    {
        string s = @"p1=6&p2=7&p3=8";
        NameValueCollection nvc = new NameValueCollection();

        foreach ( string vp in Regex.Split( s, "&" ) )
        {
            string[] singlePair = Regex.Split( vp, "=" );
            if ( singlePair.Length == 2 )
            {
                nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );    
            }    
        }
    }

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

For Visual Studio 2017 and 2019 on Windows 10

A lot of the answers here apply to older versions of Visual Studio. What worked for me, if using Visual Studio 2017 Community version, was setting an environment variable called VCTargetsPath and giving it a value of

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets

If using Visual Studio 2019 Community version,

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160

Other answers here set this variable to c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140 but I noticed in my visual studio installation, there was no folder called Microsoft.Cpp in my MSBuild folder. So keep this in mind as well as the fact that the path above is for the Community version of Visual Studio 2017.

Also, make sure that your MSBuild path in your environment variables points to the correct version of MSBuild if you're using Visual Studio 2017 Community version,

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin

If you're using Visual Studio 2019 Community version,

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

As you can see here:

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Difference between @GetMapping & @RequestMapping

@GetMapping supports the consumes attribute like @RequestMapping.

Entity framework left join

Please make your life easier (don't use join into group):

var query = from ug in UserGroups
            from ugp in UserGroupPrices.Where(x => x.UserGroupId == ug.Id).DefaultIfEmpty()
            select new 
            { 
                UserGroupID = ug.UserGroupID,
                UserGroupName = ug.UserGroupName,
                Price = ugp != null ? ugp.Price : 0 //this is to handle nulls as even when Price is non-nullable prop it may come as null from SQL (result of Left Outer Join)
            };

How to revert uncommitted changes including files and folders?

I usually use this way that works well:

mv fold/file /tmp
git checkout fold/file

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

"Keep Me Logged In" - the best approach

Implementing a "Keep Me Logged In" feature means you need to define exactly what that will mean to the user. In the simplest case, I would use that to mean the session has a much longer timeout: 2 days (say) instead of 2 hours. To do that, you will need your own session storage, probably in a database, so you can set custom expiry times for the session data. Then you need to make sure you set a cookie that will stick around for a few days (or longer), rather than expire when they close the browser.

I can hear you asking "why 2 days? why not 2 weeks?". This is because using a session in PHP will automatically push the expiry back. This is because a session's expiry in PHP is actually an idle timeout.

Now, having said that, I'd probably implement a harder timeout value that I store in the session itself, and out at 2 weeks or so, and add code to see that and to forcibly invalidate the session. Or at least to log them out. This will mean that the user will be asked to login periodically. Yahoo! does this.

Checking if a folder exists (and creating folders) in Qt, C++

To both check if it exists and create if it doesn't, including intermediaries:

QDir dir("path/to/dir");
if (!dir.exists())
    dir.mkpath(".");

Python: Open file in zip without temporarily extracting it

In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
    image = pygame.image.load(imgfile, 'img_01.png')
finally:
    imgfile.close()

Hiding a password in a python script (insecure obfuscation only)

Here is my snippet for such thing. You basically import or copy the function to your code. getCredentials will create the encrypted file if it does not exist and return a dictionaty, and updateCredential will update.

import os

def getCredentials():
    import base64

    splitter='<PC+,DFS/-SHQ.R'
    directory='C:\\PCT'

    if not os.path.exists(directory):
        os.makedirs(directory)

    try:
        with open(directory+'\\Credentials.txt', 'r') as file:
            cred = file.read()
            file.close()
    except:
        print('I could not file the credentials file. \nSo I dont keep asking you for your email and password everytime you run me, I will be saving an encrypted file at {}.\n'.format(directory))

        lanid = base64.b64encode(bytes(input('   LanID: '), encoding='utf-8')).decode('utf-8')  
        email = base64.b64encode(bytes(input('   eMail: '), encoding='utf-8')).decode('utf-8')
        password = base64.b64encode(bytes(input('   PassW: '), encoding='utf-8')).decode('utf-8')
        cred = lanid+splitter+email+splitter+password
        with open(directory+'\\Credentials.txt','w+') as file:
            file.write(cred)
            file.close()

    return {'lanid':base64.b64decode(bytes(cred.split(splitter)[0], encoding='utf-8')).decode('utf-8'),
            'email':base64.b64decode(bytes(cred.split(splitter)[1], encoding='utf-8')).decode('utf-8'),
            'password':base64.b64decode(bytes(cred.split(splitter)[2], encoding='utf-8')).decode('utf-8')}

def updateCredentials():
    import base64

    splitter='<PC+,DFS/-SHQ.R'
    directory='C:\\PCT'

    if not os.path.exists(directory):
        os.makedirs(directory)

    print('I will be saving an encrypted file at {}.\n'.format(directory))

    lanid = base64.b64encode(bytes(input('   LanID: '), encoding='utf-8')).decode('utf-8')  
    email = base64.b64encode(bytes(input('   eMail: '), encoding='utf-8')).decode('utf-8')
    password = base64.b64encode(bytes(input('   PassW: '), encoding='utf-8')).decode('utf-8')
    cred = lanid+splitter+email+splitter+password
    with open(directory+'\\Credentials.txt','w+') as file:
        file.write(cred)
        file.close()

cred = getCredentials()

updateCredentials()

Vue equivalent of setTimeout?

It is likely a scope issue. Try the following instead:

addToBasket: function(){
    item = this.photo;
    this.$http.post('/api/buy/addToBasket', item);
    this.basketAddSuccess = true;
    var self = this;
    setTimeout(function(){
        self.basketAddSuccess = false;
    }, 2000);
}

How to Save Console.WriteLine Output to Text File

Using only configuration in your app.config:

    <system.diagnostics> 
        <trace autoflush="true" indentsize="4"> 
              <listeners> 

              <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>

            <!--
            <add name="logListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="TextWriterOutput.log" /> 
            <add name="EventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="MyEventLog"/>
             -->

             <!--
              Remove the Default listener to avoid duplicate messages
              being sent to the debugger for display
             -->
             <remove name="Default" />

             </listeners> 
        </trace> 
  </system.diagnostics>

For testing, you can use DebugView before running the program, then we can easily view all of the log messages.

References:
http://blogs.msdn.com/b/jjameson/archive/2009/06/18/configuring-logging-in-a-console-application.aspx http://www.thejoyofcode.com/from_zero_to_logging_with_system_diagnostics_in_15_minutes.aspx
Redirect Trace output to Console
Problem redirecting debug output to a file using trace listener
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics.aspx

How to convert comma separated string into numeric array in javascript

This is an easy and quick solution when the string value is proper with the comma(,).

But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.

"123,234,345,"

So I suggest using push()

var arr = [], str="123,234,345,"
str.split(",").map(function(item){
    if(item.trim()!=''){arr.push(item.trim())}
})

Exception is never thrown in body of corresponding try statement

Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.

How do I install PHP cURL on Linux Debian?

Type in console as root:

apt-get update && apt-get install php5-curl

or with sudo:

sudo apt-get update && sudo apt-get install php5-curl

Sorry I missread.

1st, check your DNS config and if you can ping any host at all,

ping google.com
ping zm.archive.ubuntu.com

If it does not work, check /etc/resolv.conf or /etc/network/resolv.conf, if not, change your apt-source to a different one.

/etc/apt/sources.list

Mirrors: http://www.debian.org/mirror/list

You should not use Ubuntu sources on Debian and vice versa.

Check if any ancestor has a class using jQuery

You can use parents method with specified .class selector and check if any of them matches it:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

Pytorch reshape tensor dimension

Use torch.unsqueeze(input, dim, out=None)

>>> import torch
>>> a = torch.Tensor([1,2,3,4,5])
>>> a

 1
 2
 3
 4
 5
[torch.FloatTensor of size 5]

>>> a = a.unsqueeze(0)
>>> a

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

the error for Response.END(); is because you are using a asp update panel or any control that using javascript, try to use control native from asp or html without javascript or scriptmanager or scripting and try again

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

How to query data out of the box using Spring data JPA by both Sort and Pageable?

in 2020, the accepted answer is kinda out of date since the PageRequest is deprecated, so you should use code like this :

Pageable page = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("id").descending());
return repository.findAll(page);

Angular2 equivalent of $document.ready()

In order to use jQuery inside Angular only declare the $ as following: declare var $: any;

Can I add background color only for padding?

You can use background-gradients for that effect. For your example just add the following lines (it is just so much code because you have to use vendor-prefixes):

background-image: 
    -moz-linear-gradient(top, #000 10px, transparent 10px),
    -moz-linear-gradient(bottom, #000 10px, transparent 10px),
    -moz-linear-gradient(left, #000 10px, transparent 10px),
    -moz-linear-gradient(right, #000 10px, transparent 10px);
background-image: 
    -o-linear-gradient(top, #000 10px, transparent 10px),
    -o-linear-gradient(bottom, #000 10px, transparent 10px),
    -o-linear-gradient(left, #000 10px, transparent 10px),
    -o-linear-gradient(right, #000 10px, transparent 10px);
background-image: 
    -webkit-linear-gradient(top, #000 10px, transparent 10px),
    -webkit-linear-gradient(bottom, #000 10px, transparent 10px),
    -webkit-linear-gradient(left, #000 10px, transparent 10px),
    -webkit-linear-gradient(right, #000 10px, transparent 10px);
background-image: 
    linear-gradient(top, #000 10px, transparent 10px),
    linear-gradient(bottom, #000 10px, transparent 10px),
    linear-gradient(left, #000 10px, transparent 10px),
    linear-gradient(right, #000 10px, transparent 10px);

No need for unecessary markup.

If you just want to have a double border you could use outline and border instead of border and padding.

While you could also use pseudo-elements to achieve the desired effect, I would advise against it. Pseudo-elements are a very mighty tool CSS provides, if you "waste" them on stuff like this, you are probably gonna miss them somewhere else.

I only use pseudo-elements if there is no other way. Not because they are bad, quite the opposite, because I don't want to waste my Joker.

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

We have been using the plugin bootstrap-select for Bootstrap for dtyling selects. Really works well and has lots of interesting additional features. I can recommend it for sure.

What's the difference between JPA and Hibernate?

While JPA is the specification, Hibernate is the implementation provider that follows the rules dictated in the specification.

Why did Servlet.service() for servlet jsp throw this exception?

It can be caused by a classpath contamination. Check that you /WEB-INF/lib doesn't contain something like jsp-api-*.jar.

How to decode JWT Token?

Extending on cooxkie answer, and dpix answer, when you are reading a jwt token (such as an access_token received from AD FS), you can merge the claims in the jwt token with the claims from "context.AuthenticationTicket.Identity" that might not have the same set of claims as the jwt token.

To Illustrate, in an Authentication Code flow using OpenID Connect,after a user is authenticated, you can handle the event SecurityTokenValidated which provides you with an authentication context, then you can use it to read the access_token as a jwt token, then you can "merge" tokens that are in the access_token with the standard list of claims received as part of the user identity:

    private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage,OpenIdConnectAuthenticationOptions> context)
    {
        //get the current user identity
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)context.AuthenticationTicket.Identity;

        /*read access token from the current context*/
        string access_token = context.ProtocolMessage.AccessToken;

        JwtSecurityTokenHandler hand = new JwtSecurityTokenHandler();
        //read the token as recommended by Coxkie and dpix
        var tokenS = hand.ReadJwtToken(access_token);
        //here, you read the claims from the access token which might have 
        //additional claims needed by your application
        foreach (var claim in tokenS.Claims)
        {
            if (!claimsIdentity.HasClaim(claim.Type, claim.Value))
                claimsIdentity.AddClaim(claim);
        }

        return Task.FromResult(0);
    }

Cannot construct instance of - Jackson

Your @JsonSubTypes declaration does not make sense: it needs to list implementation (sub-) classes, NOT the class itself (which would be pointless). So you need to modify that entry to list sub-class(es) there are; or use some other mechanism to register sub-classes (SimpleModule has something like addAbstractTypeMapping).

Where are logs located?

  • Ensure debug mode is on - either add APP_DEBUG=true to .env file or set an environment variable

  • Log files are in storage/logs folder. laravel.log is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.

  • In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).

  • If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).

how do you filter pandas dataframes by multiple columns

You can create your own filter function using query in pandas. Here you have filtering of df results by all the kwargs parameters. Dont' forgot to add some validators(kwargs filtering) to get filter function for your own df.

def filter(df, **kwargs):
    query_list = []
    for key in kwargs.keys():
        query_list.append(f'{key}=="{kwargs[key]}"')
    query = ' & '.join(query_list)
    return df.query(query)

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

Converting a Uniform Distribution to a Normal Distribution

The Ziggurat algorithm is pretty efficient for this, although the Box-Muller transform is easier to implement from scratch (and not crazy slow).

How can I compare strings in C using a `switch` statement?

I think the best way to do this is separate the 'recognition' from the functionality:

struct stringcase { char* string; void (*func)(void); };

void funcB1();
void funcAzA();

stringcase cases [] = 
{ { "B1", funcB1 }
, { "AzA", funcAzA }
};

void myswitch( char* token ) {
  for( stringcases* pCase = cases
     ; pCase != cases + sizeof( cases ) / sizeof( cases[0] )
     ; pCase++ )
  {
    if( 0 == strcmp( pCase->string, token ) ) {
       (*pCase->func)();
       break;
    }
  }

}

How can I get the current date and time in UTC or GMT in Java?

To put it simple. A calendar object stores information about time zone but when you perform cal.getTime() then the timezone information will be lost. So for Timezone conversions I will advice to use DateFormat classes...

Spring Data and Native Query with pagination

I use oracle database and I did not get the result but an error with generated comma which d-man speak about above.

Then my solution was:

Pageable pageable = new PageRequest(current, rowCount);

As you can see without order by when create Pagable.

And the method in the DAO:

public interface UserRepository extends JpaRepository<User, Long> {
  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1 /*#pageable*/ ORDER BY LASTNAME",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
 }

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

How to determine the current shell I'm working on

Kindly use the below command:

ps -p $$ | tail -1 | awk '{print $4}'

How do I detect if a user is already logged in Firebase?

https://firebase.google.com/docs/auth/web/manage-users

You have to add an auth state change observer.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

How to remove specific object from ArrayList in Java?

    ArrayTest obj=new ArrayTest(1);
    test.add(obj);
    ArrayTest obj1=new ArrayTest(2);
    test.add(obj1);
    ArrayTest obj2=new ArrayTest(3);
    test.add(obj2);

    test.remove(object of ArrayTest);

you can specify how you control each object.

How to start an Android application from the command line?

You can use:

adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1

This will start the LAUNCHER Activity of the application using monkeyrunner test tool.

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

Get current clipboard content?

window.clipboardData.getData('Text') will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.

Return value from exec(@sql)

that's my procedure

CREATE PROC sp_count
    @CompanyId sysname,
    @codition sysname
    AS
    SET NOCOUNT ON
    CREATE TABLE #ctr
    ( NumRows int )

    DECLARE @intCount int
         , @vcSQL varchar(255)

    SELECT    @vcSQL = ' INSERT #ctr FROM dbo.Comm_Services 
                       WHERE CompanyId = '+@CompanyId+' and '+@condition+')'
    EXEC      (@vcSQL)

    IF @@ERROR = 0
    BEGIN
         SELECT    @intCount = NumRows
         FROM #ctr

         DROP TABLE #ctr
         RETURN @intCount
    END
    ELSE
    BEGIN
         DROP TABLE #ctr
         RETURN -1
    END
    GO

Macro to Auto Fill Down to last adjacent cell

This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.

Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

Lightweight XML Viewer that can handle large files

firstobject's 605k download lightweight native Windows free XML editor opens a 50MB file in 1.3 seconds and provides text editing, search, syntax-colored printing, plus tree view and additional XML features including formatting and full-blown CMarkup scripting built in. You can reformat an entire 50MB XML document to a different indentation (takes 3 seconds on a nothing special 2.3GHz/2GB machine).

Setting Windows PowerShell environment variables

As Jonathan Leaders mentioned here, it is important to run the command/script elevated to be able to change environment variables for 'machine', but running some commands elevated doesn't have to be done with the Community Extensions, so I'd like to modify and extend JeanT's answer in a way, that changing machine variables also can be performed even if the script itself isn't run elevated:

function Set-Path ([string]$newPath, [bool]$permanent=$false, [bool]$forMachine=$false )
{
    $Env:Path += ";$newPath"

    $scope = if ($forMachine) { 'Machine' } else { 'User' }

    if ($permanent)
    {
        $command = "[Environment]::SetEnvironmentVariable('PATH', $env:Path, $scope)"
        Start-Process -FilePath powershell.exe -ArgumentList "-noprofile -command $Command" -Verb runas
    }

}

onActivityResult is not being called in Fragment

In my case, in developer options I have turned on "Do not keep activities", which was causing this issue.

In case it helps someone.

Best way to structure a tkinter application?

Probably the best way to learn how to structure your program is by reading other people's code, especially if it's a large program to which many people have contributed. After looking at the code of many projects, you should get an idea of what the consensus style should be.

Python, as a language, is special in that there are some strong guidelines as to how you should format your code. The first is the so-called "Zen of Python":

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

On a more practical level, there is PEP8, the style guide for Python.

With those in mind, I would say that your code style doesn't really fit, particularly the nested functions. Find a way to flatten those out, either by using classes or moving them into separate modules. This will make the structure of your program much easier to understand.

Unit testing click event in Angular

I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges(); was really necessary so I removed it and it still worked. Then I removed tick(); to see if it worked and it did. Finally I removed the test from the fakeAsync() wrap, and surprise, it worked.

So I ended up with this:

it('should call onClick method', () => {
  const onClickMock = spyOn(component, 'onClick');
  fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
  expect(onClickMock).toHaveBeenCalled();
});

And it worked just fine.

Change package name for Android in React Native

I use the react-native-rename* npm package. Install it via

npm install react-native-rename -g

Then, from the root of your React Native project, execute the following:

react-native-rename "MyApp" -b com.mycompany.myapp

Difference between IISRESET and IIS Stop-Start command

Take IISReset as a suite of commands that helps you manage IIS start / stop etc.

Which means you need to specify option (/switch) what you want to do to carry any operation.

Default behavior OR default switch is /restart with iisreset so you do not need to run command twice with /start and /stop.

Hope this clarifies your question. For reference the output of iisreset /? is:

IISRESET.EXE (c) Microsoft Corp. 1998-2005

Usage:
iisreset [computername]

    /RESTART            Stop and then restart all Internet services.
    /START              Start all Internet services.
    /STOP               Stop all Internet services.
    /REBOOT             Reboot the computer.
    /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                        stopping, or restarting Internet services.
    /NOFORCE            Do not forcefully terminate Internet services if
                        attempting to stop them gracefully fails.
    /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                        a successful stop of Internet services. On expiration
                        of this timeout the computer can be rebooted if
                        the /REBOOTONERROR parameter is specified.
                        The default value is 20s for restart, 60s for stop,
                        and 0s for reboot.
    /STATUS             Display the status of all Internet services.
    /ENABLE             Enable restarting of Internet Services
                        on the local system.
    /DISABLE            Disable restarting of Internet Services
                        on the local system.

How to store the hostname in a variable in a .bat file?

Why not so?:

set host=%COMPUTERNAME%
echo %host%

How to install "ifconfig" command in my ubuntu docker image?

If Ubuntu Docker image isn't recognizing 'ifconfig' inside of GNS3, you'll need to open Ubuntu docker image on your host.

Assuming you already have docker on your host pc and ubuntu pull'd from docker images. Enter these commands in your host OS (Linux, CentOS, etc.) CLI.

$docker images

$docker run -it ubuntu

$apt-get update

$apt-get install net-tools

(side note: you can add whatever other tools and services that you would like to add now, but for now this is just to get ifconfig to work.)

$exit

Now you will commit these changes to Docker. This link for committing changes is the best summary and works (skip to Step 4):

https://phoenixnap.com/kb/how-to-commit-changes-to-docker-image#htoc-step-3-modify-the-container

When you re-open the docker image in GNS3 you should now have the ifconfig command usable and whatever other tools or services you added to the container.

Enjoy!

Jquery check if element is visible in viewport

You can see this example.

// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );

detectPartial :

  • True : the entire element is visible
  • false : part of the element is visible

visible is boolean variable which indicates if the element is visible or not.

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Use permission symbols instead of numbers

Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

#!/usr/bin/env python3

import os
import stat

os.chmod(
    'myfile',
    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |
    stat.S_IROTH
)

This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat.

Another advantage is the greater portability as mentioned in the docs:

Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

Tested in Ubuntu 16.04, Python 3.5.2.

Writing a list to a file with Python

In General

Following is the syntax for writelines() method

fileObject.writelines( sequence )

Example

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

Reference

http://www.tutorialspoint.com/python/file_writelines.htm

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

How do I keep Python print from adding newlines or spaces?

In Python 3, use

print('h', end='')

to suppress the endline terminator, and

print('a', 'b', 'c', sep='')

to suppress the whitespace separator between items. See the documentation for print

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Try the following:

driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")

Age from birthdate in python

As suggested by @[Tomasz Zielinski] and @Williams python-dateutil can do it just 5 lines.

from dateutil.relativedelta import *
from datetime import date
today = date.today()
dob = date(1982, 7, 5)
age = relativedelta(today, dob)

>>relativedelta(years=+33, months=+11, days=+16)`

Explode string by one or more spaces or tabs

To separate by tabs:

$comp = preg_split("/[\t]/", $var);

To separate by spaces/tabs/newlines:

$comp = preg_split('/\s+/', $var);

To seperate by spaces alone:

$comp = preg_split('/ +/', $var);

Inline CSS styles in React: how to implement a:hover?

Here's my solution using React Hooks. It combines the spread operator and the ternary operator.

style.js

export default {
  normal:{
    background: 'purple',
    color: '#ffffff'
  },
  hover: {
    background: 'red'
  }
}

Button.js

import React, {useState} from 'react';
import style from './style.js'

function Button(){

  const [hover, setHover] = useState(false);

  return(
    <button
      onMouseEnter={()=>{
        setHover(true);
      }}
      onMouseLeave={()=>{
        setHover(false);
      }}
      style={{
        ...style.normal,
        ...(hover ? style.hover : null)
      }}>

        MyButtonText

    </button>
  )
}

'module' has no attribute 'urlencode'

import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})

com.jcraft.jsch.JSchException: UnknownHostKey

I lost a lot of time on this stupid issue, and i think the message is quite right "there is not the host in the file i'm accessing" but you can have more than a know_host file around on your system (as example i'm using mobaXterm and it keep it's own inside the installation directory mounting the home from that root).

If you are experiencing : it's working from command line but not form the application try to access to your remote server with ssh and check with verbose -v option which file is currently used an example following:

 ssh -v [email protected]
 OpenSSH_6.2p2, OpenSSL 1.0.1g 7 Apr 2014
 debug1: Reading configuration data /etc/ssh_config
 debug1: Connecting to gitlab.com [104.210.2.228] port 22.
 debug1: Connection established.
 debug1: identity file /home/mobaxterm/.ssh/id_rsa type 1
 debug1: identity file /home/mobaxterm/.ssh/id_rsa-cert type -1
 debug1: identity file /home/mobaxterm/.ssh/id_dsa type -1
 debug1: identity file /home/mobaxterm/.ssh/id_dsa-cert type -1
 debug1: identity file /home/mobaxterm/.ssh/id_ecdsa type -1
 debug1: identity file /home/mobaxterm/.ssh/id_ecdsa-cert type -1
 debug1: Enabling compatibility mode for protocol 2.0
 debug1: Local version string SSH-2.0-OpenSSH_6.2
 debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2      Ubuntu-4ubuntu2.1
 debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH*
 debug1: SSH2_MSG_KEXINIT sent
 debug1: SSH2_MSG_KEXINIT received
 debug1: kex: server->client aes128-ctr [email protected] [email protected]
 debug1: kex: client->server aes128-ctr [email protected] [email protected]
 debug1: sending SSH2_MSG_KEX_ECDH_INIT
 debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
 debug1: Server host key: RSA b6:03:0e:39:97:9e:d0:e7:24:ce:a3:77:3e:01:42:09
 debug1: Host 'gitlab.com' is known and matches the RSA host key.
 debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19
 debug1: ssh_rsa_verify: signature correct

as you can see the key was found in :

debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19

and not in my windows home under C:\Users\my_local_user\.ssh , i simply merged them and aligned for solve the issue.

Hope this help someone in future

Nodejs convert string into UTF-8

Use the utf8 module from npm to encode/decode the string.

Installation:

npm install utf8

In a browser:

<script src="utf8.js"></script>

In Node.js:

const utf8 = require('utf8');

API:

Encode:

utf8.encode(string)

Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string. It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. (If you need to be able to encode non-scalar values as well, use WTF-8 instead.)

// U+00A9 COPYRIGHT SIGN; see http://codepoints.net/U+00A9
utf8.encode('\xA9');
// ? '\xC2\xA9'
// U+10001 LINEAR B SYLLABLE B038 E; see http://codepoints.net/U+10001
utf8.encode('\uD800\uDC01');
// ? '\xF0\x90\x80\x81'

Decode:

utf8.decode(byteString)

Decodes any given UTF-8-encoded string (byteString) as UTF-8, and returns the UTF-8-decoded version of the string. It throws an error when malformed UTF-8 is detected. (If you need to be able to decode encoded non-scalar values as well, use WTF-8 instead.)

utf8.decode('\xC2\xA9');
// ? '\xA9'

utf8.decode('\xF0\x90\x80\x81');
// ? '\uD800\uDC01'
// ? U+10001 LINEAR B SYLLABLE B038 E

Resources

Check mySQL version on Mac 10.8.5

Or just call mysql command with --version option.

mysql --version

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

Inserting a blank table row with a smaller height

Just add the CSS rule (and the slightly improved mark-up) posted below and you should get the result that you're after.

CSS

.blank_row
{
    height: 10px !important; /* overwrites any other rules */
    background-color: #FFFFFF;
}

HTML

<tr class="blank_row">
    <td colspan="3"></td>
</tr>

Since I have no idea what your current stylesheet looks like I added the !important property just in case. If possible, though, you should remove it as one rarely wants to rely on !important declarations in a stylesheet considering the big possibility that they will mess it up later on.

Calculating the position of points in a circle

Given a radius length r and an angle t in radians and a circle's center (h,k), you can calculate the coordinates of a point on the circumference as follows (this is pseudo-code, you'll have to adapt it to your language):

float x = r*cos(t) + h;
float y = r*sin(t) + k;

How to use onResume()?

KOTLIN

Any Activity that restarts has its onResume() method executed first.

To use this method, do this:

override fun onResume() {
        super.onResume()
        // your code here
    }

Differences between socket.io and websockets

Socket.IO uses WebSocket and when WebSocket is not available uses fallback algo to make real time connections.

How to save a Python interactive session?

there is another option --- pyslice. in the "wxpython 2.8 docs demos and tools", there is a open source program named "pyslices".

you can use it like a editor, and it also support using like a console ---- executing each line like a interactive interpreter with immediate echo.

of course, all the blocks of codes and results of each block will be recorded into a txt file automatically.

the results are logged just behind the corresponding block of code. very convenient.

the overview of pyslices

Combine two columns and add into one new column

Did you check the string concatenation function? Something like:

update table_c set column_a = column_b || column_c 

should work. More here

Array.push() and unique items

var helper = {};
for(var i = 0; i < data.length; i++){
  helper[data[i]] = 1; // Fill object
}
var result = Object.keys(helper); // Unique items

Concatenating Matrices in R

Sounds like you're looking for rbind:

> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30  5

Similarly, cbind stacks the matrices horizontally.

I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")

Eclipse: Java was started but returned error code=13

Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna which comes with Java 8 support by default.

How do I use jQuery to redirect?

I found out why this happening.

After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.

Thank you everyone for trying to solve this. :)

How to import a class from default package

From the Java language spec:

It is a compile time error to import a type from the unnamed package.

You'll have to access the class via reflection or some other indirect method.

Returning data from Axios API

axiosTest() is firing asynchronously and not being waited for.

A then() function needs to be hooked up afterwards in order to capture the response variable (axiosTestData).

See Promise for more info.

See Async to level up.

_x000D_
_x000D_
// Dummy Url._x000D_
const url = 'https://jsonplaceholder.typicode.com/posts/1'_x000D_
_x000D_
// Axios Test._x000D_
const axiosTest = axios.get_x000D_
_x000D_
// Axios Test Data._x000D_
axiosTest(url).then(function(axiosTestResult) {_x000D_
  console.log('response.JSON:', {_x000D_
    message: 'Request received',_x000D_
    data: axiosTestResult.data_x000D_
  })_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
_x000D_
_x000D_
_x000D_

Android Debug Bridge (adb) device - no permissions

I encountered the same problem today.

I followed the official instructions, but I didn't noticed that I SHOULD run command
"chmod a+r /etc/udev/rules.d/51-android.rules"

After I set this file to world readable and re-plug my usb cable,the status became unauthorized. Then just grant the permission and everything goes fine.

Check if multiple strings exist in another string

a = ['a', 'b', 'c']
str =  "a123"

a_match = [True for match in a if match in str]

if True in a_match:
  print "some of the strings found in str"
else:
  print "no strings found in str"

PHP: how can I get file creation date?

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';

if (file_exists($filename)) {

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

How to get .pem file from .key and .crt files?

Your keys may already be in PEM format, but just named with .crt or .key.

If the file's content begins with -----BEGIN and you can read it in a text editor:

The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem.

If the file is in binary:

For the server.crt, you would use

openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem

For server.key, use openssl rsa in place of openssl x509.

The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate.

If this is for a Web server and you cannot specify loading a separate private and public key:

You may need to concatenate the two files. For this use:

cat server.crt server.key > server.includesprivatekey.pem

I would recommend naming files with "includesprivatekey" to help you manage the permissions you keep with this file.

How to parse JSON string in Typescript

Typescript is (a superset of) javascript, so you just use JSON.parse as you would in javascript:

let obj = JSON.parse(jsonString);

Only that in typescript you can have a type to the resulting object:

interface MyObj {
    myString: string;
    myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

How to reset a timer in C#?

For a Timer (System.Windows.Forms.Timer).

The .Stop, then .Start methods worked as a reset.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I've had this error when there's been different RxJS-versions across projects. The internal checks in RxJS fails because there are several different Symbol_observable. Eventually this function throws once called from a flattening operator like switchMap.

Try importing symbol-observable in some entry point.

// main index.ts
import 'symbol-observable';

How to echo out table rows from the db (php)

Nested loop to display all rows & columns of resulting table:

$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
   for( $j = 0; $j<$cols; $j++ ) {
     echo mysql_result($result, $i, $j)."<br>";
   }
}

Can be made more complex with data decryption/decoding, error checking & html formatting before display.

Tested in MS Edge & G Chrome, PHP 5.6

Please explain the exec() function and its family

Simplistically, in UNIX, you have the concept of processes and programs. A process is an environment in which a program executes.

The simple idea behind the UNIX "execution model" is that there are two operations you can do.

The first is to fork(), which creates a brand new process containing a duplicate (mostly) of the current program, including its state. There are a few differences between the two processes which allow them to figure out which is the parent and which is the child.

The second is to exec(), which replaces the program in the current process with a brand new program.

From those two simple operations, the entire UNIX execution model can be constructed.


To add some more detail to the above:

The use of fork() and exec() exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.

The fork() call makes a near duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations, but the idea is to create as close a copy as possible). Only one process calls fork() but two processes return from that call - sounds bizarre but it's really quite elegant

The new process (called the child) gets a different process ID (PID) and has the PID of the old process (the parent) as its parent PID (PPID).

Because the two processes are now running exactly the same code, they need to be able to tell which is which - the return code of fork() provides this information - the child gets 0, the parent gets the PID of the child (if the fork() fails, no child is created and the parent gets an error code).

That way, the parent knows the PID of the child and can communicate with it, kill it, wait for it and so on (the child can always find its parent process with a call to getppid()).

The exec() call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.

So, fork() and exec() are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find - the shell forks, then the child loads the find program into memory, setting up all command line arguments, standard I/O and so forth.

But they're not required to be used together. It's perfectly acceptable for a program to call fork() without a following exec() if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions).

This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening. For this situation, the program contains both the parent and the child code.

Similarly, programs that know they're finished and just want to run another program don't need to fork(), exec() and then wait()/waitpid() for the child. They can just load the child directly into their current process space with exec().

Some UNIX implementations have an optimized fork() which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork() until the program attempts to change something in that space. This is useful for those programs using only fork() and not exec() in that they don't have to copy an entire process space. Under Linux, fork() only makes a copy of the page tables and a new task structure, exec() will do the grunt work of "separating" the memory of the two processes.

If the exec is called following fork (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process, before modifications are allowed.

Linux also has a vfork(), even more optimised, which shares just about everything between the two processes. Because of that, there are certain restrictions in what the child can do, and the parent halts until the child calls exec() or _exit().

The parent has to be stopped (and the child is not permitted to return from the current function) since the two processes even share the same stack. This is slightly more efficient for the classic use case of fork() followed immediately by exec().

Note that there is a whole family of exec calls (execl, execle, execve and so on) but exec in context here means any of them.

The following diagram illustrates the typical fork/exec operation where the bash shell is used to list a directory with the ls command:

+--------+
| pid=7  |
| ppid=4 |
| bash   |
+--------+
    |
    | calls fork
    V
+--------+             +--------+
| pid=7  |    forks    | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash   |             | bash   |
+--------+             +--------+
    |                      |
    | waits for pid 22     | calls exec to run ls
    |                      V
    |                  +--------+
    |                  | pid=22 |
    |                  | ppid=7 |
    |                  | ls     |
    V                  +--------+
+--------+                 |
| pid=7  |                 | exits
| ppid=4 | <---------------+
| bash   |
+--------+
    |
    | continues
    V

How to make URL/Phone-clickable UILabel?

extension UITapGestureRecognizer {

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {

        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)
        let textStorage = NSTextStorage(attributedString: label.attributedText!)

        // Configure layoutManager and textStorage
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)

        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines
        textContainer.size = label.bounds.size

        // main code
        let locationOfTouchInLabel = self.location(in: label)

        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInLabel, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        let indexOfCharacterRange = NSRange(location: indexOfCharacter, length: 1)
        let indexOfCharacterRect = layoutManager.boundingRect(forGlyphRange: indexOfCharacterRange, in: textContainer)
        let deltaOffsetCharacter = indexOfCharacterRect.origin.x + indexOfCharacterRect.size.width

        if locationOfTouchInLabel.x > deltaOffsetCharacter {
            return false
        } else {
            return NSLocationInRange(indexOfCharacter, targetRange)
        }
    }
}

javascript remove "disabled" attribute from html input

To set the disabled to false using the name property of the input:

document.myForm.myInputName.disabled = false;

SimpleXml to string

You can use ->child to get a child element named child.

This element will contain the text of the child element.

But if you try var_dump() on that variable, you will see it is not actually a PHP string.

The easiest way around this is to perform a strval(xml->child); That will convert it to an actual PHP string.

This is useful when debugging when looping your XML and using var_dump() to check the result.

So $s = strval($xml->child);.

String to Binary in C#

Here you go:

public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
    return encoding.GetBytes(str);
}

public static String ToBinary(Byte[] data)
{
    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}

// Use any sort of encoding you like. 
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));

Changing the interval of SetInterval while it's running

This can be initiated however you want. timeout is the method i used to keep it on the top of the hour.

I had the need for every hour to begin a code block on the hour. So this would start at server startup and run the interval hourly. Basicaly the initial run is to begin the interval within the same minute. So in a second from init, run immediately then on every 5 seconds.

var interval = 1000;
var timing =function(){
    var timer = setInterval(function(){
        console.log(interval);
        if(interval == 1000){ /*interval you dont want anymore or increment/decrement */
            interval = 3600000; /* Increment you do want for timer */
            clearInterval(timer);
            timing();
        }
    },interval);
}
timing();

Alternately if you wanted to just have something happen at start and then forever at a specific interval you could just call it at the same time as the setInterval. For example:

var this = function(){
 //do
}
setInterval(function(){
  this()
},3600000)
this()

Here we have this run the first time and then every hour.

Pass props to parent component in React.js

The question is how to pass argument from child to parent component. This example is easy to use and tested:

//Child component
class Child extends React.Component {
    render() {
        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div><button onClick={() => handleToUpdate('someVar')}>Push me</button></div>
        )
    }
}

//Parent component
class Parent extends React.Component {
    constructor(props) {
        super(props);
        var handleToUpdate  = this.handleToUpdate.bind(this);
    }

    handleToUpdate(someArg){
        alert('We pass argument from Child to Parent: \n' + someArg);
    }

    render() {
        var handleToUpdate  =   this.handleToUpdate;
        return (<div>
          <Child handleToUpdate = {handleToUpdate.bind(this)} />
        </div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <Parent />,
        document.querySelector("#demo")
    );
}

Look at JSFIDDLE

Ignore self-signed ssl cert using Jersey Client

I had the same problem adn did not want this to be set globally, so I used the same TrustManager and SSLContext code as above, I just changed the Client to be created with special properties

 ClientConfig config = new DefaultClientConfig();
 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
     new HostnameVerifier() {
         @Override
         public boolean verify( String s, SSLSession sslSession ) {
             // whatever your matching policy states
         }
     }
 ));
 Client client = Client.create(config);

What is the difference between a data flow diagram and a flow chart?

Other answers have gone over the basics of what each thing is. At the higher level, a flowchart is a design level tool, while DFDs are more analysis.

DFDs have some nice features. Since they show the flow of data, some things become more obvious when charted this way: some data is only used by a few routines, some routines use only some bits of data, some routines touch everything. Seeing that up front helps organize, restructuring, and planning.

A follow-on worth exploring is the Event-Response Diagram, which is basically a DFD only showing process and data needed to process an "event", meaning something triggered externally (customer makes payment, etc.).

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

What's the easy way to auto create non existing dir in ansible

Right now, this is the only way

- name: Ensures {{project_root}}/conf dir exists
  file: path={{project_root}}/conf state=directory
- name: Copy file
  template:
    src: code.conf.j2
    dest: "{{project_root}}/conf/code.conf"

How to navigate back to the last cursor position in Visual Studio Code?

With VSCode 1.43 (Q1 2020), those Alt+? / Alt+?, or Ctrl+- / Ctrl+Shift+- will also... preserve selection.

See issue 89699:

Benjamin Pasero (bpasero) adds:

going back/forward restores selections as they were.

Note that in order to get a history entry there needs to be at least 10 lines between the positions to consider the entry as new entry.

Go back/Forward selection -- https://user-images.githubusercontent.com/900690/73729489-6ca7da80-4735-11ea-9345-1228f0302110.gif

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

Setting environment variable JAVA_HOME to JDK 5 or 6 (instead of JDK 7) fixed the error.

Tkinter module not found on Ubuntu

Adding solution for CentOs 7 (python 3.6.x)

yum install python36-tkinter

I had tried about every version possible, hopefully this helps out others.

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

How to change my Git username in terminal?

There is a easy solution for that problem, the solution is removed the certificate the yours Keychain, the previous thing will cause that it asks again to the user and password.

Steps:

  1. Open keychain access

enter image description here

  1. Search the certificate gitHub.com.

  2. Remove gitHub.com certificate.

  3. Execute any operation with git in your terminal. this again ask your username and password.

For Windows Users find the key chain by following:

Control Panel >> User Account >> Credential Manager >> Windows Credential >> Generic Credential

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

What properties does @Column columnDefinition make redundant?

columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.

With android studio no jvm found, JAVA_HOME has been set

It says that it should be a 64-bit JDK. I have a feeling that you installed (at a previous time) a 32-bit version of Java. The path for all 32-bit applications in Windows 7 and Vista is:

C:\Program Files (x86)\

You were setting the JAVA_HOME variable to the 32-bit version of Java. Set your JAVA_HOME variable to the following:

C:\Program Files\Java\jdk1.7.0_45

If that does not work, check that the JDK version is 1.7.0_45. If not, change the JAVA_HOME variable to (with JAVAVERSION as the Java version number:

C:\Program Files\Java\jdkJAVAVERSION

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Remember: Javascript functions are CASE SENSITIVE.

I had a case where I'm pretty sure that my code would run smoothly. But still, got an error and I checked the Javascript console of Google Chrome to check what it is.

My error line is

opt.SetAttribute("value",values[a]);

And got the same error message:

Uncaught TypeError: undefined is not a function

Nothing seems wrong with the code above but it was not running. I troubleshoot for almost an hour and then compared it with my other running code. My error is that it was set to SetAttribute, which should be setAttribute.

git clone through ssh

I want to attempt an answer that includes git-flow, and three 'points' or use-cases, the git central repository, the local development and the production machine. This is not well tested.

I am giving incredibly specific commands. Instead of saying <your folder>, I will say /root/git. The only place where I am changing the original command is replacing my specific server name with example.com. I will explain the folders purpose is so you can adjust it accordingly. Please let me know of any confusion and I will update the answer.

The git version on the server is 1.7.1. The server is CentOS 6.3 (Final).

The git version on the development machine is 1.8.1.1. This is Mac OS X 10.8.4.

The central repository and the production machine are on the same machine.

the central repository, which svn users can related to as 'server' is configured as follows. I have a folder /root/git where I keep all my git repositories. I want to create a git repository for a project I call 'flowers'.

cd /root/git
git clone --bare flowers flowers.git

The git command gave two messages:

Initialized empty Git repository in /root/git/flowers.git/
warning: You appear to have cloned an empty repository.

Nothing to worry about.

On the development machine is configured as follows. I have a folder /home/kinjal/Sites where I put all my projects. I now want to get the central git repository.

cd /home/kinjal/Sites
git clone [email protected]:/root/git/flowers.git

This gets me to a point where I can start adding stuff to it. I first set up git flow

git flow init -d

By default this is on branch develop. I add my code here, now. Then I need to commit to the central git repository.

git add .
git commit -am 'initial'
git push

At this point it pushed to the develop branch. I want to also add this to the master branch.

git flow release start v0.0.0 develop
git flow release finish v0.0.0
git push

Note that I did nothing between the release start and release finish. And when I did the release finish I was prompted to edit two files. This pushed the develop branch to master.

On the production site, which is on the same machine as my central git repository, I want put the repository in /var/www/vhosts/example.net. I already have /var/www/vhosts.

cd /var/www/vhosts
git clone file:///root/git/flowers.git example.net

If the production machine would also be on a different machine, the git clone command would look like the one used on the development machine.

Efficient way to add spaces between characters in a string

s = "BINGO"
print(s.replace("", " ")[1: -1])

Timings below

$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop

How to hide 'Back' button on navigation bar on iPhone?

In c# or Xamarin.ios, this.NavigationItem.HidesBackButton = true;

Sorting a vector in descending order

First approach refers:

    std::sort(numbers.begin(), numbers.end(), std::greater<>());

You may use the first approach because of getting more efficiency than second.
The first approach's time complexity less than second one.

Spark DataFrame groupBy and sort in the descending order (pyspark)

By far the most convenient way is using this:

df.orderBy(df.column_name.desc())

Doesn't require special imports.

React hooks useState Array

use state is not always needed you can just simply do this

let paymentList = [
    {"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]

then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.

<div className="card-body">
            <div className="table-responsive">
                <table className="table table-striped">
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            paymentList.map((payment, key) => (
                                <tr key={key}>
                                    <td>{payment.txnid}</td>
                                    <td>{payment.fname}</td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            </div>
        </div>

Laravel Request getting current path with query string

Request class doesn't offer a method that would return exactly what you need. But you can easily get it by concatenating results of 2 other methods:

echo (Request::getPathInfo() . (Request::getQueryString() ? ('?' . Request::getQueryString()) : '');

Oracle SQL Developer: Unable to find a JVM

Version 1.5 is very, very old.

In the latest builds, we support 32 and 64 bit JDKs. In version 4.0, we find the JDK for you on Windows. If the software can't find it, it prompts for that path.

That path would look something like this C:\Java\jdk1.7.0_45

You can read more about this here.

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

Add this to the project level build.gradle file and it should work fine.

allprojects {
    repositories {
        google() // this is to be added if there's something already.
        jcenter()
    }
}

org.xml.sax.SAXParseException: Content is not allowed in prolog

It means XML is malformed or the response body is not XML document at all.

How to keep the local file or the remote file during merge using Git and the command line?

For the line-end thingie, refer to man git-merge:

--ignore-space-change 
--ignore-all-space 
--ignore-space-at-eol

Be sure to add autocrlf = false and/or safecrlf = false to the windows clone (.git/config)

Using git mergetool

If you configure a mergetool like this:

git config mergetool.cp.cmd '/bin/cp -v "$REMOTE" "$MERGED"'
git config mergetool.cp.trustExitCode true

Then a simple

git mergetool --tool=cp
git mergetool --tool=cp -- paths/to/files.txt
git mergetool --tool=cp -y -- paths/to/files.txt # without prompting

Will do the job

Using simple git commands

In other cases, I assume

git checkout HEAD -- path/to/myfile.txt

should do the trick

Edit to do the reverse (because you screwed up):

git checkout remote/branch_to_merge -- path/to/myfile.txt

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

For me was to remove/delete entire .vs folder(that is an invisible one) and then:

- Build
- Rebuild 

and done.

How to enable scrolling on website that disabled scrolling?

Select the Body using chrome dev tools (Inspect ) and change in css overflow:visible,

If that doesn't work then check in below css file if html, body is set as overflow:hidden , change it as visible

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

I am on Mac OS Sierra. I had to update /etc/paths and add /Users/my.username/.rbenv/shims to the top of the list.

Which selector do I need to select an option by its text?

None of the previous suggestions worked for me in jQuery 1.7.2 because I'm trying to set the selected index of the list based on the value from a textbox, and some text values are contained in multiple options. I ended up using the following:

$('#mySelect option:contains(' + value + ')').each(function(){
    if ($(this).text() == value) {
        $(this).attr('selected', 'selected');
        return false;
    }
    return true;
});

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details.

List:

class List
{
    public:
        List(): head(nullptr), tail(nullptr) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list.

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.

"Release 0.8.7 - May 13 2016

-Fix for issue when inserting read-only images on Windows. Issue #352.

-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.

-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

IF formula to compare a date with current date and return result

The formula provided by Blake doesn't seem to work for me. For past dates it returns due in xx days and for future dates, it returns overdue. Also, it will only return 15 days overdue, when it could actually be 30, 60 90+.

I created this, which seems to work and provides 'Due in xx days', 'Overdue xx days' and 'Due Today'.

=IF(ISBLANK(O10),"",IF(DAYS(TODAY(),O10)<0,CONCATENATE("Due in ",-DAYS(TODAY(),O10)," Days"),IF(DAYS(TODAY(),O10)>0,CONCATENATE("Overdue ",DAYS(TODAY(),O10)," Days"),"Due Today")))

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

How to check sbt version?

run sbt console then type sbtVersion to check sbt version, and scalaVersion for scala version

Python: Ignore 'Incorrect padding' error when base64 decoding

There are two ways to correct the input data described here, or, more specifically and in line with the OP, to make Python module base64's b64decode method able to process the input data to something without raising an un-caught exception:

  1. Append == to the end of the input data and call base64.b64decode(...)
  2. If that raises an exception, then

    i. Catch it via try/except,

    ii. (R?)Strip any = characters from the input data (N.B. this may not be necessary),

    iii. Append A== to the input data (A== through P== will work),

    iv. Call base64.b64decode(...) with those A==-appended input data

The result from Item 1. or Item 2. above will yield the desired result.

Caveats

This does not guarantee the decoded result will be what was originally encoded, but it will (sometimes?) give the OP enough to work with:

Even with corruption I want to get back to the binary because I can still get some useful info from the ASN.1 stream").

See What we know and Assumptions below.

TL;DR

From some quick tests of base64.b64decode(...)

  1. it appears that it ignores non-[A-Za-z0-9+/] characters; that includes ignoring =s unless they are the last character(s) in a parsed group of four, in which case the =s terminate the decoding (a=b=c=d= gives the same result as abc=, and a==b==c== gives the same result as ab==).

  2. It also appears that all characters appended are ignored after the point where base64.b64decode(...) terminates decoding e.g. from an = as the fourth in a group.

As noted in several comments above, there are either zero, or one, or two, =s of padding required at the end of input data for when the [number of parsed characters to that point modulo 4] value is 0, or 3, or 2, respectively. So, from items 3. and 4. above, appending two or more =s to the input data will correct any [Incorrect padding] problems in those cases.

HOWEVER, decoding cannot handle the case where the [total number of parsed characters modulo 4] is 1, because it takes a least two encoded characters to represent the first decoded byte in a group of three decoded bytes. In uncorrupted encoded input data, this [N modulo 4]=1 case never happens, but as the OP stated that characters may be missing, it could happen here. That is why simply appending =s will not always work, and why appending A== will work when appending == does not. N.B. Using [A] is all but arbitrary: it adds only cleared (zero) bits to the decoded, which may or not be correct, but then the object here is not correctness but completion by base64.b64decode(...) sans exceptions.

What we know from the OP and especially subsequent comments is

  • It is suspected that there are missing data (characters) in the Base64-encoded input data
  • The Base64 encoding uses the standard 64 place-values plus padding: A-Z; a-z; 0-9; +; /; = is padding. This is confirmed, or at least suggested, by the fact that openssl enc ... works.

Assumptions

  • The input data contain only 7-bit ASCII data
  • The only kind of corruption is missing encoded input data
  • The OP does not care about decoded output data at any point after that corresponding to any missing encoded input data

Github

Here is a wrapper to implement this solution:

https://github.com/drbitboy/missing_b64

Find duplicate entries in a column

Try this query.. It uses the Analytic function SUM:

SELECT * FROM
(  
 SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
 FROM table1 a 
 WHERE s_ind ='Y'   
)
WHERE cnt > 2

Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

Having links relative to root?

Use

<a href="/fruits/index.html">Back to Fruits List</a>

or

<a href="../index.html">Back to Fruits List</a>

Environment variables in Mac OS X

You can read up on linux, which is pretty close to what Mac OS X is. Or you can read up on BSD Unix, which is a little closer. For the most part, the differences between Linux and BSD don't amount to much.

/etc/profile are system environment variables.

~/.profile are user-specific environment variables.

"where should I set my JAVA_HOME variable?"

  • Do you have multiple users? Do they care? Would you mess some other user up by changing a /etc/profile?

Generally, I prefer not to mess with system-wide settings even though I'm the only user. I prefer to edit my local settings.

java.math.BigInteger cannot be cast to java.lang.Long

Try to convert the BigInteger to a long like this

Long longNumber= bigIntegerNumber.longValue();

C# - Simplest way to remove first occurrence of a substring from another string

If you'd like a simple method to resolve this problem. (Can be used as an extension)

See below:

    public static string RemoveFirstInstanceOfString(this string value, string removeString)
    {
        int index = value.IndexOf(removeString, StringComparison.Ordinal);
        return index < 0 ? value : value.Remove(index, removeString.Length);
    }

Usage:

    string valueWithPipes = "| 1 | 2 | 3";
    string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
    //Output, valueWithoutFirstpipe = " 1 | 2 | 3";

Inspired by and modified @LukeH's and @Mike's answer.

Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html

jQuery .load() call doesn't execute JavaScript in loaded HTML file

Test with this in trackingCode.html:

<script type="text/javascript">

    $(function() {

       show_alert();

       function show_alert() {
           alert("Inside the jQuery ready");
       }

    });
 </script>

Questions every good .NET developer should be able to answer?

I think if I were interviewing someone who had LINQ experience, I'd possibly just ask them to explain LINQ. If they can explain deferred execution, streaming, the IEnumerable/IEnumerator interfaces, foreach, iterator blocks, expression trees (for bonus points, anyway) then they can probably cope with the rest. (Admittedly they could be "ok" developers and not "get" LINQ yet - I'm really thinking of the case where they've claimed to know enough LINQ to make it a fair question.)

In the past I've asked several of the questions already listed, and a few others:

  • Difference between reference and value types
  • Pass by reference vs pass by value
  • IDisposable and finalizers
  • Strings, immutability, character encodings
  • Floating point
  • Delegates
  • Generics
  • Nullable types

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

Are arrays passed by value or passed by reference in Java?

Kind of a trick realty... Even references are passed by value in Java, hence a change to the reference itself being scoped at the called function level. The compiler and/or JVM will often turn a value type into a reference.

Only Add Unique Item To List

//HashSet allows only the unique values to the list
HashSet<int> uniqueList = new HashSet<int>();

var a = uniqueList.Add(1);
var b = uniqueList.Add(2);
var c = uniqueList.Add(3);
var d = uniqueList.Add(2); // should not be added to the list but will not crash the app

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1,"Happy");
dict.Add(2, "Smile");
dict.Add(3, "Happy");
dict.Add(2, "Sad"); // should be failed // Run time error "An item with the same key has already been added." App will crash

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<string, int> dictRev = new Dictionary<string, int>();

dictRev.Add("Happy", 1);
dictRev.Add("Smile", 2);
dictRev.Add("Happy", 3); // should be failed // Run time error "An item with the same key has already been added." App will crash
dictRev.Add("Sad", 2);

How to delete specific rows and columns from a matrix in a smarter way?

> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    1    2    3    4
[3,]    3    2    1    2    3
[4,]    4    3    2    1    2
[5,]    5    4    3    2    1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,]    1    3    4    5
[2,]    2    2    3    4
[3,]    3    1    2    3
[4,]    4    2    1    2
[5,]    5    3    2    1

Just use the command S <- S[,-2] to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,].

Checkboxes in web pages – how to make them bigger?

Here's a trick that works in most recent browsers (IE9+) as a CSS only solution that can be improved with javascript to support IE8 and below.

<div>
  <input type="checkbox" id="checkboxID" name="checkboxName" value="whatever" />
  <label for="checkboxID"> </label>
</div>

Style the label with what you want the checkbox to look like

#checkboxID
{
  position: absolute fixed;
  margin-right: 2000px;
  right: 100%;
}
#checkboxID + label
{
  /* unchecked state */
}
#checkboxID:checked + label
{
  /* checked state */
}

For javascript, you'll be able to add classes to the label to show the state. Also, it would be wise to use the following function:

$('label[for]').live('click', function(e){
  $('#' + $(this).attr('for') ).click();
  return false;
});

EDIT to modify #checkboxID styles

Case insensitive comparison NSString

Converting Jason Coco's answer to Swift for the profoundly lazy :)

if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
{
  // Strings are equal.
}

smooth scroll to top

You can simply use

_x000D_
_x000D_
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
        document.getElementById("gotoTop").style.display = "block";_x000D_
    } else {_x000D_
        document.getElementById("gotoTop").style.display = "none";_x000D_
    }_x000D_
   _x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
 _x000D_
     $('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  font-size: 20px;_x000D_
}_x000D_
_x000D_
#gotoTop {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 30px;_x000D_
  z-index: 99;_x000D_
  font-size: 18px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  cursor: pointer;_x000D_
  padding: 15px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
#gotoTop:hover {_x000D_
  background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="gotoTop" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
_x000D_
_x000D_

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
    root   /path/to/static-content;
}

location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

How to change an image on click using CSS alone?

No, you will need scripting to place a click Event handler on the Element that does what you want.

Get safe area inset top and bottom heights

To get the height between the layout guides you just do

let guide = view.safeAreaLayoutGuide
let height = guide.layoutFrame.size.height

So full frame height = 812.0, safe area height = 734.0

Below is the example where the green view has frame of guide.layoutFrame

enter image description here

CSS3 transition doesn't work with display property

You cannot use height: 0 and height: auto to transition the height. auto is always relative and cannot be transitioned towards. You could however use max-height: 0 and transition that to max-height: 9999px for example.

Sorry I couldn't comment, my rep isn't high enough...

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If you are using Laravel as your Backend, then edit your .htaccess file by just pasting this code, to solve problem CROS in your Angular or IONIC project

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Casting a variable using a Type variable

How could you do that? You need a variable or field of type T where you can store the object after the cast, but how can you have such a variable or field if you know T only at runtime? So, no, it's not possible.

Type type = GetSomeType();
Object @object = GetSomeObject();

??? xyz = @object.CastTo(type); // How would you declare the variable?

xyz.??? // What methods, properties, or fields are valid here?

Read Excel File in Python

The approach I took reads the header information from the first row to determine the indexes of the columns of interest.

You mentioned in the question that you also want the values output to a string. I dynamically build a format string for the output from the FORMAT column list. Rows are appended to the values string separated by a new line char.

The output column order is determined by the order of the column names in the FORMAT list.

In my code below the case of the column name in the FORMAT list is important. In the question above you've got 'Pincode' in your FORMAT list, but 'PinCode' in your excel. This wouldn't work below, it would need to be 'PinCode'.

from xlrd import open_workbook
wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
    formatString = ("%s,"*len(columnIndex))[0:-1] + "\n"

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        values += formatString % tuple(currentRowValues)

print values

For the sample input you gave above this code outputs:

>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0

And because I'm a python noob, props be to: this answer, this answer, this question, this question and this answer.

How to get the server path to the web directory in Symfony2 from inside the controller?

Since Symfony 3.3,

You can use %kernel.project_dir%/web/ instead of %kernel.root_dir%/../web/

How do I set headers using python's urllib?

adding HTTP headers using urllib2:

from the docs:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

Recursive search and replace in text files on Mac and Linux

https://bitbucket.org/masonicboom/serp is a go utility (i.e. cross-platform), tested on OSX, that does recursive search-and-replace for text in files within a given directory, and confirms each replacement. It's new, so might be buggy.

Usage looks like:

$ ls test
a  d  d2 z
$ cat test/z
hi
$ ./serp --root test --search hi --replace bye --pattern "*"                         
test/z: replace hi with bye? (y/[n]) y
$ cat test/z
bye

FormsAuthentication.SignOut() does not log the user out

Are you testing/seeing this behaviour using IE? It's possible that IE is serving up those pages from the cache. It is notoriously hard to get IE to flush it's cache, and so on many occasions, even after you log out, typing the url of one of the "secured" pages would show the cached content from before.

(I've seen this behaviour even when you log as a different user, and IE shows the "Welcome " bar at the top of your page, with the old user's username. Nowadays, usually a reload will update it, but if it's persistant, it could still be a caching issue.)

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

What does -save-dev mean in npm install grunt --save-dev

--save-dev: Package will appear in your devDependencies.

According to the npm install docs.

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.

In other words, when you run npm install, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).

According to the package.json docs

Edit: Attempt at visualising what npm install does:

  • yourproject
    • dependency installed
      • dependency installed
        • dependency installed
        • devDependency NOT installed
      • devDependency NOT installed
    • devDependency installed
      • dependency installed
      • devDependency NOT installed

boto3 client NoRegionError: You must specify a region error only sometimes

os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

In my case sensitivity mattered.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I had the same issue when I changed the home directory of one use. In my case it was because of selinux. I used the below to fix the issue:

selinuxenabled 0
setenforce 0

'App not Installed' Error on Android

I had the same type of error this was cauysed by this line in my android manifest XML file.

android:permission="android.permission.INSTALL_LOCATION_PROVIDER"

I removed the line and it solved my issue. Hope this helps

C# event with custom arguments

I might be late in the game, but how about:

public event Action<MyEvent> EventTriggered = delegate { }; 

private void Trigger(MyEvent e) 
{ 
     EventTriggered(e);
} 

Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.

I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

SQL Server: How to check if CLR is enabled?

This is @Jason's answer but with simplified output

SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'

The above returns the following:

| name        | Enabled |
-------------------------
| clr enabled | YES     |

Tested on SQL Server 2017

Vue.JS: How to call function after page loaded?

You import the function from outside the main instance, and don't add it to the methods block. so the context of this is not the vm.

Either do this:

ready() {
  checkAuth.call(this)
}

or add the method to your methods first (which will make Vue bind this correctly for you) and call this method:

methods: {
  checkAuth: checkAuth
},
ready() {
  this.checkAuth()
}

Remove all whitespaces from NSString

- (NSString *)removeWhitespaces {
  return [[self componentsSeparatedByCharactersInSet:
                    [NSCharacterSet whitespaceCharacterSet]]
      componentsJoinedByString:@""];
}

Python interpreter error, x takes no arguments (1 given)

Your updateVelocity() method is missing the explicit self parameter in its definition.

Should be something like this:

def updateVelocity(self):    
    for x in range(0,len(self.velocity)):
        self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 \
          * random.random()*(self.gbest[x]-self.current[x])

Your other methods (except for __init__) have the same problem.

cell format round and display 2 decimal places

Another way is to use FIXED function, you can specify the number of decimal places but it defaults to 2 if the places aren't specified, i.e.

=FIXED(E5,2)

or just

=FIXED(E5)

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

Make sure you have closed your MSAccess file before running the java program.

Use Ant for running program with command line arguments

If you do not want to handle separate properties for each possible argument, I suggest you'd use:

<arg line="${args}"/>

You can check if the property is not set using a specific target with an unless attribute and inside do:

<input message="Type the desired command line arguments:" addProperty="args"/>

Putting it all together gives:

<target name="run" depends="compile, input-runargs" description="run the project">
  <!-- You can use exec here, depending on your needs -->
  <java classname="Main">
    <arg line="${args}"/>
  </java>
</target>
<target name="input-runargs" unless="args" description="prompts for command line arguments if necessary">
  <input addProperty="args" message="Type the desired command line arguments:"/>
</target>

You can use it as follows:

ant
ant run
ant run -Dargs='--help'

The first two commands will prompt for the command-line arguments, whereas the latter won't.

Android ListView with different layouts for each row

ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType(), and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.

Check out this tutorial on how to use the RecyclerView to do what you are looking for.

Add support library to Android Studio project

In Android Studio 1.0, this worked for me :-
Open the build.gradle (Module : app) file and paste this (at the end) :-

dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
}

Note that this dependencies is different from the dependencies inside buildscript in build.gradle (Project)
When you edit the gradle file, a message shows that you must sync the file. Press "Sync now"

Source : https://developer.android.com/tools/support-library/setup.html#add-library

Build not visible in itunes connect

This was My Mistake:

I had a minor update in a Push Notification content part and I did not even touch my code.

But I thought I might have to re-upload it in order to reflect that change in the latest version.

And I did.

Tried to upload 3 Builds One by One.

But Not a single build has shown in the Test Flight Version.(Shocked)

Later I realized my mistake that just by updating APNS content part without even touching my code, I was trying to upload a new build and was expecting to reflect it in the Test Flight. (So stupid of me)

Why am I getting this error Premature end of file?

Use inputstream once don't use it multiple times and Do inputstream.close()

Adding new column to existing DataFrame in Python pandas

If we want to assign a scaler value eg: 10 to all rows of a new column in a df:

df = df.assign(new_col=lambda x:10)  # x is each row passed in to the lambda func

df will now have new column 'new_col' with value=10 in all rows.

How can I obtain the element-wise logical NOT of a pandas Series?

@unutbu's answer is spot on, just wanted to add a warning that your mask needs to be dtype bool, not 'object'. Ie your mask can't have ever had any nan's. See here - even if your mask is nan-free now, it will remain 'object' type.

The inverse of an 'object' series won't throw an error, instead you'll get a garbage mask of ints that won't work as you expect.

In[1]: df = pd.DataFrame({'A':[True, False, np.nan], 'B':[True, False, True]})
In[2]: df.dropna(inplace=True)
In[3]: df['A']
Out[3]:
0    True
1   False
Name: A, dtype object
In[4]: ~df['A']
Out[4]:
0   -2
0   -1
Name: A, dtype object

After speaking with colleagues about this one I have an explanation: It looks like pandas is reverting to the bitwise operator:

In [1]: ~True
Out[1]: -2

As @geher says, you can convert it to bool with astype before you inverse with ~

~df['A'].astype(bool)
0    False
1     True
Name: A, dtype: bool
(~df['A']).astype(bool)
0    True
1    True
Name: A, dtype: bool

Mercurial — revert back to old version and continue from there

After using hg update -r REV it wasn't clear in the answer about how to commit that change so that you can then push.

If you just try to commit after the update, Mercurial doesn't think there are any changes.

I had to first make a change to any file (say in a README) so Mercurial recognized that I made a new change, then I could commit that.

This then created two heads as mentioned.

To get rid of the other head before pushing, I then followed the No-Op Merges step to remedy that situation.

I was then able to push.

Float a div right, without impacting on design

What do you mean by impacts? Content will flow around a float. That's how they work.

If you want it to appear above your design, try setting:

z-index: 10;  
position: absolute;  
right: 0;  
top: 0;

How can I create an editable combo box in HTML/Javascript?

Here is a script for that: Demo, Source

Or another one which works slightly differently: link removed (site no longer exists)

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

How to get the real and total length of char * (char array)?

You can implement your own new and delete functions, as well as an additional get-size function:

#define CEIL_DIV(x,y) (((x)-1)/(y)+1)

void* my_new(int size)
{
    if (size > 0)
    {
        int* ptr = new int[1+CEIL_DIV(size,sizeof(int))];
        if (ptr)
        {
            ptr[0] = size;
            return ptr+1;
        }
    }
    return 0;
}

void my_delete(void* mem)
{
    int* ptr = (int*)mem-1;
    delete ptr;
}

int my_size(void* mem)
{
    int* ptr = (int*)mem-1;
    return ptr[0];
}

Alternatively, you can override the new and delete operators in a similar manner.