Programs & Examples On #Google api

Google offers a variety of APIs, mostly web APIs for web developers. The APIs are based on popular Google consumer products, including Google Maps, Google Earth, AdSense, Adwords, Google Apps and YouTube.

Using Postman to access OAuth 2.0 Google APIs

  1. go to https://console.developers.google.com/apis/credentials
  2. create web application credentials.

Postman API Access

  1. use these settings with oauth2 in Postman:

SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema

post https: //www.googleapis.com/admin/directory/v1/customer/customer-id/schemas

{
  "fields": [
    {
      "fieldName": "role",
      "fieldType": "STRING",
      "multiValued": true,
      "readAccessType": "ADMINS_AND_SELF"
    }
  ],
  "schemaName": "SAML"
}
  1. to patch user use:

SCOPE = https://www.googleapis.com/auth/admin.directory.user

PATCH https://www.googleapis.com/admin/directory/v1/users/[email protected]

 {
  "customSchemas": {
     "SAML": {
       "role": [
         {
          "value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
          "customType": "Admin"
         }
       ]
     }
   }
}

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

Why do access tokens expire?

A couple of scenarios might help illustrate the purpose of access and refresh tokens and the engineering trade-offs in designing an oauth2 (or any other auth) system:

Web app scenario

In the web app scenario you have a couple of options:

  1. if you have your own session management, store both the access_token and refresh_token against your session id in session state on your session state service. When a page is requested by the user that requires you to access the resource use the access_token and if the access_token has expired use the refresh_token to get the new one.

Let's imagine that someone manages to hijack your session. The only thing that is possible is to request your pages.

  1. if you don't have session management, put the access_token in a cookie and use that as a session. Then, whenever the user requests pages from your web server send up the access_token. Your app server could refresh the access_token if need be.

Comparing 1 and 2:

In 1, access_token and refresh_token only travel over the wire on the way between the authorzation server (google in your case) and your app server. This would be done on a secure channel. A hacker could hijack the session but they would only be able to interact with your web app. In 2, the hacker could take the access_token away and form their own requests to the resources that the user has granted access to. Even if the hacker gets a hold of the access_token they will only have a short window in which they can access the resources.

Either way the refresh_token and clientid/secret are only known to the server making it impossible from the web browser to obtain long term access.

Let's imagine you are implementing oauth2 and set a long timeout on the access token:

In 1) There's not much difference here between a short and long access token since it's hidden in the app server. In 2) someone could get the access_token in the browser and then use it to directly access the user's resources for a long time.

Mobile scenario

On the mobile, there are a couple of scenarios that I know of:

  1. Store clientid/secret on the device and have the device orchestrate obtaining access to the user's resources.

  2. Use a backend app server to hold the clientid/secret and have it do the orchestration. Use the access_token as a kind of session key and pass it between the client and the app server.

Comparing 1 and 2

In 1) Once you have clientid/secret on the device they aren't secret any more. Anyone can decompile and then start acting as though they are you, with the permission of the user of course. The access_token and refresh_token are also in memory and could be accessed on a compromised device which means someone could act as your app without the user giving their credentials. In this scenario the length of the access_token makes no difference to the hackability since refresh_token is in the same place as access_token. In 2) the clientid/secret nor the refresh token are compromised. Here the length of the access_token expiry determines how long a hacker could access the users resources, should they get hold of it.

Expiry lengths

Here it depends upon what you're securing with your auth system as to how long your access_token expiry should be. If it's something particularly valuable to the user it should be short. Something less valuable, it can be longer.

Some people like google don't expire the refresh_token. Some like stackflow do. The decision on the expiry is a trade-off between user ease and security. The length of the refresh token is related to the user return length, i.e. set the refresh to how often the user returns to your app. If the refresh token doesn't expire the only way they are revoked is with an explicit revoke. Normally, a log on wouldn't revoke.

Hope that rather length post is useful.

What are the alternatives now that the Google web search API has been deprecated?

There's a note on top of the docs:

Note: The Google Web Search API has been officially deprecated as of November 1, 2010. It will continue to work as per our deprecation policy, but the number of requests you may make per day will be limited. Therefore, we encourage you to move to the new Custom Search API.

The deprecation policy says that they will continue to run the API for 3 years. So if you already have an application that uses the old API, you don't have to rush to change things just yet. If you're writing a new application, use the Custom Search API. See my answer here for how to do this in Python, but the idea's the same for any language.

OAuth2 and Google API: access token expiration time?

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

I used Palek's solution inside a Bootstrap validator and it works. I'd have added a comment to his but I don'y have the rep;). Simplified version:

        $('#form').validator().on('submit', function (e) {
           var response = grecaptcha.getResponse();
           //recaptcha failed validation
           if(response.length == 0) {
               e.preventDefault();
               $('#recaptcha-error').show();
           }
           //recaptcha passed validation
           else {
               $('#recaptcha-error').hide();
           }
           if (e.isDefaultPrevented()) {
              return false;
           } else {
              return true;
           }
       });

Is there a link to the "latest" jQuery library on Google APIs?

DO NOT USE THIS ANSWER. The URL is pointing at jQuery 1.11 (and always will).

Credits to Basic for above snippet

http://code.jquery.com/jquery-latest.min.js is the minified version, always up-to-date.

invalid_grant trying to get oAuth token from google

In my case, the issue was in my code. Mistakenly I've tried to initiate client 2 times with the same tokens. If none of the answers above helped make sure you do not generate 2 instances of the client.

My code before the fix:

def gc_service
      oauth_client = Signet::OAuth2::Client.new(client_options)
      oauth_client.code = params[:code]
      response = oauth_client.fetch_access_token!
      session[:authorization] = response
      oauth_client.update!(session[:authorization])

      gc_service = Google::Apis::CalendarV3::CalendarService.new
      gc_service.authorization = oauth_client

      gc_service
    end
primary_calendar_id = gc_service.list_calendar_lists.items.select(&:primary).first.id

gc_service.insert_acl(primary_calendar_id, acl_rule_object, send_notifications: false)

as soon as I change it to (use only one instance):

@gc_service = gc_service
primary_calendar_id = @gc_service.list_calendar_lists.items.select(&:primary).first.id

@gc_service.insert_acl(primary_calendar_id, acl_rule_object, send_notifications: false)

it fixed my issues with grant type.

Alternative to google finance api

If you are still looking to use Google Finance for your data you can check this out.

I recently needed to test if SGX data is indeed retrievable via google finance (and of course i met with the same problem as you)

Is there a Google Keep API?

No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.

Check this link: https://developers.google.com/gsuite/products for updates.

However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi

Get user info via Google API

Add this to the scope - https://www.googleapis.com/auth/userinfo.profile

And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json

It has loads of stuff - including name, public profile url, gender, photo etc.

How to use Google Translate API in my Java application?

Generate your own API key here. Check out the documentation here.

You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.

Below is a quick start example which translates two English strings to Spanish:

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;

public class QuickstartSample
{
    public static void main(String[] arguments) throws IOException, GeneralSecurityException
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
                // Set your application name
                .setApplicationName("Stackoverflow-Example")
                .build();
        Translate.Translations.List list = t.new Translations().list(
                Arrays.asList(
                        // Pass in list of strings to be translated
                        "Hello World",
                        "How to use Google Translate from Java"),
                // Target language
                "ES");

        // TODO: Set your API-Key from https://console.developers.google.com/
        list.setKey("your-api-key");
        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Required maven dependencies for the code snippet:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-translate</artifactId>
    <version>LATEST</version>
</dependency>

<dependency>
    <groupId>com.google.http-client</groupId>
    <artifactId>google-http-client-gson</artifactId>
    <version>LATEST</version>
</dependency>

This IP, site or mobile application is not authorized to use this API key

  url = https://maps.googleapis.com/maps/api/directions/json?origin=19.0176147,72.8561644&destination=28.65381,77.22897&mode=driving&key=AIzaSyATaUNPUjc5rs0lVp2Z_spnJle-AvhKLHY

add only in AppDelegate like

            GMSServices.provideAPIKey("AIzaSyATaUNPUjc5rs0lVp2Z_spnJle-AvhKLHY")

and remove the key in this url.

now url is

https://maps.googleapis.com/maps/api/directions/json?origin=19.0176147,72.8561644&destination=28.65381,77.22897&mode=driving

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

In my case the sub domain name causes the problem. Here are details

I used app_development.something.com, here underscore(_) sub domain is creating CORS error. After changing app_development to app-development it works fine.

Getting Google+ profile picture url with user_id

trying to access the /s2/profile/photo url works for most users but not all.

The only full proof method is to use the Google+ API. You don't need user authentication to request public profile data so it's a rather simple method:

  1. Get a Google+ API key on https://cloud.google.com/console

  2. Make a simple GET request to: https://www.googleapis.com/plus/v1/people/+< username >?key=

Note the + before the username. If you use user ids instead (the long string of digits), you don't need the +

  1. you will get a very comprehensive JSON representation of the profile data which includes: "image":{"url": "https://lh4.googleusercontent.com/..... the rest of the picture url...."}

Where can I get Google developer key

Please use Google API console
Create a new project
For the created project goto API access
There you will find your Client ID and Secret. And the API key in the last is your developer key.

How can I access Google Sheet spreadsheets only with Javascript?

Here's the Gist.

You can create a spreadsheet using the Google Sheets API. There is currently no way to delete a spreadsheet using the API (read the documentation). Think of Google Docs API as the route to create and look-up documents.

You can add/remove worksheets within the spreadsheet using the worksheet based feeds.

Updating a spreadsheet is done through either list based feeds or cell based feeds.

Reading the spreadsheet can be done through either the Google Spreadsheets APIs mentioned above or, for published sheets only, by using the Google Visualization API Query Language to query the data (which can return results in CSV, JSON, or HTML table format).


Forget jQuery. jQuery is only really valuable if you're traversing the DOM. Since GAS (Google Apps Scripting) doesn't use the DOM jQuery will add no value to your code. Stick to vanilla.

I'm really surprised that nobody has provided this information in an answer yet. Not only can it be done, but it's relatively easy to do using vanilla JS. The only exception being the Google Visualization API which is relatively new (as of 2011). The Visualization API also works exclusively through a HTTP query string URI.

How can I get stock quotes using Google Finance API?

Here is an example that you can use. Havent got Google Finance yet, but Here is the Yahoo Example. You will need the HTMLAgilityPack , Which is awesome. Happy Symbol Hunting.

Call the procedure by using YahooStockRequest(string Symbols);

Where Symbols = a comma-delimited string of symbols, or just one symbol

public string YahooStockRequest(string Symbols,bool UseYahoo=true)
        {
            {
                string StockQuoteUrl = string.Empty;

                try
                {
                    // Use Yahoo finance service to download stock data from Yahoo
                    if (UseYahoo)
                    {
                        string YahooSymbolString = Symbols.Replace(",","+");
                        StockQuoteUrl = @"http://finance.yahoo.com/q?s=" + YahooSymbolString + "&ql=1";
                    }
                    else
                    {
                        //Going to Put Google Finance here when I Figure it out.
                    }

                    // Initialize a new WebRequest.
                    HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(StockQuoteUrl);
                    // Get the response from the Internet resource.
                    HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                    // Read the body of the response from the server.

                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    string pageSource;
                    using (StreamReader sr = new StreamReader(webresp.GetResponseStream()))
                    {
                        pageSource = sr.ReadToEnd();
                    }
                    doc.LoadHtml(pageSource.ToString());
                    if (UseYahoo)
                    {
                        string Results=string.Empty;
                        //loop through each Symbol that you provided with a "," delimiter
                        foreach (string SplitSymbol in Symbols.Split(new char[] { ',' }))
                        {
                            Results+=SplitSymbol + " : " + doc.GetElementbyId("yfs_l10_" + SplitSymbol).InnerText + Environment.NewLine;
                        }
                        return (Results);
                    }
                    else
                    {
                        return (doc.GetElementbyId("ref_14135_l").InnerText);
                    }

                }
                catch (WebException Webex)
                {
                    return("SYSTEM ERROR DOWNLOADING SYMBOL: " + Webex.ToString());

                }

            }
        }

How to refresh token with Google API client?

I have a same problem with google/google-api-php-client v2.0.0-RC7 and after search for 1 hours, i solved this problem using json_encode like this:

    if ($client->isAccessTokenExpired()) {
        $newToken = json_decode(json_encode($client->getAccessToken()));
        $client->refreshToken($newToken->refresh_token);
        file_put_contents(storage_path('app/client_id.txt'), json_encode($client->getAccessToken()));
    }

RegEx for Javascript to allow only alphanumeric

/^([a-zA-Z0-9 _-]+)$/

the above regex allows spaces in side a string and restrict special characters.It Only allows a-z, A-Z, 0-9, Space, Underscore and dash.

Changing background colour of tr element on mouseover

You could try:

tr:hover {
    background-color: #000;
}

tr:hover td {
    background-color: transparent; /* or #000 */
}

JS Fiddle demo.

How do I protect javascript files?

I think the only way is to put required data on the server and allow only logged-in user to access the data as required (you can also make some calculations server side). This wont protect your javascript code but make it unoperatable without the server side code

Java collections convert a string to a list of characters

The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:

List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);

Fatal error: [] operator not supported for strings

I had similar situation:

$foo = array();
$foo[] = 'test'; // error    
$foo[] = "test"; // working fine

Enum Naming Convention - Plural

In general, the best practice recommendation is singular, except for those enums that have the [Flags] attribute attached to them, (and which therefore can contain bit fields), which should be plural.

After reading your edited question, I get the feeling you may think the property name or variable name has to be different from the enum type name... It doesn't. The following is perfectly fine...

  public enum Status { New, Edited, Approved, Cancelled, Closed }

  public class Order
  {
      private Status stat;
      public Status Status
      { 
         get { return stat; }
         set { stat = value; }
      }
  }

Accessing dict_keys element by index in Python3

I wanted "key" & "value" pair of a first dictionary item. I used the following code.

 key, val = next(iter(my_dict.items()))

How to convert an OrderedDict into a regular dict in python3

>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!

Given a DateTime object, how do I get an ISO 8601 date in string format?

I would just use XmlConvert:

XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);

It will automatically preserve the time zone.

How to order events bound with jQuery

You can try something like this:

/**
  * Guarantee that a event handler allways be the last to execute
  * @param owner The jquery object with any others events handlers $(selector)
  * @param event The event descriptor like 'click'
  * @param handler The event handler to be executed allways at the end.
**/
function bindAtTheEnd(owner,event,handler){
    var aux=function(){owner.unbind(event,handler);owner.bind(event,handler);};
    bindAtTheStart(owner,event,aux,true);

}
/**
  * Bind a event handler at the start of all others events handlers.
  * @param owner Jquery object with any others events handlers $(selector);
  * @param event The event descriptor for example 'click';
  * @param handler The event handler to bind at the start.
  * @param one If the function only be executed once.
**/
function bindAtTheStart(owner,event,handler,one){
    var eventos,index;
    var handlers=new Array();
    owner.unbind(event,handler);
    eventos=owner.data("events")[event];
    for(index=0;index<eventos.length;index+=1){
        handlers[index]=eventos[index];
    }
    owner.unbind(event);
    if(one){
        owner.one(event,handler);
    }
    else{
        owner.bind(event,handler);
    }
    for(index=0;index<handlers.length;index+=1){
        owner.bind(event,ownerhandlers[index]);
    }   
}

How to manually include external aar package using new Gradle Android Build System

In my case I have some depencies in my library and when I create an aar from it I failed, because of missed depencies, so my solution is to add all depencies from my lib with an arr file.

So my project level build.gradle looks so:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
        //add it to be able to add depency to aar-files from libs folder in build.gradle(yoursAppModule)
        flatDir {
            dirs 'libs'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(modile app) so:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.sampleapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //your project depencies
    ...
    //add lib via aar-depency
    compile(name: 'aarLibFileNameHere', ext: 'aar')
    //add all its internal depencies, as arr don't have it
    ...
}

and library build.gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    //here goes library projects dependencies, which you must include
    //in yours build.gradle(modile app) too
    ...
}

export html table to csv

Should work on every modern browser and without jQuery or any dependency, here my implementation :

// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ',') {
    // Select rows from table_id
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    // Construct csv
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            // Clean innertext to remove multiple spaces and jumpline (break csv)
            var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
            // Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
            data = data.replace(/"/g, '""');
            // Push escaped string
            row.push('"' + data + '"');
        }
        csv.push(row.join(separator));
    }
    var csv_string = csv.join('\n');
    // Download it
    var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

Then add your download button/link :

<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>

CSV file is timedated and compatible with default Excel format.

Update after comments: Added second parameter "separator", it can be used to configure another character like ;, it's useful if you have user downloading your csv in different region of the world because they can use another default separator for Excel, for more information see : https://superuser.com/a/606274/908273

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

How to use a WSDL file to create a WCF service (not make a call)

Using the "Add Service Reference" tool in Visual Studio, you can insert the address as:

file:///path/to/wsdl/file.wsdl

And it will load properly.

How to do a PUT request with curl?

An example PUT following Martin C. Martin's comment:

curl -T filename.txt http://www.example.com/dir/

With -T (same as --upload-file) curl will use PUT for HTTP.

Regular Expression for matching parentheses

Two options:

Firstly, you can escape it using a backslash -- \(

Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]

Trying to use fetch and pass in mode: no-cors

The simple solution: Add the following to the very top of the php file you are requesting the data from.

header("Access-Control-Allow-Origin: *");

Where do I find the Instagram media ID of a image

Same thing you can implement in Python-

import requests,json

def get_media_id(media_url):
   url = 'https://api.instagram.com/oembed/?callback=&url=' + media_url
   response = requests.get(url).json()
   print(response['media_id'])

get_media_id('MEDIA_URL')

What is the MySQL JDBC driver connection string?

Assuming your driver is in path,

String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, "username", "password");

CreateProcess error=206, The filename or extension is too long when running main() method

This is because of your long project directory name, which gives you a very long CLASSPATH altogether. Either you need to reduce jars added at CLASSPATH (make sure removing unnecessary jars only) Or the best way is to reduce the project directory and import the project again. This will reduce the CLASSPATH. It worked for me.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

I wonder if this question has been answered well: how css margins work and why is it that margin-top:-5; is not the same as margin-bottom:5;?

Margin is distance from the surroundings of the element. margin-top says "... distance from surroundings as we measure from top 'side' of the element's 'box' and margin-bottom being the distance from the bottom 'side' of the 'box'". Then margin-top:5; is concerned with the top 'side' perimeter,-5 in that case; anything approaching from top 'side' can overlap top 'side' of element by 5, and margin-bottom:5; means distance between element bottom 'side' and surrounding is 5.

Basically that but affected by float'ed elements and the like: http://www.w3.org/TR/CSS2/box.html#margin-properties.

http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide-to-using-negative-margins/

I stand to be corrected.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

If it is OK to use .NET code I'd suggest using SMO: http://msdn.microsoft.com/en-us/library/ms162169.aspx, In your particular case it would be the Table class http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.table.aspx This would be a more portable solution than using version specific system views and tables.

If this is something you are going to use on a regular basis - you might want to write a simple console application, perhaps with a runtime T4 code generator http://msdn.microsoft.com/en-us/library/ee844259.aspx

If it's just a one-off task - you could use my LiveDoco's( http://www.livedoco.com ) export to XML feature with an optional XSLT transform or I'm sure there are free tools out there that can do this. This one looks okay: http://sqldbdoc.codeplex.com/ - supports XML via XSLT, but I'm not sure if you can run it for a selection of tables though (With LiveDoco you can).

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

What is a PDB file?

PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.

This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb files. So effectively pdb files are really a boon to developers while debugging a program.

Generally it is not recommended to exclude the generation of *.pdb files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.

If you still want to disable generation of *.pdb files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none from "Debug Info" drop-down box -> press OK as shown in the snapshot below.

None Debug Info setting for a C# Project

Note: This setting will have to be done separately for "Debug" and "Release" build configurations.

How do you convert CString and std::string std::wstring to each other?

Solve that by using std::basic_string<TCHAR> instead of std::string and it should work fine regardless of your character setting.

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

CSS transition shorthand with multiple properties?

This helped me understand / streamline, only what I needed to animate:

// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}

.base {
  max-width: 0vw;
  opacity: 0;

  transition-property: max-width, opacity; // relative order
  transition-duration: 2s, 4s; // effects relatively ordered animation properties
  transition-delay: 6s; // effects delay of all animation properties
  animation-timing-function: ease;

  &:hover {
    max-width: 100vw;
    opacity: 1;

    transition-duration: 5s; // effects duration of all aniomation properties
    transition-delay: 2s, 7s; // effects relatively ordered animation properties
  }
}

~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class

push multiple elements to array

You can push multiple elements into an array in the following way

_x000D_
_x000D_
var a = [];_x000D_
    _x000D_
a.push(1, 2, 3);_x000D_
_x000D_
console.log(a);
_x000D_
_x000D_
_x000D_

FirstOrDefault: Default value other than null

You can use DefaultIfEmpty followed by First:

T customDefault = ...;
IEnumerable<T> mySequence = ...;
mySequence.DefaultIfEmpty(customDefault).First();

How to get last key in an array?

I would also like to offer an alternative solution to this problem.

Assuming all your keys are numeric without any gaps, my preferred method is to count the array then minus 1 from that value (to account for the fact that array keys start at 0.

$array = array(0=>'dog', 1=>'cat');

$lastKey = count($array)-1;
$lastKeyValue = $array[$lastKey];

var_dump($lastKey);
print_r($lastKeyValue);

This would give you:

int(1) cat

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

What is the T-SQL syntax to connect to another SQL Server?

In SQL Server Management Studio, turn on SQLCMD mode from the Query menu. Then at the top of your script, type in the command below

:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]

If you are connecting to multiple servers, be sure to insert GO between connections; otherwise your T-SQL won't execute on the server you're thinking it will.

VBA collection: list of keys

An alternative solution is to store the keys in a separate Collection:

'Initialise these somewhere.
Dim Keys As Collection, Values As Collection

'Add types for K and V as necessary.
Sub Add(K, V) 
Keys.Add K
Values.Add V, K
End Sub

You can maintain a separate sort order for the keys and the values, which can be useful sometimes.

How can I align two divs horizontally?

Nowadays, we could use some flexbox to align those divs.

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div>_x000D_
        <span>source list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
_x000D_
    <div>_x000D_
        <span>destination list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making div content responsive

try this css:

/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}

/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */    
@media only screen and (max-width: 479px){
    #container2 { width: 90%; }
}

Here the demo: http://jsfiddle.net/ongisnade/CG9WN/

git-diff to ignore ^M

Why do you get these ^M in your git diff?

In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M at the end of the lines I added in git diff. I think the ^M were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR line endings, and in OS X it uses LF line endings.

Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.

So what should we do about this?

You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.

If you go for this option, you should however fix the current files (because they're still using the CR line endings). I did this by following these steps:

  1. Remove all files from the repository, but not from your filesystem.

    git rm --cached -r .
    
  2. Add a .gitattributes file that enforces certain files to use a LF as line endings. Put this in the file:

    *.ext text eol=crlf
    

    Replace .ext with the file extensions you want to match.

  3. Add all the files again.

    git add .
    

    This will show messages like this:

    warning: CRLF will be replaced by LF in <filename>.
    The file will have its original line endings in your working directory.
    
  4. You could remove the .gitattributes file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.

  5. Commit and push it all.

  6. Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:

    The file will have its original line endings in your working directory.
    

    You can do something like this to remove the files:

    git ls | grep ".ext$" | xargs rm -f
    

    And then this to get them back with the correct line endings:

    git ls | grep ".ext$" | xargs git checkout
    

    Of course replacing .ext with the extension you want.

Now your project only uses LF characters for the line endings, and the nasty CR characters won't ever come back :).

The other option is to enforce windows style line endings. You can also use the .gitattributes file for this.

More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all

Entity Framework rollback and remove bad migration

I am using EF Core with ASP.NET Core V2.2.6. @Richard Logwood's answer was great and it solved my problem, but I needed a different syntax.

So, For those using EF Core with ASP.NET Core V2.2.6 +...

instead of

Update-Database <Name of last good migration>

I had to use:

dotnet ef database update <Name of last good migration>

And instead of

Remove-Migration

I had to use:

dotnet ef migrations remove

For --help i had to use :

dotnet ef migrations --help


Usage: dotnet ef migrations [options] [command]

Options:
  -h|--help        Show help information
  -v|--verbose     Show verbose output.
  --no-color       Don't colorize output.
  --prefix-output  Prefix output with level.

Commands:
  add     Adds a new migration.
  list    Lists available migrations.
  remove  Removes the last migration.
  script  Generates a SQL script from migrations.

Use "migrations [command] --help" for more information about a command.

This let me role back to the stage where my DB worked as expected, and start from beginning.

"Invalid signature file" when attempting to run a .jar

In case you're using gradle, here is a full farJar task:

version = '1.0'
//create a single Jar with all dependencies
task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Title': 'Gradle Jar File Example',  
            'Implementation-Version': version,
            'Main-Class': 'com.example.main'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA' 
    with jar
}

HTML table needs spacing between columns, not rows

The better approach uses Shredder's css rule: padding: 0 15px 0 15px only instead of inline css, define a css rule that applies to all tds. Do This by using a style tag in your page:

<style type="text/css">
td
{
    padding:0 15px;
}
</style>

or give the table a class like "paddingBetweenCols" and in the site css use

.paddingBetweenCols td
{
    padding:0 15px;
}

The site css approach defines a central rule that can be reused by all pages.

If your doing to use the site css approach, it would be best to define a class like above and apply the padding to the class...unless you want all td's on the entire site to have the same rule applied.

Fiddle for using style tag

Fiddle for using site css

How do I prevent Eclipse from hanging on startup?

JAVA VERSION COULD BE PROBLEM:

I tried few answers given above. But it didnot work. But meanwhile I was trying them it clicked to me that I switched the java version for some other stuff & forgot to switch back.

Once I jumped back to the previous version. Eclipse started working for me.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Linux - Install redis-cli only

# get system libraries
sudo yum install -y gcc wget

# get stable version and untar it
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make redis-cli

If the build fails / make command fails, then :

Removing all line with _Atomic from src/server.h and src/networking.c should makes the compile complete.

# make it globally accesible
sudo cp src/redis-cli /usr/local/bin/

SQL: How to properly check if a record exists

The other answers are quite good, but it would also be useful to add LIMIT 1 (or the equivalent, to prevent the checking of unnecessary rows.

Laravel Check If Related Model Exists

In php 7.2+ you can't use count on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:

$model->relation()->exists()

generic solution working on all the relation types (pre php 7.2):

if (count($model->relation))
{
  // exists
}

This will work for every relation since dynamic properties return Model or Collection. Both implement ArrayAccess.

So it goes like this:

single relations: hasOne / belongsTo / morphTo / morphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

to-many relations: hasMany / belongsToMany / morphMany / morphToMany / morphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

MySQL load NULL values from CSV data

MySQL manual says:

When reading data with LOAD DATA INFILE, empty or missing columns are updated with ''. If you want a NULL value in a column, you should use \N in the data file. The literal word “NULL” may also be used under some circumstances.

So you need to replace the blanks with \N like this:

1,2,3,4,5
1,2,3,\N,5
1,2,3

How to find and replace all occurrences of a string recursively in a directory tree?

Try this:

find /home/user/ -type f | xargs sed -i  's/a\.example\.com/b.example.com/g'

In case you want to ignore dot directories

find . \( ! -regex '.*/\..*' \) -type f | xargs sed -i 's/a\.example\.com/b.example.com/g'

Edit: escaped dots in search expression

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Finally, I got a solution!

My Context is:- I want disconnect socket connection when activity destroyed, I tried to finish() activity but it didn't work me, its keep connection live somewhere.

so I use android.os.Process.killProcess(android.os.Process.myPid()); its kill my activity and i used android:excludeFromRecents="true" for remove from recent activity .

Creating dummy variables in pandas for python

The following code returns dataframe with the 'Category' column replaced by categorical columns:

df_with_dummies = pd.get_dummies(df, prefix='Category_', columns=['Category'])

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Align Bootstrap Navigation to Center

Add 'justified' class to 'ul'.

<ul class="nav navbar-nav justified">

CSS:

.justified {
    position:absolute;
    left:50%;
}

Now, calculate its 'margin-left' in order to align it to center.

// calculating margin-left to align it to center;
var width = $('.justified').width();
$('.justified').css('margin-left', '-' + (width / 2)+'px');

JSFiddle Code

JSFiddle Embedded Link

Add new value to an existing array in JavaScript

Indeed, you must initialize your array then right after that use array.push() command line.

var array = new Array();
array.push("first value");
array.push("second value");

How do I run a class in a WAR from the command line?

the best way if you use Spring Boot is :

1/ Create a ServletInitializer extends SpringBootServletInitializer Class . With method configure which run your Application Class

2/ Generate always a maven install WAR file

3/ With this artefact you can even :

    . start application from war file with java -jar file.war

    . put your war file in your favorite Web App server (like tomcat, ...)

How to start Spyder IDE on Windows

The name of the spyder executable was changed to spyder3.exe in python version 3. I install pyqt5 and spyder via pip and was able to launch spyder3. I first tried without installing pyqt5 and nothing happened. Once I installed pyqt5, then spyder 3 opened.

Try the following from a windows cmd.exe prompt:

    C:\Users\..>pip install pyqt5
    C:\Users\..>pip install spyder
    C:\Users\..>spyder3

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Detect whether current Windows version is 32 bit or 64 bit

I want to add what I use in shell scripts (but can easily be used in any language) here. The reason is, that some of the solutions here don't work an WoW64, some use things not really meant for that (checking if there is a *(x86) folder) or don't work in cmd scripts. I feel, this is the "proper" way to do it, and should be safe even in future versions of Windows.

 @echo off
 if /i %processor_architecture%==AMD64 GOTO AMD64
 if /i %PROCESSOR_ARCHITEW6432%==AMD64 GOTO AMD64
    rem only defined in WoW64 processes
 if /i %processor_architecture%==x86 GOTO x86
 GOTO ERR
 :AMD64
    rem do amd64 stuff
 GOTO EXEC
 :x86
    rem do x86 stuff
 GOTO EXEC
 :EXEC
    rem do arch independent stuff
 GOTO END
 :ERR
    rem I feel there should always be a proper error-path!
    @echo Unsupported architecture!
    pause
 :END

How do I convert from BLOB to TEXT in MySQL?

Here's an example of a person who wants to convert a blob to char(1000) with UTF-8 encoding:

CAST(a.ar_options AS CHAR(10000) CHARACTER SET utf8)

This is his answer. There is probably much more you can read about CAST right here. I hope it helps some.

How to build minified and uncompressed bundle with webpack?

I found a new solution for this problem.

This uses an array of configuration to enable webpack to build the minified and non-minified version in parallel. This make build faster. No need to run the webpack twice. No need extra plugins. Just webpack.

webpack.config.js

const devConfig = {
  mode: 'development',
  entry: { bundle: './src/entry.js' },
  output: { filename: '[name].js' },
  module: { ... },
  resolve: { ... },
  plugins: { ... }
};

const prodConfig = {
  ...devConfig,
  mode: 'production',
  output: { filename: '[name].min.js' }
};

module.exports = (env) => {
  switch (env) {
    case 'production':
      return [devConfig, prodConfig];
    default:
      return devConfig;
  }
};

Running webpack will only build the non-minified version.

Running webpack --env=production will build the minified and non-minified version at the same time.

pandas read_csv and filter columns with usecols

The solution lies in understanding these two keyword arguments:

  • names is only necessary when there is no header row in your file and you want to specify other arguments (such as usecols) using column names rather than integer indices.
  • usecols is supposed to provide a filter before reading the whole DataFrame into memory; if used properly, there should never be a need to delete columns after reading.

So because you have a header row, passing header=0 is sufficient and additionally passing names appears to be confusing pd.read_csv.

Removing names from the second call gives the desired output:

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        header=0,
        index_col=["date", "loc"], 
        usecols=["date", "loc", "x"],
        parse_dates=["date"])

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

Sum values from an array of key-value pairs in JavaScript

You can use the native map method for Arrays. map Method (Array) (JavaScript)

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
var a = 0;
myData.map( function(aa){ a += aa[1];  return a; });

a is your result

npm install error from the terminal

You're likely not in the node directory. Try switching to the directory that you unpacked node to and try running the command there.

How to set up file permissions for Laravel?

First of your answer is.

sudo chmod -R 777/775 /path/project_folder

Now You need to understand permissions and options in ubuntu.

  • chmod - You can set permissions.
  • chown - You can set the ownership of files and directories.
  • 777 - read/write/execute.
  • 775 - read/execute.

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

How to express a NOT IN query with ActiveRecord/Rails?

Here is a more complex "not in" query, using a subquery in rails 4 using squeel. Of course very slow compared to the equivalent sql, but hey, it works.

    scope :translations_not_in_english, ->(calmapp_version_id, language_iso_code){
      join_to_cavs_tls_arr(calmapp_version_id).
      joins_to_tl_arr.
      where{ tl1.iso_code == 'en' }.
      where{ cavtl1.calmapp_version_id == my{calmapp_version_id}}.
      where{ dot_key_code << (Translation.
        join_to_cavs_tls_arr(calmapp_version_id).
        joins_to_tl_arr.    
        where{ tl1.iso_code == my{language_iso_code} }.
        select{ "dot_key_code" }.all)}
    }

The first 2 methods in the scope are other scopes which declare the aliases cavtl1 and tl1. << is the not in operator in squeel.

Hope this helps someone.

How to Load Ajax in Wordpress

Use wp_localize_script and pass url there:

wp_localize_script( some_handle, 'admin_url', array('ajax_url' => admin_url( 'admin-ajax.php' ) ) );

then inside js, you can call it by

admin_url.ajax_url 

Automatically set appsettings.json for dev and release environments in asp.net core?

.vscode/launch.json file is only used by Visual Studio as well as /Properties/launchSettings.json file. Don't use these files in production.

The launchSettings.json file:

  1. Is only used on the local development machine.
  2. Is not deployed.
  3. contains profile settings.

    • Environment values set in launchSettings.json override values set in the system environment

To use a file 'appSettings.QA.json' for example. You can use 'ASPNETCORE_ENVIRONMENT'. Follow the steps below.

  1. Add a new Environment Variable on the host machine and call it 'ASPNETCORE_ENVIRONMENT'. Set its value to 'QA'.
  2. Create a file 'appSettings.QA.json' in your project. Add your configuration here.
  3. Deploy to the machine in step 1. Confirm 'appSettings.QA.json' is deployed.
  4. Load your website. Expect appSettings.QA.json to be used in here.

TypeError: a bytes-like object is required, not 'str' in python and CSV

just change wb to w

outfile=open('./immates.csv','wb')

to

outfile=open('./immates.csv','w')

MongoDB: How to query for records where field is null or not set?

db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();

Exploitable PHP functions

i'd particularly want to add unserialize() to this list. It has had a long history of various vulnerabilities including arbitrary code execution, denial of service and memory information leakage. It should never be called on user-supplied data. Many of these vuls have been fixed in releases over the last dew years, but it still retains a couple of nasty vuls at the current time of writing.

For other information about dodgy php functions/usage look around the Hardened PHP Project and its advisories. Also the recent Month of PHP Security and 2007's Month of PHP Bugs projects

Also note that, by design, unserializing an object will cause the constructor and destructor functions to execute; another reason not to call it on user-supplied data.

c++ exception : throwing std::string

A few principles:

  1. you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.

  2. Don't throw pointers but object, that way memory is handled for you.

Example:

struct MyException : public std::exception
{
   std::string s;
   MyException(std::string ss) : s(ss) {}
   ~MyException() throw () {} // Updated
   const char* what() const throw() { return s.c_str(); }
};

And then use it in your code:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw MyException("it's the end of the world!");
  }
}

void Foo::Caller(){
  try{
    this->Bar();// should throw
  }catch(MyException& caught){
    std::cout<<"Got "<<caught.what()<<std::endl;
  }
}

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

SELECT only rows that contain only alphanumeric characters in MySQL

Try this code:

SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$'

This makes sure that all characters match.

Get JavaScript object from array of objects by value of property

I don't know why you are against a for loop (presumably you meant a for loop, not specifically for..in), they are fast and easy to read. Anyhow, here's some options.

For loop:

function getByValue(arr, value) {

  for (var i=0, iLen=arr.length; i<iLen; i++) {

    if (arr[i].b == value) return arr[i];
  }
}

.filter

function getByValue2(arr, value) {

  var result  = arr.filter(function(o){return o.b == value;} );

  return result? result[0] : null; // or undefined

}

.forEach

function getByValue3(arr, value) {

  var result = [];

  arr.forEach(function(o){if (o.b == value) result.push(o);} );

  return result? result[0] : null; // or undefined

}

If, on the other hand you really did mean for..in and want to find an object with any property with a value of 6, then you must use for..in unless you pass the names to check.

Example

function getByValue4(arr, value) {
  var o;

  for (var i=0, iLen=arr.length; i<iLen; i++) {
    o = arr[i];

    for (var p in o) {
      if (o.hasOwnProperty(p) && o[p] == value) {
        return o;
      }
    }
  }
}

How to view the Folder and Files in GAC?

To view the files just browse them from the command prompt (cmd), eg.:

c:\>cd \Windows\assembly\GAC_32
c:\Windows\assembly\GAC_32> dir

To add and remove files from the GAC use the tool gacutil

Turn a single number into single digits Python

The easiest way is to turn the int into a string and take each character of the string as an element of your list:

>>> n = 43365644 
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits)  # use the extends method if you want to add the list to another

It involves a casting operation, but it's readable and acceptable if you don't need extreme performance.

git pull from master into the development branch

Situation: Working in my local branch, but I love to keep-up updates in the development branch named dev.

Solution: Usually, I prefer to do :

git fetch
git rebase origin/dev

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

A tip for others: if you have NI applications installed, the NI Application Web Server also uses the port 8080.

Difference between Math.Floor() and Math.Truncate()

Truncate drops the decimal point.

How to call a PHP function on the click of a button

Try this:

if($_POST['select'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    select();
}
if($_POST['insert'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    insert();
}

Oracle Not Equals Operator

As everybody else has said, there is no difference. (As a sanity check I did some tests, but it was a waste of time, of course they work the same.)

But there are actually FOUR types of inequality operators: !=, ^=, <>, and ¬=. See this page in the Oracle SQL reference. On the website the fourth operator shows up as ÿ= but in the PDF it shows as ¬=. According to the documentation some of them are unavailable on some platforms. Which really means that ¬= almost never works.

Just out of curiosity, I'd really like to know what environment ¬= works on.

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

change PYTHONHOME to the parent folder of the bin file of python, like /usr,which is the parent folder of /usr/bin.

How to get "GET" request parameters in JavaScript?

try the below code, it will help you get the GET parameters from url . for more details.

 var url_string = window.location.href; // www.test.com?filename=test
    var url = new URL(url_string);
    var paramValue = url.searchParams.get("filename");
    alert(paramValue)

relative path in BAT script

You should be able to use the current directory

"%CD%"\bin\Iris.exe

What is the purpose of Android's <merge> tag in XML layouts?

<merge/> is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.

For example, if you were to <include/> a layout from another file without using merge, the two files might look something like this:

layout1.xml:

<FrameLayout>
   <include layout="@layout/layout2"/>
</FrameLayout>

layout2.xml:

<FrameLayout>
   <TextView />
   <TextView />
</FrameLayout>

which is functionally equivalent to this single layout:

<FrameLayout>
   <FrameLayout>
      <TextView />
      <TextView />
   </FrameLayout>
</FrameLayout>

That FrameLayout in layout2.xml may not be useful. <merge/> helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):

layout2.xml:

<merge>
   <TextView />
   <TextView />
</merge>

This is functionally equivalent to this layout:

<FrameLayout>
   <TextView />
   <TextView />
</FrameLayout>

but since you are using <include/> you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

OpenCV with Network Cameras

rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).

Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/

I did not need to compile OpenCV with ffmpg support.

How to concatenate items in a list to a single string?

If you want to generate a string of strings separated by commas in final result, you can use something like this:

sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"

I hope this can help someone.

CSS media query to target iPad and iPad only?

/*working only in ipad portrait device*/
@media only screen and (width: 768px) and (height: 1024px) and (orientation:portrait) {
  body{
    background: red !important;
  }  
}
/*working only in ipad landscape device*/
@media all and (width: 1024px) and (height: 768px) and (orientation:landscape){
  body{
    background: green !important;
  }   
}

In the media query of specific devices, please use '!important' keyword to override the default CSS. Otherwise that does not change your webpage view on that particular devices.

Firebase cloud messaging notification not received by device

I faced the same issue of Firebase cloud messaging not received by device.

In my case package name defined on Firebase Console Project was diferent than that the one defined on Manifest & Gradle of my Android Project.

As a result I received token correctly but no messages at all.

To sumarize, it's mandatory that Firebase Console package name and Manifest & Gradle matchs.

You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden.

Calling a Variable from another Class

You need to specify an access modifier for your variable. In this case you want it public.

public class Variables
{
    public static string name = "";
}

After this you can use the variable like this.

Variables.name

Checking if a list of objects contains a property with a specific value

Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll instance method:

List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);

For each row return the column name of the largest value

Based on the above suggestions, the following data.table solution worked very fast for me:

library(data.table)

set.seed(45)
DT <- data.table(matrix(sample(10, 10^7, TRUE), ncol=10))

system.time(
  DT[, col_max := colnames(.SD)[max.col(.SD, ties.method = "first")]]
)
#>    user  system elapsed 
#>    0.15    0.06    0.21
DT[]
#>          V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 col_max
#>       1:  7  4  1  2  3  7  6  6  6   1      V1
#>       2:  4  6  9 10  6  2  7  7  1   3      V4
#>       3:  3  4  9  8  9  9  8  8  6   7      V3
#>       4:  4  8  8  9  7  5  9  2  7   1      V4
#>       5:  4  3  9 10  2  7  9  6  6   9      V4
#>      ---                                       
#>  999996:  4  6 10  5  4  7  3  8  2   8      V3
#>  999997:  8  7  6  6  3 10  2  3 10   1      V6
#>  999998:  2  3  2  7  4  7  5  2  7   3      V4
#>  999999:  8 10  3  2  3  4  5  1  1   4      V2
#> 1000000: 10  4  2  6  6  2  8  4  7   4      V1

And also comes with the advantage that can always specify what columns .SD should consider by mentioning them in .SDcols:

DT[, MAX2 := colnames(.SD)[max.col(.SD, ties.method="first")], .SDcols = c("V9", "V10")]

In case we need the column name of the smallest value, as suggested by @lwshang, one just needs to use -.SD:

DT[, col_min := colnames(.SD)[max.col(-.SD, ties.method = "first")]]

How to solve SyntaxError on autogenerated manage.py?

Also, the tutorial recommends that a virtual environment is used (see Django documentation: https://docs.djangoproject.com/en/2.0/topics/install/#installing-official-release"). You can do this with pipenv --three. Once you've installed django with pipenv install django and activated your virtual environment with pipenv shell, python will refer to python3 when executing python manage.py runserver.

Pipenv documentation: https://pipenv.kennethreitz.org/

ORA-00907: missing right parenthesis

Albeit from the useless _T and incorrectly spelled histories. If you are using SQL*Plus, it does not accept create table statements with empty new lines between create table <name> ( and column definitions.

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

Install Qt on Ubuntu

The ubuntu package name is qt5-default, not qt.

Printing Even and Odd using two Threads in Java

Simple Solution below:-

package com.test;

class MyThread implements Runnable{

    @Override
    public void run() {
        int i=1;
        while(true) {
            String name=Thread.currentThread().getName();
            if(name.equals("task1") && i%2!=0) {
                System.out.println(name+"::::"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else if(name.equals("task2") && i%2==0){
                System.out.println(name+"::::"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            i++;
        }

    }

    public static void main(String[] args) {

        MyThread task1=new MyThread();
        MyThread task2=new MyThread();

        Thread t1=new Thread(task1,"task1");
        Thread t2=new Thread(task2,"task2");

        t1.start();
        t2.start();

    }

}

Show datalist labels but submit the actual value

Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.

Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.

If you want to disallow user input entirely, maybe select would be a better choice.


To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:

To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.

<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
    <option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.

document.querySelector('input[list]').addEventListener('input', function(e) {
    var input = e.target,
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
        inputValue = input.value;

    hiddenInput.value = inputValue;

    for(var i = 0; i < options.length; i++) {
        var option = options[i];

        if(option.innerText === inputValue) {
            hiddenInput.value = option.getAttribute('data-value');
            break;
        }
    }
});

The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.

Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""


Working jsFiddle examples: plain javascript and jQuery

adb shell command to make Android package uninstall dialog appear

While the above answers work but in case you have multiple devices connected to your computer then the following command can be used to remove the app from one of them:

adb -s <device-serial> shell pm uninstall <app-package-name>

If you want to find out the device serial then use the following command:

adb devices -l

This will give you a list of devices attached. The left column shows the device serials.

Adding a favicon to a static HTML page

Note that FF fails to load an icon with a redundant // in URL like /img//favicon.png. Tested on FF 53. Chrome is OK.

How to set $_GET variable

$_GET contains the keys / values that are passed to your script in the URL.

If you have the following URL :

http://www.example.com/test.php?a=10&b=plop

Then $_GET will contain :

array
  'a' => string '10' (length=2)
  'b' => string 'plop' (length=4)


Of course, as $_GET is not read-only, you could also set some values from your PHP code, if needed :

$_GET['my_value'] = 'test';

But this doesn't seem like good practice, as $_GET is supposed to contain data from the URL requested by the client.

How to install requests module in Python 3.4, instead of 2.7

Just answering this old thread can be installed without pip On windows or Linux:

1) Download Requests from https://github.com/kennethreitz/requests click on clone or download button

2) Unzip the files in your python directory .Exp your python is installed in C:Python\Python.exe then unzip there

3) Depending on the Os run the following command:

  • Windows use command cd to your python directory location then setup.py install
  • Linux command: python setup.py install

Thats it :)

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

Cannot get to $rootScope

I've found the following "pattern" to be very useful:

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
function MainCtrl (scope, rootscope, location, thesocket, ...) {

where, MainCtrl is a controller. I am uncomfortable relying on the parameter names of the Controller function doing a one-for-one mimic of the instances for fear that I might change names and muck things up. I much prefer explicitly using $inject for this purpose.

jQuery hide and show toggle div with plus and minus icon

Try something like this

jQuery

$('#toggle_icon').toggle(function() {

    $('#toggle_icon').text('-');
    $('#toggle_text').slideToggle();

}, function() {

    $('#toggle_icon').text('+');
    $('#toggle_text').slideToggle();

});

HTML

<a href="#" id="toggle_icon">+</a>

<div id="toggle_text" style="display: none">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>

DEMO

The program can't start because libgcc_s_dw2-1.dll is missing

If you are wondering where you can download the shared library (although this will not work on your client's devices unless you include the dll) here is the link: https://de.osdn.net/projects/mingw/downloads/72215/libgcc-9.2.0-1-mingw32-dll-1.tar.xz/

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

PHP MySQL Query Where x = $variable

What you are doing right now is you are adding . on the string and not concatenating. It should be,

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");

or simply

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '$email'");

pthread_join() and pthread_exit()

In pthread_exit, ret is an input parameter. You are simply passing the address of a variable to the function.

In pthread_join, ret is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL.

Long explanation:

In pthread_join, you get back the address passed to pthread_exit by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.

Accessing last x characters of a string in Bash

Another workaround is to use grep -o with a little regex magic to get three chars followed by the end of line:

$ foo=1234567890
$ echo $foo | grep -o ...$
890

To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep with this regex:

$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd

You can also use different ranges, such as 5,10 to get the last five to ten chars.

SASS - use variables across multiple files

How about writing some color-based class in a global sass file, thus we don't need to care where variables are. Just like the following:

// base.scss 
@import "./_variables.scss";

.background-color{
    background: $bg-color;
}

and then, we can use the background-color class in any file. My point is that I don't need to import variable.scss in any file, just use it.

React - Display loading screen while DOM is rendering?

Setting the timeout in componentDidMount works but in my application I received a memory leak warning. Try something like this.

constructor(props) {
    super(props)
    this.state = { 
      loading: true,
    }
  }
  componentDidMount() {
    this.timerHandle = setTimeout(() => this.setState({ loading: false }), 3500); 
  }

  componentWillUnmount(){
    if (this.timerHandle) {
      clearTimeout(this.timerHandle);
      this.timerHandle = 0;
    }
  }

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

If you are building DEBUG APK, just add:

debug {
            multiDexEnabled true
        }

inside buildTypes

and if you are building RELEASE APK, add multiDexEnabled true in release block as-

release {
                ...
                multiDexEnabled true
                ...
        }

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

Using Postman to access OAuth 2.0 Google APIs

This is an old question, but it has no chosen answer, and I just solved this problem myself. Here's my solution:

  1. Make sure you are set up to work with your Google API in the first place. See Google's list of prerequisites. I was working with Google My Business, so I also went through it's Get Started process.

  2. In the OAuth 2.0 playground, Step 1 requires you to select which API you want to authenticate. Select or input as applicable for your case (in my case for Google My Business, I had to input https://www.googleapis.com/auth/plus.business.manage into the "Input your own scopes" input field). Note: this is the same as what's described in step 6 of the "Make a simple HTTP request" section of the Get Started guide.

  3. Assuming successful authentication, you should get an "Access token" returned in the "Step 1's result" step in the OAuth playground. Copy this token to your clipboard.

  4. Open Postman and open whichever collection you want as necessary.

  5. In Postman, make sure "GET" is selected as the request type, and click on the "Authorization" tab below the request type drop-down.

  6. In the Authorization "TYPE" dropdown menu, select "Bearer Token"

  7. Paste your previously copied "Access Token" which you copied from the OAuth playground into the "Token" field which displays in Postman.

  8. Almost there! To test if things work, put https://mybusiness.googleapis.com/v4/accounts/ into the main URL input bar in Postman and click the send button. You should get a JSON list of accounts back in the response that looks something like the following:

    
    {
        "accounts": [
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "PERSONAL",
                "state": {
                    "status": "UNVERIFIED"
                }
            },
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "LOCATION_GROUP",
                "role": "OWNER",
                "state": {
                    "status": "UNVERIFIED"
                },
                "permissionLevel": "OWNER_LEVEL"
            }
        ]
    }
    

Get first day of week in SQL Server

Maybe I'm over simplifying here, and that may be the case, but this seems to work for me. Haven't ran into any problems with it yet...

CAST('1/1/' + CAST(YEAR(GETDATE()) AS VARCHAR(30)) AS DATETIME) + (DATEPART(wk, YOUR_DATE) * 7 - 7) as 'FirstDayOfWeek'
CAST('1/1/' + CAST(YEAR(GETDATE()) AS VARCHAR(30)) AS DATETIME) + (DATEPART(wk, YOUR_DATE) * 7) as 'LastDayOfWeek'

Combining "LIKE" and "IN" for SQL Server

Effectively, the IN statement creates a series of OR statements... so

SELECT * FROM table WHERE column IN (1, 2, 3)

Is effectively

SELECT * FROM table WHERE column = 1 OR column = 2 OR column = 3

And sadly, that is the route you'll have to take with your LIKE statements

SELECT * FROM table
WHERE column LIKE 'Text%' OR column LIKE 'Hello%' OR column LIKE 'That%'

Remove scroll bar track from ScrollView in Android

Solved my problem by adding this to my ListView:

android:scrollbars="none"

Quick Way to Implement Dictionary in C

For ease of implementation, it's hard to beat naively searching through an array. Aside from some error checking, this is a complete implementation (untested).

typedef struct dict_entry_s {
    const char *key;
    int value;
} dict_entry_s;

typedef struct dict_s {
    int len;
    int cap;
    dict_entry_s *entry;
} dict_s, *dict_t;

int dict_find_index(dict_t dict, const char *key) {
    for (int i = 0; i < dict->len; i++) {
        if (!strcmp(dict->entry[i], key)) {
            return i;
        }
    }
    return -1;
}

int dict_find(dict_t dict, const char *key, int def) {
    int idx = dict_find_index(dict, key);
    return idx == -1 ? def : dict->entry[idx].value;
}

void dict_add(dict_t dict, const char *key, int value) {
   int idx = dict_find_index(dict, key);
   if (idx != -1) {
       dict->entry[idx].value = value;
       return;
   }
   if (dict->len == dict->cap) {
       dict->cap *= 2;
       dict->entry = realloc(dict->entry, dict->cap * sizeof(dict_entry_s));
   }
   dict->entry[dict->len].key = strdup(key);
   dict->entry[dict->len].value = value;
   dict->len++;
}

dict_t dict_new(void) {
    dict_s proto = {0, 10, malloc(10 * sizeof(dict_entry_s))};
    dict_t d = malloc(sizeof(dict_s));
    *d = proto;
    return d;
}

void dict_free(dict_t dict) {
    for (int i = 0; i < dict->len; i++) {
        free(dict->entry[i].key);
    }
    free(dict->entry);
    free(dict);
}

Github: error cloning my private repository

The solution that work for me in windows 64bits is the following

git config --system http.sslverify false

JQuery: Change value of hidden input field

It's simple as:

$('#action').val("1");

#action is hidden input field id.

How to collapse blocks of code in Eclipse?

For Python it is as follows:

  • collapse all 1 level: Ctrl+9
  • expand all 1 level: Ctrl+0
  • collapse current: Ctrl+-
  • expand current: Ctrl++

Hope that helps.

-bash: export: `=': not a valid identifier

I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.

Scenario 1: There cannot be spaces beside the = (equals) sign

$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question

$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier

$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier

Scenario 2: Object value assignment should not have spaces besides quotes

$ export TEMP_ENV={ "key" : "json example" } 
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier

Scenario 3: List value assignment should not have spaces between values

$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier

I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

$("#text").val(function(i,v) { 
   return v.replace(".", ":"); 
});

TABLOCK vs TABLOCKX

Quite an old article on mssqlcity attempts to explain the types of locks:

Shared locks are used for operations that do not change or update data, such as a SELECT statement.

Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.

Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).


The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.

Naming conventions for Java methods that return boolean

If you wish your class to be compatible with the Java Beans specification, so that tools utilizing reflection (e.g. JavaBuilders, JGoodies Binding) can recognize boolean getters, either use getXXXX() or isXXXX() as a method name. From the Java Beans spec:

8.3.2 Boolean properties

In addition, for boolean properties, we allow a getter method to match the pattern:

public boolean is<PropertyName>();

This “is<PropertyName>” method may be provided instead of a “get<PropertyName>” method, or it may be provided in addition to a “get<PropertyName>” method. In either case, if the “is<PropertyName>” method is present for a boolean property then we will use the “is<PropertyName>” method to read the property value. An example boolean property might be:

public boolean isMarsupial();
public void setMarsupial(boolean m);

How do I use floating-point division in bash?

here is awk command: -F = field separator == +

echo "2.1+3.1" |  awk -F "+" '{print ($1+$2)}'

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

Linq to SQL .Sum() without group ... into

I know this is an old question but why can't you do it like:

db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);

I am not sure how to do this using query expressions.

Convert JSON array to an HTML table in jQuery

Using jQuery will make this simpler.

The following code will take an array of arrays and store convert them into rows and cells.

$.getJSON(url , function(data) {
    var tbl_body = "";
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = "";
        $.each(this, function(k , v) {
            tbl_row += "<td>"+v+"</td>";
        });
        tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
        odd_even = !odd_even;               
    });
    $("#target_table_id tbody").html(tbl_body);
});

You could add a check for the keys you want to exclude by adding something like

var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };

at the start of the getJSON callback function and adding:

if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}

around the tbl_row += line.

Edit: Was assigning a null variable previously

Edit: Version based on Timmmm's injection-free contribution.

$.getJSON(url , function(data) {
    var tbl_body = document.createElement("tbody");
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = tbl_body.insertRow();
        tbl_row.className = odd_even ? "odd" : "even";
        $.each(this, function(k , v) {
            var cell = tbl_row.insertCell();
            cell.appendChild(document.createTextNode(v.toString()));
        });        
        odd_even = !odd_even;               
    });
    $("#target_table_id").append(tbl_body);   //DOM table doesn't have .appendChild
});

Android Calling JavaScript functions in WebView

public void run(final String scriptSrc) { 
        webView.post(new Runnable() {
            @Override
            public void run() { 
                webView.loadUrl("javascript:" + scriptSrc); 
            }
        }); 
    }

How to call Android contacts list?

To my surprise you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time). However you do need permission to read the details of the contact like phone number.

How can we stop a running java process through Windows cmd?

start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar

start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar --stop

Enable PHP Apache2

If anyone gets

ERROR: Module phpX.X does not exist!

just install the module for your current php version:

apt-get install libapache2-mod-phpX.X

How to hide the Google Invisible reCAPTCHA badge

I saw next comment about this

It's also helpful to place the badge inline if you want to apply your own CSS to it. But do remember that you agreed to show Google's Terms and conditions when you registered for an API key - so don't hide it, please. And while it is possible to make the badge disappear completely with CSS, we wouldn't recommend it.

Bootstrap 3 Navbar with Logo

You must use code as this:

<div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" 
            data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="logo" rel="home" href="#" title="Buy Sell Rent Everyting">
        <img style=""
             src="/img/transparent-white-logo.png">
    </a>
</div>

Class of A tag must be "logo" not navbar-brand.

How to lay out Views in RelativeLayout programmatically?

If you really want to layout manually, i'd suggest not to use a standard layout at all. Do it all on your own, here a kotlin example:

class ProgrammaticalLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ViewGroup(context, attrs, defStyleAttr) { 
    private val firstTextView = TextView(context).apply {
        test = "First Text"
    }

    private val secondTextView = TextView(context).apply {
        text = "Second Text"
    }

    init {
        addView(firstTextView)
        addView(secondTextView)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        // center the views verticaly and horizontaly
        val firstTextLeft = (measuredWidth - firstTextView.measuredWidth) / 2
        val firstTextTop = (measuredHeight - (firstTextView.measuredHeight + secondTextView.measuredHeight)) / 2
        firstTextView.layout(firstTextLeft,firstTextTop, firstTextLeft + firstTextView.measuredWidth,firstTextTop + firstTextView.measuredHeight)

        val secondTextLeft = (measuredWidth - secondTextView.measuredWidth) / 2
        val secondTextTop = firstTextView.bottom
        secondTextView.layout(secondTextLeft,secondTextTop, secondTextLeft + secondTextView.measuredWidth,secondTextTop + secondTextView.measuredHeight)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { 
        // just assume we`re getting measured exactly by the parent
        val measuredWidth = MeasureSpec.getSize(widthMeasureSpec)
        val measuredHeight = MeasureSpec.getSize(heightMeasureSpec)

        firstTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
        secondTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))

        setMeasuredDimension(measuredWidth, measuredHeight)
    }
}

This might give you an idea how this could work

List of enum values in java

You can simply write

new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));

Git: How to update/checkout a single file from remote origin master?

Or git stash (if you have changes) on the branch you're on, checkout master, pull for the latest changes, grab that file to your desktop (or the entire app). Checkout the branch you were on. Git stash apply back to the state you were at, then fix the changes manually or drag it replacing the file.

This way is not sooooo cool but it def works if you guys can't figure anything else out.

Passing parameters to a JQuery function

If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false

like this:

function DoAction(id, name) 
{ 
    // your code
    return false;
}

How to capitalize the first letter of word in a string using Java?

You can try the following code:

public string capitalize(str) {
    String[] array = str.split(" ");
    String newStr;
    for(int i = 0; i < array.length; i++) {
        newStr += array[i].substring(0,1).toUpperCase() + array[i].substring(1) + " ";
    }
    return newStr.trim();
}

Accessing value inside nested dictionaries

My implementation:

def get_nested(data, *args):
    if args and data:
        element  = args[0]
        if element:
            value = data.get(element)
            return value if len(args) == 1 else get_nested(value, *args[1:])

Example usage:

>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>

There are no exceptions raised in case a key is missing, None value is returned in that case.

Reading images in python

You can also use Pillow like this:

from PIL import Image
image = Image.open("image_path.jpg")
image.show()

Left-pad printf with spaces

int space = 40;
printf("%*s", space, "Hello");

This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40). Same can be used for characters and integers as follows:

printf("%*d", space, 10);
printf("%*c", space, 'x');

This method using a parameter to determine spaces is useful where a variable number of spaces is required. These statements will still work with integer literals as follows:

printf("%*d", 10, 10);
printf("%*c", 20, 'x');
printf("%*s", 30, "Hello");

Hope this helps someone like me in future.

How do I run Visual Studio as an administrator by default?

@Kumar

"W7 prompts everytime to run this program "devenv.exe" , anyway to get rid of that ?"

Yes. You can prevent Windows from prompting you by going to Control Panel/User Accounts/Change User Account Control settings and move the slider down.

Make HTML5 video poster be same size as video itself

You can resize image size after generating thumb

exec("ffmpeg -i $video_image_dir/out.png -vf scale=320:240 {$video_image_dir}/resize.png",$out2, $return2);

How can I set a DateTimePicker control to a specific date?

Also, we can assign the Value to the Control in Designer Class (i.e. FormName.Designer.cs).

DateTimePicker1.Value = DateTime.Now;

This way you always get Current Date...

How do you append rows to a table using jQuery?

I'm assuming you want to add this row to the <tbody> element, and simply using append() on the <table> will insert the <tr> outside the <tbody>, with perhaps undesirable results.

$('a').click(function() {
   $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});

EDIT: Here is the complete source code, and it does indeed work: (Note the $(document).ready(function(){});, which was not present before.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('a').click(function() {
       $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
    });
});
</script>
<title></title>
</head>
<body>
<a href="javascript:void(0);">Link</a>
<table id="myTable">
  <tbody>
    <tr>
      <td>test</td>
    </tr>
  </tbody>
</table>
</body>
</html>

How and where are Annotations used in Java?

It attaches additional information about code by (a) compiler check or (b) code analysis

**

  • Following are the Built-in annotations:: 2 types

**

Type 1) Annotations applied to java code:

@Override // gives error if signature is wrong while overriding.
Public boolean equals (Object Obj) 

@Deprecated // indicates the deprecated method
Public doSomething()....

@SuppressWarnings() // stops the warnings from printing while compiling.
SuppressWarnings({"unchecked","fallthrough"})

Type 2) Annotations applied to other annotations:

@Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at run-time through reflection.

@Documented - Marks another annotation for inclusion in the documentation.

@Target - Marks another annotation to restrict what kind of java elements the annotation may be applied to

@Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).

**

  • Custom Annotations::

** http://en.wikipedia.org/wiki/Java_annotation#Custom_annotations


FOR BETTER UNDERSTANDING TRY BELOW LINK:ELABORATE WITH EXAMPLES


http://www.javabeat.net/2007/08/annotations-in-java-5-0/

How to read data of an Excel file using C#?

Use OLEDB Connection to communicate with excel files. it gives better result

using System.Data.OleDb;



                string physicalPath = "Your Excel file physical path";
                OleDbCommand cmd = new OleDbCommand();
                OleDbDataAdapter da = new OleDbDataAdapter();
                DataSet ds = new DataSet();
                String strNewPath = physicalPath;
                String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                String query = "SELECT * FROM [Sheet1$]"; // You can use any different queries to get the data from the excel sheet
                OleDbConnection conn = new OleDbConnection(connString);
                if (conn.State == ConnectionState.Closed) conn.Open();
                try
                {
                    cmd = new OleDbCommand(query, conn);
                    da = new OleDbDataAdapter(cmd);
                    da.Fill(ds);

                }
                catch
                {
                    // Exception Msg 

                }
                finally
                {
                    da.Dispose();
                    conn.Close();
                }

The Output data will be stored in dataset, using the dataset object you can easily access the datas. Hope this may helpful

jQuery events .load(), .ready(), .unload()

NOTE: .load() & .unload() have been deprecated


$(window).load();

Will execute after the page along with all its contents are done loading. This means that all images, CSS (and content defined by CSS like custom fonts and images), scripts, etc. are all loaded. This happens event fires when your browser's "Stop" -icon becomes gray, so to speak. This is very useful to detect when the document along with all its contents are loaded.

$(document).ready();

This on the other hand will fire as soon as the web browser is capable of running your JavaScript, which happens after the parser is done with the DOM. This is useful if you want to execute JavaScript as soon as possible.

$(window).unload();

This event will be fired when you are navigating off the page. That could be Refresh/F5, pressing the previous page button, navigating to another website or closing the entire tab/window.

To sum up, ready() will be fired before load(), and unload() will be the last to be fired.

SQL Server SELECT LAST N Rows

Is "Id" indexed? If not, that's an important thing to do (I suspect it is already indexed).

Also, do you need to return ALL columns? You may be able to get a substantial improvement in speed if you only actually need a smaller subset of columns which can be FULLY catered for by the index on the ID column - e.g. if you have a NONCLUSTERED index on the Id column, with no other fields included in the index, then it would have to do a lookup on the clustered index to actually get the rest of the columns to return and that could be making up a lot of the cost of the query. If it's a CLUSTERED index, or a NONCLUSTERED index that includes all the other fields you want to return in the query, then you should be fine.

'namespace' but is used like a 'type'

if the error is

Line 26:
Line 27: @foreach (Customers customer in Model) Line 28: { Line 29:

give the full name space
like @foreach (Start.Models.customer customer in Model)

Find the number of employees in each department - SQL Oracle

Try the query below:

select count(*),d.dname from emp e , dept d where d.deptno = e.deptno
group by d.dname

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

Setting environment variables in Linux using Bash

Set a local and environment variable using Bash on Linux

Check for a local or environment variables for a variable called LOL in Bash:

el@server /home/el $ set | grep LOL
el@server /home/el $
el@server /home/el $ env | grep LOL
el@server /home/el $

Sanity check, no local or environment variable called LOL.

Set a local variable called LOL in local, but not environment. So set it:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ env | grep LOL
el@server /home/el $

Variable 'LOL' exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run exec bash.

Set a local variable, and then clear out all local variables in Bash

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ exec bash
el@server /home/el $ set | grep LOL
el@server /home/el $

You could also just unset the one variable:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ unset LOL
el@server /home/el $ set | grep LOL
el@server /home/el $

Local variable LOL is gone.

Promote a local variable to an environment variable:

el@server /home/el $ DOGE="such variable"
el@server /home/el $ export DOGE
el@server /home/el $ set | grep DOGE
DOGE='such variable'
el@server /home/el $ env | grep DOGE
DOGE=such variable

Note that exporting makes it show up as both a local variable and an environment variable.

Exported variable DOGE above survives a Bash reset:

el@server /home/el $ exec bash
el@server /home/el $ env | grep DOGE
DOGE=such variable
el@server /home/el $ set | grep DOGE
DOGE='such variable'

Unset all environment variables:

You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:

el@server /home/el $ export CAN="chuck norris"
el@server /home/el $ env | grep CAN
CAN=chuck norris
el@server /home/el $ set | grep CAN
CAN='chuck norris'
el@server /home/el $ env -i bash
el@server /home/el $ set | grep CAN
el@server /home/el $ env | grep CAN

You created an environment variable, and then reset the terminal to get rid of them.

Or you could set and unset an environment variable manually like this:

el@server /home/el $ export FOO="bar"
el@server /home/el $ env | grep FOO
FOO=bar
el@server /home/el $ unset FOO
el@server /home/el $ env | grep FOO
el@server /home/el $

Installing SciPy and NumPy using pip

Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"

sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy

Java: how to add image to Jlabel?

You have to supply to the JLabel an Icon implementation (i.e ImageIcon). You can do it trough the setIcon method, as in your question, or through the JLabel constructor:

Image image=GenerateImage.toImage(true);  //this generates an image file
ImageIcon icon = new ImageIcon(image); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

I recommend you to read the Javadoc for JLabel, Icon, and ImageIcon. Also, you can check the How to Use Labels Tutorial, for more information.

View's SELECT contains a subquery in the FROM clause

As per documentation:

MySQL Docs

  • The SELECT statement cannot contain a subquery in the FROM clause.

Your workaround would be to create a view for each of your subqueries.

Then access those views from within your view view_credit_status

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case I had two issues...

1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"

enter image description here

2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

enter image description here

jQuery DataTable overflow and text-wrapping issues

You can try setting the word-wrap however it doesn't work in all browsers yet.

Another method would be to add an element around your cell data like this:

<td><span>...</span></td>

Then add some css like this:

.datatable td span{
    max-width: 400px;
    display: block;
    overflow: hidden;
}

Android - How to regenerate R class?

I had that problem and I just right-clicked on packet of my project and Build Project. Instantly the class R appeared in packet gen.

remove double quotes from Json return data using Jquery

You can simple try String(); to remove the quotes.

Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp

Thank me later.

PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.

How can I use getSystemService in a non-activity class (LocationManager)?

You can go for this :

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

Removing empty rows of a data file in R

If you have empty rows, not NAs, you can do:

data[!apply(data == "", 1, all),]

To remove both (NAs and empty):

data <- data[!apply(is.na(data) | data == "", 1, all),]

Find size and free space of the filesystem containing a given file

The simplest way to find out it.

import os
from collections import namedtuple

DiskUsage = namedtuple('DiskUsage', 'total used free')

def disk_usage(path):
    """Return disk usage statistics about the given path.

    Will return the namedtuple with attributes: 'total', 'used' and 'free',
    which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return DiskUsage(total, used, free)

PYTHONPATH vs. sys.path

I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set sys.path in the invoke scripts for standalone projects.

However sys.path.append isn't the way to do it. You can easily get duplicates, and it doesn't sort out .pth files. Better (and more readable): site.addsitedir.

And script.py wouldn't normally be the more appropriate place to do it, as it's inside the package you want to make available on the path. Library modules should certainly not be touching sys.path themselves. Instead, you'd normally have a hashbanged-script outside the package that you use to instantiate and run the app, and it's in this trivial wrapper script you'd put deployment details like sys.path-frobbing.

How to Set Active Tab in jQuery Ui

If you want to set the active tab by ID instead of index, you can also use the following:

$('#tabs').tabs({ active: $('#tabs ul').index($('#tab-101')) });

Two values from one input in python?

a,b=[int(x) for x in input().split()]
print(a,b)

Output

10 8

10 8

How to delete or change directory of a cloned git repository on a local computer

You can just delete that directory that you cloned the repo into, and re-clone it wherever you'd like.

SVN Repository Search

Update January, 2020

VisualSVN Server 4.2 supports finding files and folders in the web interface. Try out the new feature on one of the demo server’s repositories!

See the version 4.2 Release Notes, and download VisualSVN Server 4.2.0 from the main download page.

enter image description here


Old answer

Beginning with Subversion 1.8, you can use --search option with svn log command. Note that the command does not perform full-text search inside a repository, it considers the following data only:

  • revision's author (svn:author unversioned property),
  • date (svn:date unversioned property),
  • log message text (svn:log unversioned property),
  • list of changed paths (i.e. paths affected by the particular revision).

Here is the help page about these new search options:

 If the --search option is used, log messages are displayed only if the
 provided search pattern matches any of the author, date, log message
 text (unless --quiet is used), or, if the --verbose option is also
 provided, a changed path.
 The search pattern may include "glob syntax" wildcards:
     ?      matches any single character
     *      matches a sequence of arbitrary characters
     [abc]  matches any of the characters listed inside the brackets
 If multiple --search options are provided, a log message is shown if
 it matches any of the provided search patterns. If the --search-and
 option is used, that option's argument is combined with the pattern
 from the previous --search or --search-and option, and a log message
 is shown only if it matches the combined search pattern.
 If --limit is used in combination with --search, --limit restricts the
 number of log messages searched, rather than restricting the output
 to a particular number of matching log messages.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

Wrong port number in my case. Check if port number when starting Selenium server is the same as in your script.

Create session factory in Hibernate 4

The method buildSessionFactory is deprecated from the Hibernate 4 release and it is replaced with the new API. If you are using the Hibernate 4.3.0 and above, your code has to be:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

What are C++ functors and their uses?

A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function:

// this is a functor
struct add_x {
  add_x(int val) : x(val) {}  // Constructor
  int operator()(int y) const { return x + y; }

private:
  int x;
};

// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument

std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element 
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1)); 
assert(out[i] == in[i] + 1); // for all i

There are a couple of nice things about functors. One is that unlike regular functions, they can contain state. The above example creates a function which adds 42 to whatever you give it. But that value 42 is not hardcoded, it was specified as a constructor argument when we created our functor instance. I could create another adder, which added 27, just by calling the constructor with a different value. This makes them nicely customizable.

As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function std::transform should call. It should call add_x::operator(). That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.

If I had passed a function pointer instead, the compiler couldn't immediately see which function it points to, so unless it performs some fairly complex global optimizations, it'd have to dereference the pointer at runtime, and then make the call.

How to determine if a string is a number with C++?

I think this regular expression should handle almost all cases

"^(\\-|\\+)?[0-9]*(\\.[0-9]+)?"

so you can try the following function that can work with both (Unicode and ANSI)

bool IsNumber(CString Cs){
Cs.Trim();

#ifdef _UNICODE
std::wstring sr = (LPCWSTR)Cs.GetBuffer(Cs.GetLength());
return std::regex_match(sr, std::wregex(_T("^(\\-|\\+)?[0-9]*(\\.[0-9]+)?")));

#else
    std::string s = (LPCSTR)Cs.GetBuffer();
return std::regex_match(s, std::regex("^(\\-|\\+)?[0-9]*(\\.[0-9]+)?"));
#endif
}

Protractor : How to wait for page complete after click a button?

You don't need to wait. Protractor automatically waits for angular to be ready and then it executes the next step in the control flow.

How to make a <div> appear in front of regular text/tables

You can use the stacking index of the div to make it appear on top of anything else. Make it a larger value that other elements and it well be on top of others.

use z-index property. See Specifying the stack level: the 'z-index' property and

Elaborate description of Stacking Contexts

Something like

#divOnTop { z-index: 1000; }

<div id="divOnTop">I am on top</div>

What you have to look out for will be IE6. In IE 6 some elements like <select> will be placed on top of an element with z-index value higher than the <select>. You can have a workaround for this by placing an <iframe> behind the div.

See this Internet Explorer z-index bug?

Java Equivalent of C# async/await?

There isn't anything native to java that lets you do this like async/await keywords, but what you can do if you really want to is use a CountDownLatch. You could then imitate async/await by passing this around (at least in Java7). This is a common practice in Android unit testing where we have to make an async call (usually a runnable posted by a handler), and then await for the result (count down).

Using this however inside your application as opposed to your test is NOT what I am recommending. That would be extremely shoddy as CountDownLatch depends on you effectively counting down the right number of times and in the right places.

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

datatable jquery - table header width not aligned with body width

Found the solution :

Added table-layout:fixed to the table. And opened the application in IE mode.

JavaScript before leaving the page

In order to have a popop with Chrome 14+, you need to do the following :

jQuery(window).bind('beforeunload', function(){
    return 'my text';
});

The user will be asked if he want to stay or leave.

How do I prompt a user for confirmation in bash script?

use case/esac.

read -p "Continue (y/n)?" choice
case "$choice" in 
  y|Y ) echo "yes";;
  n|N ) echo "no";;
  * ) echo "invalid";;
esac

advantage:

  1. neater
  2. can use "OR" condition easier
  3. can use character range, eg [yY][eE][sS] to accept word "yes", where any of its characters may be in lowercase or in uppercase.

Android Paint: .measureText() vs .getTextBounds()

My experience with this is that getTextBounds will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText assumes one line.

In order to get accurate measuring results, you should use the StaticLayout to render the text and pull out the measurements.

For example:

String text = "text";
TextPaint textPaint = textView.getPaint();
int boundedWidth = 1000;

StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int height = layout.getHeight();

How to round up integer division and have int result in Java?

Another one-liner that is not too complicated:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

Could use long instead of int; just change the parameter types and return type.

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _dap.Fill(tblEmployees);
}

YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

Identify duplicate values in a list in Python

m = len(mylist)
for index,value in enumerate(mylist):
        for i in xrange(1,m):
                if(index != i):
                    if (L[i] == L[index]):
                        print "Location %d and location %d has same list-entry:  %r" % (index,i,value)

This has some redundancy that can be improved however.

How to redraw DataTable with new data

Another alternative is

dtColumns[index].visible = false/true;

To show or hide any column.

Javascript set img src

Pure JavaScript to Create img tag and add attributes manually ,

var image = document.createElement("img");
var imageParent = document.getElementById("body");
image.id = "id";
image.className = "class";
image.src = searchPic.src;            // image.src = "IMAGE URL/PATH"
imageParent.appendChild(image);

Set src in pic1

document["#pic1"].src = searchPic.src;

or with getElementById

document.getElementById("pic1").src= searchPic.src;

j-Query to archive this,

$("#pic1").attr("src", searchPic.src);

Subtract two variables in Bash

Alternatively to the suggested 3 methods you can try let which carries out arithmetic operations on variables as follows:

let COUNT=$FIRSTV-$SECONDV

or

let COUNT=FIRSTV-SECONDV