Programs & Examples On #Mediarss

Viewing contents of a .jar file

Jad is klunky and no longer maintained. I've switched to "Java Decompiler", which has a slick UI and support for new language features.

Every decompiler I've used, though, runs into code it doesn't successfully decompile. For those, it helps to understand the disassembled Java byte code produced by the standard JDK tool, javap.

What is the standard exception to throw in Java for not supported/implemented operations?

Differentiate between the two cases you named:

How to add google-services.json in Android?

Instead of putting in root folder as given in docs of firebase, just copy the google-json file in the projectname/app 's root folder and it works fine then . Its just simple !

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.Append(......);

    StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
    sw.Write(sb.ToString());
    sw.Close();

Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.

git: can't push (unpacker error) related to permission issues

Where I work we have been using this method on all of our repositories for a few years without any problems (except when we create a new repository and forget to set it up this way):

  1. Set 'sharedRepository = true' in the config file's '[core]' section.
  2. Change the group id of the repository to a group shared by all users who are allowed to push to it:

    chgrp -R shared_group /git/our_repos
    chmod -R g+w /git/our_repos
    
  3. Set the setgid bit on all directories in the repository so that new files/directories keep the same group:

    find /git/our_repos -type d -exec chmod g+s {} +
    
  4. Add this line to the pre-receive hook in the repository to ensure new file permissions allow group read/write:

    umask 007
    

C++ Fatal Error LNK1120: 1 unresolved externals

My problem was int Main() instead of int main()

good luck

CodeIgniter - File upload required validation

you can use call back function, like this

  $this->form_validation->set_rules('userfile', 'Document', 'callback_file_selected_test');

    if ($this->form_validation->run() == FALSE) {
         //error
     }
    else{
           // success       
      }

function file_selected_test(){

    $this->form_validation->set_message('file_selected_test', 'Please select file.');
    if (empty($_FILES['userfile']['name'])) {
            return false;
        }else{
            return true;
        }
}

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

What is the purpose of global.asax in asp.net

MSDN has an outline of the purpose of the global.asax file.

Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):

  • Application_Start
  • Application_End
  • Session_Start
  • Session_End
  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_Error

There are other events that you can also hook into, such as "LogRequest".

How to add image in Flutter

How to include images in your app

1. Create an assets/images folder

  • This should be located in the root of your project, in the same folder as your pubspec.yaml file.
  • In Android Studio you can right click in the Project view
  • You don't have to call it assets or images. You don't even need to make images a subfolder. Whatever name you use, though, is what you will regester in the pubspec.yaml file.

2. Add your image to the new folder

  • You can just copy your image into assets/images. The relative path of lake.jpg, for example, would be assets/images/lake.jpg.

3. Register the assets folder in pubspec.yaml

  • Open the pubspec.yaml file that is in the root of your project.

  • Add an assets subsection to the flutter section like this:

      flutter:
        assets:
          - assets/images/lake.jpg
    
  • If you have multiple images that you want to include then you can leave off the file name and just use the directory name (include the final /):

      flutter:
        assets:
          - assets/images/
    

4. Use the image in code

  • Get the asset in an Image widget with Image.asset('assets/images/lake.jpg').

  • The entire main.dart file is here:

      import 'package:flutter/material.dart';
    
      void main() => runApp(MyApp());
    
      class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            home: Scaffold(
              appBar: AppBar(
                title: Text("Image from assets"),
              ),
              body: Image.asset('assets/images/lake.jpg'), //   <--- image
            ),
          );
        }
      }
    

5. Restart your app

When making changes to pubspec.yaml I find that I often need to completely stop my app and restart it again, especially when adding assets. Otherwise I get a crash.

Running the app now you should have something like this:

enter image description here

Further reading

  • See the documentation for how to do things like provide alternate images for different densities.

Videos

The first video here goes into a lot of detail about how to include images in your app. The second video covers more about how to adjust how they look.

How can I start an Activity from a non-Activity class?

Your onTap override receives the MapView from which you can obtain the Context:

@Override
public boolean onTap(GeoPoint p, MapView mapView)
{
    // ...

    Intent intent = new Intent();
    intent.setClass(mapView.getContext(), FullscreenView.class);
    startActivity(intent);

    // ...
}

MySQL high CPU usage

As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:

On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):

$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

How do I know if jQuery has an Ajax request pending?

We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

JS Code

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });

How can I submit a form using JavaScript?

It works perfectly in my case.

document.getElementById("form1").submit();

Also, you can use it in a function as below:

function formSubmit()
{
    document.getElementById("form1").submit();
}

How to make a redirection on page load in JSF 1.x

Set the GET query parameters as managed properties in faces-config.xml so that you don't need to gather them manually:

<managed-bean>
    <managed-bean-name>forward</managed-bean-name>
    <managed-bean-class>com.example.ForwardBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>action</property-name>
        <value>#{param.action}</value>
    </managed-property>
    <managed-property>
        <property-name>actionParam</property-name>
        <value>#{param.actionParam}</value>
    </managed-property>
</managed-bean>

This way the request forward.jsf?action=outcome1&actionParam=123 will let JSF set the action and actionParam parameters as action and actionParam properties of the ForwardBean.

Create a small view forward.xhtml (so small that it fits in default response buffer (often 2KB) so that it can be resetted by the navigationhandler, otherwise you've to increase the response buffer in the servletcontainer's configuration), which invokes a bean method on beforePhase of the f:view:

<!DOCTYPE html>
<html xmlns:f="http://java.sun.com/jsf/core">
    <f:view beforePhase="#{forward.navigate}" />
</html>

The ForwardBean can look like this:

public class ForwardBean {
    private String action;
    private String actionParam;

    public void navigate(PhaseEvent event) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = action; // Do your thing?
        facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
    }

    // Add/generate the usual boilerplate.
}

The navigation-rule speaks for itself (note the <redirect /> entries which would do ExternalContext#redirect() instead of ExternalContext#dispatch() under the covers):

<navigation-rule>
    <navigation-case>
        <from-outcome>outcome1</from-outcome>
        <to-view-id>/outcome1.xhtml</to-view-id>
        <redirect />
    </navigation-case>
    <navigation-case>
        <from-outcome>outcome2</from-outcome>
        <to-view-id>/outcome2.xhtml</to-view-id>
        <redirect />
    </navigation-case>
</navigation-rule>

An alternative is to use forward.xhtml as

<!DOCTYPE html>
<html>#{forward}</html>

and update the navigate() method to be invoked on @PostConstruct (which will be invoked after bean's construction and all managed property setting):

@PostConstruct
public void navigate() {
    // ...
}    

It has the same effect, however the view side is not really self-documenting. All it basically does is printing ForwardBean#toString() (and hereby implicitly constructing the bean if not present yet).


Note for the JSF2 users, there is a cleaner way of passing parameters with <f:viewParam> and more robust way of handling the redirect/navigation by <f:event type="preRenderView">. See also among others:

C++: what regex library should I use?

In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.

jQuery object equality

First order your object based on key using this function

function sortObject(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}

Then, compare the stringified version of your object, using this funtion

function isEqualObject(a,b){
    return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}

Here is an example

Assuming objects keys are ordered differently and are of the same values

var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}

isEqualObject(obj1,obj2);//returns true

How to set layout_weight attribute dynamically from code?

Use LinearLayout.LayoutParams:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);

EDIT: Ah, Erich's answer is easier!

Catch paste input

This proved to be quite illusive. The value of the input is not updated prior to the execution of the code inside the paste event function. I tried calling other events from within the paste event function but the input value is still not updated with the pasted text inside the function of any events. That is all events apart from keyup. If you call keyup from within the paste event function you can sanitize the pasted text from within the keyup event function. like so...

$(':input').live
(
    'input paste',
    function(e)
    {
        $(this).keyup();
    }
);

$(':input').live
(
    'keyup',
    function(e)
    {
        // sanitize pasted text here
    }
);

There is one caveat here. In Firefox, if you reset the input text on every keyup, if the text is longer than the viewable area allowed by the input width, then resetting the value on every keyup breaks the browser functionality that auto scrolls the text to the caret position at the end of the text. Instead the text scrolls back to the beginning leaving the caret out of view.

How to get the indexpath.row when an element is activated?

For Swift2.1

I found a way to do it, hopefully, it'll help.

let point = tableView.convertPoint(CGPoint.zero, fromView: sender)

    guard let indexPath = tableView.indexPathForRowAtPoint(point) else {
        fatalError("can't find point in tableView")
    }

How to find out if a Python object is a string?

Its simple, use the following code (we assume the object mentioned to be obj)-

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')

Delete empty lines using sed

I am missing the awk solution:

awk 'NF' file

Which would return:

xxxxxx
yyyyyy
zzzzzz

How does this work? Since NF stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk perform its default action: print the current line.

Efficient way of having a function only execute once in a loop

You can also use one of the standard library functools.lru_cache or functools.cache decorators in front of the function:

from functools import lru_cache

@lru_cache def expensive_function(): return None

https://docs.python.org/3/library/functools.html

Best way to compare dates in Android

Your code could be reduced to

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

Select * from table
where CONTAINS([Column], '"A00*"')  

will act as % same as

where [Column] Like 'A00%'

Collections.sort with multiple fields

This is an old question so I don't see a Java 8 equivalent. Here is an example for this specific case.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Compares multiple parts of the Report object.
 */
public class SimpleJava8ComparatorClass {

    public static void main(String[] args) {
        List<Report> reportList = new ArrayList<>();
        reportList.add(new Report("reportKey2", "studentNumber2", "school1"));
        reportList.add(new Report("reportKey4", "studentNumber4", "school6"));
        reportList.add(new Report("reportKey1", "studentNumber1", "school1"));
        reportList.add(new Report("reportKey3", "studentNumber2", "school4"));
        reportList.add(new Report("reportKey2", "studentNumber2", "school3"));

        System.out.println("pre-sorting");
        System.out.println(reportList);
        System.out.println();

        Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
            .thenComparing(Report::getStudentNumber)
            .thenComparing(Report::getSchool));

        System.out.println("post-sorting");
        System.out.println(reportList);
    }

    private static class Report {

        private String reportKey;
        private String studentNumber;
        private String school;

        public Report(String reportKey, String studentNumber, String school) {
            this.reportKey = reportKey;
            this.studentNumber = studentNumber;
            this.school = school;
        }

        public String getReportKey() {
            return reportKey;
        }

        public void setReportKey(String reportKey) {
            this.reportKey = reportKey;
        }

        public String getStudentNumber() {
            return studentNumber;
        }

        public void setStudentNumber(String studentNumber) {
            this.studentNumber = studentNumber;
        }

        public String getSchool() {
            return school;
        }

        public void setSchool(String school) {
            this.school = school;
        }

        @Override
        public String toString() {
            return "Report{" +
                   "reportKey='" + reportKey + '\'' +
                   ", studentNumber='" + studentNumber + '\'' +
                   ", school='" + school + '\'' +
                   '}';
        }
    }
}

Get timezone from DateTime

DateTime does not know its timezone offset. There is no built-in method to return the offset or the timezone name (e.g. EAT, CEST, EST etc).

Like suggested by others, you can convert your date to UTC:

DateTime localtime = new DateTime.Now;
var utctime = localtime.ToUniversalTime();

and then only calculate the difference:

TimeSpan difference = localtime - utctime;

Also you may convert one time to another by using the DateTimeOffset:

DateTimeOffset targetTime = DateTimeOffset.Now.ToOffset(new TimeSpan(5, 30, 0));

But this is sort of lossy compression - the offset alone cannot tell you which time zone it is as two different countries may be in different time zones and have the same time only for part of the year (eg. South Africa and Europe). Also, be aware that summer daylight saving time may be introduced at different dates (EST vs CET - a 3-week difference).

You can get the name of your local system time zone using TimeZoneInfo class:

TimeZoneInfo localZone = TimeZoneInfo.Local;
localZone.IsDaylightSavingTime(localtime) ? localZone.DaylightName : localZone.StandardName

I agree with Gerrie Schenck, please read the article he suggested.

Change size of axes title and labels in ggplot2

You can change axis text and label size with arguments axis.text= and axis.title= in function theme(). If you need, for example, change only x axis title size, then use axis.title.x=.

g+theme(axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"))

There is good examples about setting of different theme() parameters in ggplot2 page.

How do I resolve a HTTP 414 "Request URI too long" error?

Under Apache, the limit is a configurable value, LimitRequestLine. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000) under AccessFileName .htaccess.

However, note that if you're actually running into this limit, you are probably abusing GET to begin with. You should use POST to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."

Codeigniter - no input file specified

RewriteEngine, DirectoryIndex in .htaccess file of CodeIgniter apps

I just changed the .htaccess file contents and as shown in the following links answer. And tried refreshing the page (which didn't work, and couldn't find the request to my controller) it worked.

Then just because of my doubt I undone the changes I did to my .htaccess inside my public_html folder back to original .htaccess content. So it's now as follows (which is originally it was):

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]

And now also it works.

Hint: Seems like before the Rewrite Rules haven't been clearly setup within the Server context.

My file structure is as follows:

/
|- gheapp
|    |- application
|    L- system
|
|- public_html
|    |- .htaccess
|    L- index.php

And in the index.php I have set up the following paths to the system and the application:

$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';

Note: by doing so, our application source code becomes hidden to the public at first.

Please, if you guys find anything wrong with my answer, comment and re-correct me!
Hope beginners would find this answer helpful.

Thanks!

A transport-level error has occurred when receiving results from the server

It happened to me when I was trying to restore a SQL database and checked following Check Box in Options tab,

enter image description here

As it's a stand alone database server just closing down SSMS and reopening it solved the issue for me.

What is the use of BindingResult interface in spring MVC?

From the official Spring documentation:

General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building.

Serves as result holder for a DataBinder, obtained via the DataBinder.getBindingResult() method. BindingResult implementations can also be used directly, for example to invoke a Validator on it (e.g. as part of a unit test).

What is the difference between json.load() and json.loads() functions

The json.load() method (without "s" in "load") can read a file directly:

import json
with open('strings.json') as f:
    d = json.load(f)
    print(d)

json.loads() method, which is used for string arguments only.

import json

person = '{"name": "Bob", "languages": ["English", "Fench"]}'
print(type(person))
# Output : <type 'str'>

person_dict = json.loads(person)
print( person_dict)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}

print(type(person_dict))
# Output : <type 'dict'>

Here , we can see after using loads() takes a string ( type(str) ) as a input and return dictionary.

Intellij JAVA_HOME variable

In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"

  • Platform Settings > SDKs ( +; )
  • Click the + button to add a new SDK (or rename and load an existing one)
  • Choose the /Contents/Home directory from the appropriate SDK
    (i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)

How to convert Rows to Columns in Oracle?

 select * FROM doc_tab
    PIVOT
    (
    Min(document_id)
    FOR document_type IN ('Voters ID','Pan card','Drivers licence')
    ) 

outputs as this

enter image description here

sql fiddle demo here

Plotting of 1-dimensional Gaussian distribution function

With the excellent matplotlib and numpy packages

from matplotlib import pyplot as mp
import numpy as np

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
    mp.plot(x_values, gaussian(x_values, mu, sig))

mp.show()

will produce something like plot showing one-dimensional gaussians produced by matplotlib

How to access JSON decoded array in PHP

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

How do I get a decimal value when using the division operator in Python?

Here we have two possible cases given below

from __future__ import division

print(4/100)
print(4//100)

How to prevent SIGPIPEs (or handle them properly)

Another method is to change the socket so it never generates SIGPIPE on write(). This is more convenient in libraries, where you might not want a global signal handler for SIGPIPE.

On most BSD-based (MacOS, FreeBSD...) systems, (assuming you are using C/C++), you can do this with:

int set = 1;
setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));

With this in effect, instead of the SIGPIPE signal being generated, EPIPE will be returned.

Could you explain STA and MTA?

I find the existing explanations too gobbledygook. Here's my explanation in plain English:

STA: If a thread creates a COM object that's set to STA (when calling CoCreateXXX you can pass a flag that sets the COM object to STA mode), then only this thread can access this COM object (that's what STA means - Single Threaded Apartment), other thread trying to call methods on this COM object is under the hood silently turned into delivering messages to the thread that creates(owns) the COM object. This is very much like the fact that only the thread that created a UI control can access it directly. And this mechanism is meant to prevent complicated lock/unlock operations.

MTA: If a thread creates a COM object that's set to MTA, then pretty much every thread can directly call methods on it.

That's pretty much the gist of it. Although technically there're some details I didn't mention, such as in the 'STA' paragraph, the creator thread must itself be STA. But this is pretty much all you have to know to understand STA/MTA/NA.

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

With Spring can I make an optional path variable?

You can't have optional path variables, but you can have two controller methods which call the same service code:

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
        HttpServletRequest req,
        @PathVariable String type,
        @RequestParam("track") String track) {
    return getTestBean(type);
}

@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
        HttpServletRequest req,
        @RequestParam("track") String track) {
    return getTestBean();
}

How to insert a new line in Linux shell script?

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

User Control - Custom Properties

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

Passing HTML input value as a JavaScript Function Parameter

   <form action="" onsubmit="additon()" name="form1" id="form1">
      a: <input type="number" name="a" id="a"><br>
      b: <input type="number" name="b" id="b"><br>
      <input type="submit" value="Submit" name="submit">
   </form>
  <script>
      function additon() 
      {
           var a = document.getElementById('a').value;
           var b = document.getElementById('b').value;
           var sum = parseInt(a) + parseInt(b);
           return sum;
      }
  </script>

Is it possible to modify a string of char in C?

A lot of folks get confused about the difference between char* and char[] in conjunction with string literals in C. When you write:

char *foo = "hello world";

...you are actually pointing foo to a constant block of memory (in fact, what the compiler does with "hello world" in this instance is implementation-dependent.)

Using char[] instead tells the compiler that you want to create an array and fill it with the contents, "hello world". foo is the a pointer to the first index of the char array. They both are char pointers, but only char[] will point to a locally allocated and mutable block of memory.

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.

How can I find the product GUID of an installed MSI setup?

If you have too many installers to find what you are looking for easily, here is some powershell to provide a filter and narrow it down a little by display name.

$filter = "*core*sdk*"; (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name | % { $path = "Registry::$_"; Get-ItemProperty $path } | Where-Object { $_.DisplayName -like $filter } | Select-Object -Property DisplayName, PsChildName

wampserver doesn't go green - stays orange

you can run appache:

E:\wamp\bin\apache\apache2.4.9\bin\httpd.exe -d E:/wamp/bin/apache/apache2.4.9

after that see the log of error and solve it.

Does JavaScript pass by reference?

Function arguments are passed either by-value or by-sharing, but never ever by reference in JavaScript!

Call-by-Value

Primitive types are passed by-value:

_x000D_
_x000D_
var num = 123, str = "foo";

function f(num, str) {
  num += 1;
  str += "bar";
  console.log("inside of f:", num, str);
}

f(num, str);
console.log("outside of f:", num, str);
_x000D_
_x000D_
_x000D_

Reassignments inside a function scope are not visible in the surrounding scope.

This also applies to Strings, which are a composite data type and yet immutable:

_x000D_
_x000D_
var str = "foo";

function f(str) {
  str[0] = "b"; // doesn't work, because strings are immutable
  console.log("inside of f:", str);
}

f(str);
console.log("outside of f:", str);
_x000D_
_x000D_
_x000D_

Call-by-Sharing

Objects, that is to say all types that are not primitives, are passed by-sharing. A variable that holds a reference to an object actually holds merely a copy of this reference. If JavaScript would pursue a call-by-reference evaluation strategy, the variable would hold the original reference. This is the crucial difference between by-sharing and by-reference.

What are the practical consequences of this distinction?

_x000D_
_x000D_
var o = {x: "foo"}, p = {y: 123};

function f(o, p) {
  o.x = "bar"; // Mutation
  p = {x: 456}; // Reassignment
  console.log("o inside of f:", o);
  console.log("p inside of f:", p);
}

f(o, p);

console.log("o outside of f:", o);
console.log("p outside of f:", p);
_x000D_
_x000D_
_x000D_

Mutating means to modify certain properties of an existing Object. The reference copy that a variable is bound to and that refers to this object remains the same. Mutations are thus visible in the caller's scope.

Reassigning means to replace the reference copy bound to a variable. Since it is only a copy, other variables holding a copy of the same reference remain unaffected. Reassignments are thus not visible in the caller's scope like they would be with a call-by-reference evaluation strategy.

Further information on evaluation strategies in ECMAScript.

HTML5 - mp4 video does not play in IE9

Ended up using http://videojs.com/ to support all browsers.

But to get the video working in IE9 and Chrome I just added html5 doc type and used mp4:

<!DOCTYPE html>
<html>
<body>
  <video src="video.mp4" width="400" height="300" preload controls>
  </video>
</body>
</html>

JQuery Parsing JSON array

var dataArray = [];
var obj = jQuery.parseJSON(yourInput);

$.each(obj, function (index, value) {
    dataArray.push([value["yourID"].toString(), value["yourValue"] ]);
});

this helps me a lot :-)

Auto-expanding layout with Qt-Designer

After creating your QVBoxLayout in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout should now stretch to fit the window and will resize automatically when the entire window is resized.

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

How can I determine browser window size on server side C#

I went with using the regex from detectmobilebrowser.com to check against the user-agent string. Even tho it says it was last updated in 2014 it was accurate on the devices I tested.

Here is the C# code I got from them at the time of submitting this answer:

<%@ Page Language="C#" %> 
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%
    string u = Request.ServerVariables["HTTP_USER_AGENT"];
    Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
    Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
    if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4)))) {
        Response.Redirect("http://detectmobilebrowser.com/mobile");
    }
%>

Looking for simple Java in-memory cache

Try @Cacheable from jcabi-aspects. With a single annotation you make the entire method result cacheable in memory:

public class Resource {
  @Cacheable(lifetime = 5, unit = TimeUnit.SECONDS)
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}

Also, read this article: http://www.yegor256.com/2014/08/03/cacheable-java-annotation.html

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

How can I delete Docker's images?

The reason for the error is that even though the image did not have any tag, there still exists a container created on that image which might be in the exited state. So you need to ensure that you have stopped and deleted all containers created on those images. The following command helps you in removing all containers that are not running:

docker rm `docker ps -aq --no-trunc --filter "status=exited"`

Now this removes all the dangling non-intermediate <none> images:

docker rmi `docker images --filter 'dangling=true' -q --no-trunc`

Note: To stops all running containers:

docker stop `docker ps -q`

How to check if a variable is equal to one string or another string?

Two separate checks. Also, use == rather than is to check for equality rather than identity.

 if var=='stringone' or var=='stringtwo':
     dosomething()

Forking vs. Branching in GitHub

Forking creates an entirely new repository from existing repository (simply doing git clone on gitHub/bitbucket)

Forks are best used: when the intent of the ‘split’ is to create a logically independent project, which may never reunite with its parent.

Branch strategy creates a new branch over the existing/working repository

Branches are best used: when they are created as temporary places to work through a feature, with the intent to merge the branch with the origin.

More Specific :- In open source projects it is the owner of the repository who decides who can push to the repository. However, the idea of open source is that everybody can contribute to the project.

This problem is solved by forks: any time a developer wants to change something in an open source project, they don’t clone the official repository directly. Instead, they fork it to create a copy. When the work is finished, they make a pull request so that the owner of the repository can review the changes and decide whether to merge them to his project.

At its core forking is similar to feature branching, but instead of creating branches a fork of the repository is made, and instead of doing a merge request you create a pull request.

The below links provide the difference in a well-explained manner :

https://blog.gitprime.com/the-definitive-guide-to-forks-and-branches-in-git/

https://buddy.works/blog/5-types-of-git-workflows

http://www.continuousagile.com/unblock/branching.html

Google Chrome: This setting is enforced by your administrator

In my case, the setting was HKEY_CURRENT_USER\Software\Policies\Google\Chrome

I deleted Chrome and everything is fine now.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

In your MoviesService you should import FirebaseListObservable in order to define return type FirebaseListObservable<any[]>

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

then get() method should like this-

get (): FirebaseListObservable<any[]>{
        return this.db.list('/movies');
    }

this get() method will return FirebaseListObervable of movies list

In your MoviesComponent should look like this

export class MoviesComponent implements OnInit {
  movies: any[];

  constructor(private moviesDb: MoviesService) { }

  ngOnInit() {
    this.moviesDb.get().subscribe((snaps) => {
       this.movies = snaps;
   });
 }
}

Then you can easily iterate through movies without async pipe as movies[] data is not observable type, your html should be this

ul
  li(*ngFor='let movie of movies')
    {{ movie.title }}

if you declear movies as a

movies: FirebaseListObservable<any[]>;

then you should simply call

movies: FirebaseListObservable<any[]>;
ngOnInit() {
    this.movies = this.moviesDb.get();
}

and your html should be this

ul
  li(*ngFor='let movie of movies | async')
    {{ movie.title }}

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

How to link to specific line number on github

Don't just link to the line numbers! Be sure to use the canonical URL too. Otherwise when that file is updated, you'll have a URL that points to the wrong lines!

How to make a permanent link to the right lines:

Click on the line number you want (like line 18), and the URL in your browser will get a #L18 tacked onto the end. You literally click on the 18 at the left side, not the line of code. Looks like this:

line 18 selected

And now your browser's URL looks like this:

https://github.com/git/git/blob/master/README#L18

If you want multiple lines selected, simply hold down the shift key and click a second line number, like line 20. Looks like this:

enter image description here

And now your browser's URL looks like this:

https://github.com/git/git/blob/master/README#L18-L20

Here's the important part:

Now get the canonical url for that particular commit by pressing the y key. The URL in your browser will change to become something like this:

https://github.com/git/git/blob/5bdb7a78adf2a2656a1915e6fa656aecb45c1fc3/README#L18-L20

That link contains the actual SHA hash for that particular commit, rather than the current version of the file on master. That means that this link will work forever and not point to lines 18-20 of whatever future version of that file might contain.

Now bask in the glow of your new permanent link. ;-)

update 9/29/2017: As pointed out by @watashiSHUN, github has now made it easier to get the permanent link by providing a ... menu on the left after you select one or more lines. Please upvote @watashiSHUN's answer too.

GitHub permalink menu

update 3/25/2016: Case in point — in the example above, I referred to the "README" file in the URL. Those non-canonical urls actually worked when this answer was written. But now those urls no longer work since README was moved to README.md. But the canonical URL with SHA hash still works, just as expected.

How to check variable type at runtime in Go language

See type assertions here:

http://golang.org/ref/spec#Type_assertions

I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

From official documentation

Warning: Do not filter files with binary content like images! This will most likely result in corrupt output.

If you have both text files and binary files as resources it is recommended to have two separated folders. One folder src/main/resources (default) for the resources which are not filtered and another folder src/main/resources-filtered for the resources which are filtered.

<project>
  ...
  <build>
    ...
    <resources>
      <resource>
        <directory>src/main/resources-filtered</directory>
        <filtering>true</filtering>
      </resource>
      ...
    </resources>
    ...
  </build>
  ...
</project>

Now you can put those files into src/main/resources which should not filtered and the other files into src/main/resources-filtered.

As already mentioned filtering binary files like images,pdf`s etc. could result in corrupted output. To prevent such problems you can configure file extensions which will not being filtered.

Most certainly, You have in your directory files that cannot be filtered. So you have to specify the extensions that has not be filtered.

How do I format a date in Jinja2?

Google App Engine users : If you're moving from Django to Jinja2, and looking to replace the date filter, note that the % formatting codes are different.

The strftime % codes are here: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

SQL like search string starts with

Aside from using %, age of empires III to lower case is age of empires iii so your query should be:

select *
from games
where lower(title) like 'age of empires iii%'

What does the line "#!/bin/sh" mean in a UNIX shell script?

It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.

#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl  <-- perl script
#!/usr/bin/php  <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.

Most scripting languages tend to interpret a line starting with # as comment and will ignore the following !/usr/bin/whatever portion, which might otherwise cause a syntax error in the interpreted language.

YouTube embedded video: set different thumbnail

Just copy and paste the code in HTML file. and enjoy the happy coding. Using Youtube api to manage the thumbnail of youtube embedded video.

<!DOCTYPE html>
<html>
<body>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script>
        var tag = document.createElement('script');

        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        var player;
        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '640',
                videoId: 'M7lc1UVf-VE',
                events: {
                    'onReady': onPlayerReady,
                }
            });
        }

        function onPlayerReady(event) {
            $('#play_vid').click(function() {
                event.target.playVideo();
            });
        }

        $(document).ready(function() {
            $('#player').hide();
            $('#play_vid').click(function() {
                $('#player').show();
                $('#play_vid').hide();
            });
        });
    </script>

    <div id="player"></div>
    <img id="play_vid" src="YOUR_IMAGE_PATH" />
</body>
</html>

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

How to "properly" print a list?

You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:

import string

print string.translate(str(lst), None, "'")

Using the string.translate() function will also work in 2.6+, so using it might be preferable.

Java using enum with switch statement

I like a few usages of Java enum:

  1. .name() allows you to fetch the enum name in String.
  2. .ordinal() allow you to get the integer value, 0-based.
  3. You can attach other value parameters with each enum.
  4. and, of course, switch enabled.

enum with value parameters:

    enum StateEnum {
        UNDEFINED_POLL  ( 1 * 1000L,       4 * 1000L),
        SUPPORT_POLL    ( 1 * 1000L,       5 * 1000L),
        FAST_POLL       ( 2 * 1000L,  4 * 60 * 1000L),
        NO_POLL         ( 1 * 1000L,       6 * 1000L); 
        ...
    }

switch example:

private void queuePoll(StateEnum se) {
    // debug print se.name() if needed
    switch (se) {
        case UNDEFINED_POLL:
            ...
            break;
        case SUPPORT_POLL:
            ...
            break;

Escaping single quote in PHP when inserting into MySQL

I had the same problem and I solved it like this:

$text = str_replace("'", "\'", $YourContent);

There is probably a better way to do this, but it worked for me and it should work for you too.

View list of all JavaScript variables in Google Chrome Console

To view any variable in chrome, go to "Sources", and then "Watch" and add it. If you add the "window" variable here then you can expand it and explore.

Cannot load properties file from resources directory

If the file is placed under target/classes after compiling, then it is already in a directory that is part of the build path. The directory src/main/resources is the Maven default directory for such resources, and it is automatically placed to the build path by the Eclipse Maven plugin (M2E). So, there is no need to move your properties file.

The other topic is, how to retrieve such resources. Resources in the build path are automatically in the class path of the running Java program. Considering this, you should always load such resources with a class loader. Example code:

String resourceName = "myconf.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
    props.load(resourceStream);
}
// use props here ...

JSON date to Java date?

Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).

So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX") produces a format that can parse both "2013-03-11T01:38:18.309Z" and "2013-03-11T01:38:18.309+0000" and will give you the same result.

Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.

I actually have more trouble on the JavaScript side to deal with both formats.

How to make VS Code to treat other file extensions as certain language?

I have followed a different approach to solve pretty much the same problem, in my case, I made a new extension that adds PHP syntax highlighting support for Drupal-specific files (such as .module and .inc): https://github.com/mastazi/VS-code-drupal

As you can see in the code, I created a new extension rather than modifying the existing PHP extension. Obviously I declare a dependency on the PHP extension in the Drupal extension.

The advantage of doing it this way is that if there is an update to the PHP extension, my custom support for Drupal doesn't get lost in the update process.

Is it possible to get only the first character of a String?

String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.

So, assuming getSymbol() returns a String, to print the first character, you could do:

System.out.println(ld.getSymbol().charAt(0)); // char at index 0

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

How to pass multiple parameters in a querystring

Query_string

(Following is the text of the linked section of the Wikipedia entry.)

Structure

A typical URL containing a query string is as follows:

http://server/path/program?query_string

When a server receives a request for such a page, it runs a program (if configured to do so), passing the query_string unchanged to the program. The question mark is used as a separator and is not part of the query string.

A link in a web page may have a URL that contains a query string, however, HTML defines three ways a web browser can generate the query string:

  • a web form via the ... element
  • a server-side image map via the ?ismap? attribute on the element with a construction
  • an indexed search via the now deprecated element

Web forms

The main use of query strings is to contain the content of an HTML form, also known as web form. In particular, when a form containing the fields field1, field2, field3 is submitted, the content of the fields is encoded as a query string as follows:

field1=value1&field2=value2&field3=value3...

  • The query string is composed of a series of field-value pairs.
  • Within each pair, the field name and value are separated by an equals sign. The equals sign may be omitted if the value is an empty string.
  • The series of pairs is separated by the ampersand, '&' (or semicolon, ';' for URLs embedded in HTML and not generated by a ...; see below). While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field:

field1=value1&field1=value2&field1=value3...

For each field of the form, the query string contains a pair field=value. Web forms may include fields that are not visible to the user; these fields are included in the query string when the form is submitted

This convention is a W3C recommendation. W3C recommends that all web servers support semicolon separators in addition to ampersand separators[6] to allow application/x-www-form-urlencoded query strings in URLs within HTML documents without having to entity escape ampersands.

Technically, the form content is only encoded as a query string when the form submission method is GET. The same encoding is used by default when the submission method is POST, but the result is not sent as a query string, that is, is not added to the action URL of the form. Rather, the string is sent as the body of the HTTP request.

Attributes / member variables in interfaces?

Interfaces cannot require instance variables to be defined -- only methods.

(Variables can be defined in interfaces, but they do not behave as might be expected: they are treated as final static.)

Happy coding.

jquery .on() method with load event

As the other have mentioned, the load event does not bubble. Instead you can manually trigger a load-like event with a custom event:

$('#item').on('namespace/onload', handleOnload).trigger('namespace/onload')

If your element is already listening to a change event:

$('#item').on('change', handleChange).trigger('change')

I find this works well. Though, I stick to custom events to be more explicit and avoid side effects.

How do I detect whether a Python variable is a function?

callable(x) will return true if the object passed can be called in Python, but the function does not exist in Python 3.0, and properly speaking will not distinguish between:

class A(object):
    def __call__(self):
        return 'Foo'

def B():
    return 'Bar'

a = A()
b = B

print type(a), callable(a)
print type(b), callable(b)

You'll get <class 'A'> True and <type function> True as output.

isinstance works perfectly well to determine if something is a function (try isinstance(b, types.FunctionType)); if you're really interested in knowing if something can be called, you can either use hasattr(b, '__call__') or just try it.

test_as_func = True
try:
    b()
except TypeError:
    test_as_func = False
except:
    pass

This, of course, won't tell you whether it's callable but throws a TypeError when it executes, or isn't callable in the first place. That may not matter to you.

How can I make text appear on next line instead of overflowing?

Try the <wbr> tag - not as elegant as the word-wrap property that others suggested, but it's a working solution until all major browsers (read IE) implement CSS3.

Php $_POST method to get textarea value

Always (always, always, I'm not kidding) use htmlspecialchars():

echo htmlspecialchars($_POST['contact_list']);

Get TimeZone offset value from TimeZone without TimeZone name

We can easily get the millisecond offset of a TimeZone with only a TimeZone instance and System.currentTimeMillis(). Then we can convert from milliseconds to any time unit of choice using the TimeUnit class.

Like so:

public static int getOffsetHours(TimeZone timeZone) {
    return (int) TimeUnit.MILLISECONDS.toHours(timeZone.getOffset(System.currentTimeMillis()));
}

Or if you prefer the new Java 8 time API

public static ZoneOffset getOffset(TimeZone timeZone) { //for using ZoneOffsett class
    ZoneId zi = timeZone.toZoneId();
    ZoneRules zr = zi.getRules();
    return zr.getOffset(LocalDateTime.now());
}

public static int getOffsetHours(TimeZone timeZone) { //just hour offset
    ZoneOffset zo = getOffset(timeZone);
    TimeUnit.SECONDS.toHours(zo.getTotalSeconds());
}

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Here is another way to detect the current viewport without putting the viewport size numbers in your javascript.

See css and javascript snippets here: https://gist.github.com/steveh80/288a9a8bd4c3de16d799

After adding that snippets to your css and javascript files you can detect the current viewport like this:

viewport.is('xs') // returns boolean

If you want to detect a viewport range use it like this

viewport.isEqualOrGreaterThan('sm') // returns true for sm, md and lg

How to change ViewPager's page?

slide to right

viewPager.arrowScroll(View.FOCUS_RIGHT);

slide to left

viewPager.arrowScroll(View.FOCUS_LEFT);

How to use a class from one C# project with another C# project

Say your class in project 2 is called MyClass.

Obviously, first reference your project 2 under references in project 1 then

using namespaceOfProject2;

// for the class calling bit:

namespaceOfProject2.MyClass project2Class = new namespaceOfProject2.MyClass();

so whenever you want to reference that class you type project2Class. Plus make sure that class is public too.

How do I get a list of folders and sub folders without the files?

dir /ad /b /s will give the required answer.

How to get jSON response into variable from a jquery script

You should use data.response in your JS instead of json.response.

Remove IE10's "clear field" X button on certain inputs?

Style the ::-ms-clear pseudo-element for the box:

.someinput::-ms-clear {
    display: none;
}

What is a 'multi-part identifier' and why can't it be bound?

It's probably a typo. Look for the places in your code where you call [schema].[TableName] (basically anywhere you reference a field) and make sure everything is spelled correctly.

Personally, I try to avoid this by using aliases for all my tables. It helps tremendously when you can shorten a long table name to an acronym of it's description (i.e. WorkOrderParts -> WOP), and also makes your query more readable.

Edit: As an added bonus, you'll save TONS of keystrokes when all you have to type is a three or four-letter alias vs. the schema, table, and field names all together.

CSV parsing in Java - working example..?

You also have the Apache Commons CSV library, maybe it does what you need. See the guide. Updated to Release 1.1 in 2014-11.

Also, for the foolproof edition, I think you'll need to code it yourself...through SimpleDateFormat you can choose your formats, and specify various types, if the Date isn't like any of your pre-thought types, it isn't a Date.

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

I found that my issue was someone committed the file .project and .classpath that had references to Java1.5 as the default JRE.

<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5">
    <attributes>
        <attribute name="owner.project.facets" value="java"/>
    </attributes>
</classpathentry>

By closing the project, removing the files, and then re-importing as a Maven project, I was able to properly set the project to use workspace JRE or the relevant jdk without it reverting back to 1.5 . Thus, avoid checking into your SVN the .project and .classpath files

Hope this helps others.

Rename Excel Sheet with VBA Macro

This should do it:

WS.Name = WS.Name & "_v1"

Check if a value exists in ArrayList

public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}

JavaScript dictionary with names

Another approach would be to have an array of objects, with each individual object holding the properties of a column. This slightly changes the structure of "myMappings", but makes it easy to work with:

var myMappings = [
    { title: "Name", width: "10%" },
    { title: "Phone", width: "10%" },
    { title: "Address", width: "50%" },
    { title: "Zip", width: "10%" },
    { title: "Comments", width: "20%" }
];

Then you could easily iterate through all your "columns" with a for loop:

for (var i = 0; i < myMappings.length; i += 1) {
    // myMappings[i].title ...
    // myMappings[i].width ...
}

How to find largest objects in a SQL Server database?

I've been using this SQL script (which I got from someone, somewhere - can't reconstruct who it came from) for ages and it's helped me quite a bit understanding and determining the size of indices and tables:

SELECT 
    t.name AS TableName,
    i.name as indexName,
    sum(p.rows) as RowCounts,
    sum(a.total_pages) as TotalPages, 
    sum(a.used_pages) as UsedPages, 
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.object_id = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.name NOT LIKE 'dt%' AND
    i.object_id > 255 AND  
    i.index_id <= 1
GROUP BY 
    t.name, i.object_id, i.index_id, i.name 
ORDER BY 
    object_name(i.object_id) 

Of course, you can use another ordering criteria, e.g.

ORDER BY SUM(p.rows) DESC

to get the tables with the most rows, or

ORDER BY SUM(a.total_pages) DESC

to get the tables with the most pages (8K blocks) used.

Resolving instances with ASP.NET Core DI from within ConfigureServices

I know this is an old question but I'm astonished that a rather obvious and disgusting hack isn't here.

You can exploit the ability to define your own ctor function to grab necessary values out of your services as you define them... obviously this would be ran every time the service was requested unless you explicitly remove/clear and re-add the definition of this service within the first construction of the exploiting ctor.

This method has the advantage of not requiring you to build the service tree, or use it, during the configuration of the service. You are still defining how services will be configured.

public void ConfigureServices(IServiceCollection services)
{
    //Prey this doesn't get GC'd or promote to a static class var
    string? somevalue = null;

    services.AddSingleton<IServiceINeedToUse, ServiceINeedToUse>(scope => {
         //create service you need
         var service = new ServiceINeedToUse(scope.GetService<IDependantService>())
         //get the values you need
         somevalue = somevalue ?? service.MyDirtyHack();
         //return the instance
         return service;
    });
    services.AddTransient<IOtherService, OtherService>(scope => {
         //Explicitly ensuring the ctor function above is called, and also showcasing why this is an anti-pattern.
         scope.GetService<IServiceINeedToUse>();
         //TODO: Clean up both the IServiceINeedToUse and IOtherService configuration here, then somehow rebuild the service tree.
         //Wow!
         return new OtherService(somevalue);
    });
}

The way to fix this pattern would be to give OtherService an explicit dependency on IServiceINeedToUse, rather than either implicitly depending on it or its method's return value... or resolving that dependency explicitly in some other fashion.

How do I make a LinearLayout scrollable?

Put your whole content in linear layout which is placed inside ScrollView.

ScrollView takes only one layout as its child.

isScrollContainer="true"

This property is used when your softkey in android pops up and still you want your view to scroll.

How to produce an csv output file from stored procedure in SQL Server

You can do this using OPENROWSET as suggested in this answer. Reposting Slogmeister Extrarodinare answer:

Use T-SQL

INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName

But, there are couple of caveats:

  1. You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.

  2. The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.

How to get < span > value?

You need to change your code as below:-

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

After doing this you will get the tag value in alert.

Change column type in pandas

pandas >= 1.0

Here's a chart that summarises some of the most important conversions in pandas.

enter image description here

Conversions to string are trivial .astype(str) and are not shown in the figure.

"Hard" versus "Soft" conversions

Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes                                                                  

a    object
b    object
dtype: object

# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes                                             

a    int64
b    int64
dtype: object

# Infers better data types for object data - soft conversion
df.infer_objects().dtypes                                                  

a    object  # no change
b     int64
dtype: object

# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes                                                     

How to generate random number with the specific length in python

You could write yourself a little function to do what you want:

import random
def randomDigits(digits):
    lower = 10**(digits-1)
    upper = 10**digits - 1
    return random.randint(lower, upper)

Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.

How to Clear Console in Java?

Runtime.getRuntime().exec("PlatformDepedentCode");

You need to replace "PlatformDependentCode" with your platform's clear console command.

The exec() method executes the command you entered as the argument, just as if it is entered in the console.

In Windows you would write it as Runtime.getRuntime().exec("cls");.

How do I handle ImeOptions' done button click?

More details on how to set the OnKeyListener, and have it listen for the Done button.

First add OnKeyListener to the implements section of your class. Then add the function defined in the OnKeyListener interface:

/*
 * Respond to soft keyboard events, look for the DONE press on the password field.
 */
public boolean onKey(View v, int keyCode, KeyEvent event)
{
    if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
        (keyCode == KeyEvent.KEYCODE_ENTER))
    {
        // Done pressed!  Do something here.
    }
    // Returning false allows other listeners to react to the press.
    return false;
}

Given an EditText object:

EditText textField = (EditText)findViewById(R.id.MyEditText);
textField.setOnKeyListener(this);

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

I wrote a package (https://github.com/alexsanjoseph/compareDF) since I had the same issue.

  > df1 <- data.frame(a = 1:5, b=letters[1:5], row = 1:5)
  > df2 <- data.frame(a = 1:3, b=letters[1:3], row = 1:3)
  > df_compare = compare_df(df1, df2, "row")

  > df_compare$comparison_df
    row chng_type a b
  1   4         + 4 d
  2   5         + 5 e

A more complicated example:

library(compareDF)
df1 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
                         "Hornet 4 Drive", "Duster 360", "Merc 240D"),
                 id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Mer"),
                 hp = c(110, 110, 181, 110, 245, 62),
                 cyl = c(6, 6, 4, 6, 8, 4),
                 qsec = c(16.46, 17.02, 33.00, 19.44, 15.84, 20.00))

df2 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
                         "Hornet 4 Drive", " Hornet Sportabout", "Valiant"),
                 id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Val"),
                 hp = c(110, 110, 93, 110, 175, 105),
                 cyl = c(6, 6, 4, 6, 8, 6),
                 qsec = c(16.46, 17.02, 18.61, 19.44, 17.02, 20.22))

> df_compare$comparison_df
    grp chng_type                id1 id2  hp cyl  qsec
  1   1         -  Hornet Sportabout Dus 175   8 17.02
  2   2         +         Datsun 710 Dat 181   4 33.00
  3   2         -         Datsun 710 Dat  93   4 18.61
  4   3         +         Duster 360 Dus 245   8 15.84
  5   7         +          Merc 240D Mer  62   4 20.00
  6   8         -            Valiant Val 105   6 20.22

The package also has an html_output command for quick checking

df_compare$html_output enter image description here

"Cannot GET /" with Connect on Node.js

You typically want to render templates like this:

app.get('/', function(req, res){
  res.render('index.ejs');
});

However you can also deliver static content - to do so use:

app.use(express.static(__dirname + '/public'));

Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

Take a look through the express API and Connect Static middleware docs for more info.

Action Bar's onClick listener for the Home button

Best way to customize Action bar onClickListener is onSupportNavigateUp()

This code will be helpful link for helping code

Get screenshot on Windows with Python?

import pyautogui

s = pyautogui.screenshot()
s.save(r'C:\\Users\\NAME\\Pictures\\s.png')

Select a date from date picker using Selenium webdriver

Just do

  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("document.getElementById('id').value='1988-01-01'");

Mongoose (mongodb) batch insert?

Model.create() vs Model.collection.insert(): a faster approach

Model.create() is a bad way to do inserts if you are dealing with a very large bulk. It will be very slow. In that case you should use Model.collection.insert, which performs much better. Depending on the size of the bulk, Model.create() will even crash! Tried with a million documents, no luck. Using Model.collection.insert it took just a few seconds.

Model.collection.insert(docs, options, callback)
  • docs is the array of documents to be inserted;
  • options is an optional configuration object - see the docs
  • callback(err, docs) will be called after all documents get saved or an error occurs. On success, docs is the array of persisted documents.

As Mongoose's author points out here, this method will bypass any validation procedures and access the Mongo driver directly. It's a trade-off you have to make since you're handling a large amount of data, otherwise you wouldn't be able to insert it to your database at all (remember we're talking hundreds of thousands of documents here).

A simple example

var Potato = mongoose.model('Potato', PotatoSchema);

var potatoBag = [/* a humongous amount of potato objects */];

Potato.collection.insert(potatoBag, onInsert);

function onInsert(err, docs) {
    if (err) {
        // TODO: handle error
    } else {
        console.info('%d potatoes were successfully stored.', docs.length);
    }
}

Update 2019-06-22: although insert() can still be used just fine, it's been deprecated in favor of insertMany(). The parameters are exactly the same, so you can just use it as a drop-in replacement and everything should work just fine (well, the return value is a bit different, but you're probably not using it anyway).

Reference

Remove scrollbars from textarea

Try the following, not sure which will work for all browsers or the browser you are working with, but it would be best to try all:

<textarea style="overflow:auto"></textarea>

Or

<textarea style="overflow:hidden"></textarea>

...As suggested above

You can also try adding this, I never used it before, just saw it posted on a site today:

<textarea style="resize:none"></textarea>

This last option would remove the ability to resize the textarea. You can find more information on the CSS resize property here

Get Base64 encode file-data from Input Form

It's entirely possible in browser-side javascript.

The easy way:

The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,), but that's no biggie. This would take all the fun out though.

The hard way:

If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer(). This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.

There are two methods:

  • Convert to string and use the built-in btoa or similar
    • I haven't tested all cases, but works for me- just get the char-codes
  • Convert directly from a Uint8Array to base64

I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.

What I do now:

The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):

function uint8ToString(buf) {
    var i, length, out = '';
    for (i = 0, length = buf.length; i < length; i += 1) {
        out += String.fromCharCode(buf[i]);
    }
    return out;
}

From there, just do:

var base64 = btoa(uint8ToString(yourUint8Array));

Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:

window.open("data:application/octet-stream;base64," + base64);

This will download it as a file.

Other info:

To get the data as a Uint8Array, look at the MDN docs:

Typescript es6 import module "File is not a module error"

In addition to A. Tim's answer there are times when even that doesn't work, so you need to:

  1. Rewrite the import string, using the intellisense. Sometimes this fixes the issue
  2. Restart VS Code

How to find memory leak in a C++ code/project?

MTuner is a free multi platform memory profiling, leak detection and analysis tool supporting MSVC, GCC and Clang compilers. Features include:

  • timeline based history of memory usage and live memory blocks
  • powerful memory operation filtering based on heap, memory tag, time range, etc.
  • SDK for manual instrumentation with full source code
  • continuous integration support through command line usage
  • call stack tree and tree map navigation
  • much more.

Users can profile any software targeting platforms with GCC or Clang cross compilers. MTuner comes with built in support for Windows, PlayStation 4 and PlayStation 3 platforms.

What is the best way to get all the divisors of a number?

Here is a smart and fast way to do it for numbers up to and around 10**16 in pure Python 3.6,

from itertools import compress

def primes(n):
    """ Returns  a list of primes < n for n > 2 """
    sieve = bytearray([True]) * (n//2)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)
    return [2,*compress(range(3,n,2), sieve[1:])]

def factorization(n):
    """ Returns a list of the prime factorization of n """
    pf = []
    for p in primeslist:
      if p*p > n : break
      count = 0
      while not n % p:
        n //= p
        count += 1
      if count > 0: pf.append((p, count))
    if n > 1: pf.append((n, 1))
    return pf

def divisors(n):
    """ Returns an unsorted list of the divisors of n """
    divs = [1]
    for p, e in factorization(n):
        divs += [x*p**k for k in range(1,e+1) for x in divs]
    return divs

n = 600851475143
primeslist = primes(int(n**0.5)+1) 
print(divisors(n))

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

How can I remove all text after a character in bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.

$ a='hello:world'

$ b=${a%:*}
$ echo "$b"
hello

$ a='hello:world:of:tomorrow'

$ echo "${a%:*}"
hello:world:of

$ echo "${a%%:*}"
hello

$ echo "${a#*:}"
world:of:tomorrow

$ echo "${a##*:}"
tomorrow

Execute multiple command lines with the same process using .NET

As another answer alludes to under newer versions of Windows it seems to be necessary to read the standard output and/or standard error streams otherwise it will stall between commands. A neater way to do that instead of using delays is to use an async callback to consume output from the stream:

static void RunCommands(List<string> cmds, string workingDirectory = "")
{
    var process = new Process();
    var psi = new ProcessStartInfo();
    psi.FileName = "cmd.exe";
    psi.RedirectStandardInput = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.UseShellExecute = false;
    psi.WorkingDirectory = workingDirectory;
    process.StartInfo = psi;
    process.Start();
    process.OutputDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
    process.ErrorDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    using (StreamWriter sw = process.StandardInput)
    {
        foreach (var cmd in cmds)
        {
            sw.WriteLine (cmd);
        }
    }
    process.WaitForExit();
}

AppendChild() is not a function javascript

 function createQuestionPanel() {

        var element = document.createElement("Input");
        element.setAttribute("type", "button");
        element.setAttribute("value", "button");
        element.setAttribute("name", "button");


        var div = document.createElement("div"); <------- Create DIv Node
        div.appendChild(element);<--------------------
        document.body.appendChild(div) <------------- Then append it to body

    }

    function formvalidate() {

    }

Is it possible to read from a InputStream with a timeout?

I would question the problem statement rather than just accept it blindly. You only need timeouts from the console or over the network. If the latter you have Socket.setSoTimeout() and HttpURLConnection.setReadTimeout() which both do exactly what is required, as long as you set them up correctly when you construct/acquire them. Leaving it to an arbitrary point later in the application when all you have is the InputStream is poor design leading to a very awkward implementation.

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

SkipSoft.net has some great toolkits. I ran into a similar problem with my Galaxy Nexus.... Ran the corresponding toolkit, which configured my system and downloaded the correct drivers. I then went into Windows Hardware manager after connecting the phone... Windows reported the exclamation that it couldn't find the device driver, so I ran update, and gave it the drivers directory the toolkit had created... and everything started working great. Hope this helps :)

Cannot find "Package Explorer" view in Eclipse

The simplest, and best long-term solution

Go to the main menu on top of Eclipse and locate Window next to Run and expand it.

 Window->Reset Perspective... to restore all views to their defaults

It will reset the default setting.

Display Bootstrap Modal using javascript onClick

A JavaScript function must first be made that holds what you want to be done:

function print() { console.log("Hello World!") }

and then that function must be called in the onClick method from inside an element:

<a onClick="print()"> ... </a>

You can learn more about modal interactions directly from the Bootstrap 3 documentation found here: http://getbootstrap.com/javascript/#modals

Your modal bind is also incorrect. It should be something like this, where "myModal" = ID of element:

$('#myModal').modal(options)

In other words, if you truly want to keep what you already have, put a "#" in front GSCCModal and see if that works.

It is also not very wise to have an onClick bound to a div element; something like a button would be more suitable.

Hope this helps!

How do I escape only single quotes?

After a long time fighting with this problem, I think I have found a better solution.

The combination of two functions makes it possible to escape a string to use as HTML.

One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.

Solution:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

  • a PHP line created to call a JavaScript function like

echo 'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"

Difference between virtual and abstract methods

Abstract Method:

  • If an abstract method is defined in a class, then the class should declare as an abstract class.

  • An abstract method should contain only method definition, should not Contain the method body/implementation.

  • An abstract method must be over ride in the derived class.

Virtual Method:

  • Virtual methods can be over ride in the derived class but not mandatory.
  • Virtual methods must have the method body/implementation along with the definition.

Example:

public abstract class baseclass
        {
            public abstract decimal getarea(decimal Radius);

            public virtual decimal interestpermonth(decimal amount)
            {
                return amount*12/100;
            }

            public virtual decimal totalamount(decimal Amount,decimal principleAmount)
            {
                return Amount + principleAmount;
            }
        }

        public class derivedclass:baseclass
        {
            public override decimal getarea(decimal Radius)
            {
                return 2 * (22 / 7) * Radius;
            }

            public override decimal interestpermonth(decimal amount)
            {
                return amount * 14 / 100;
            }
        }

for-in statement

In Typescript 1.5 and later, you can use for..of as opposed to for..in

var numbers = [1, 2, 3];

for (var number of numbers) {
    console.log(number);
}

Round up value to nearest whole number in SQL UPDATE

Ceiling is the command you want to use.

Unlike Round, Ceiling only takes one parameter (the value you wish to round up), therefore if you want to round to a decimal place, you will need to multiply the number by that many decimal places first and divide afterwards.

Example.

I want to round up 1.2345 to 2 decimal places.

CEILING(1.2345*100)/100 AS Cost

Pandas get topmost n records within each group

Since 0.14.1, you can now do nlargest and nsmallest on a groupby object:

In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]: 
id   
1   2    3
    1    2
2   6    4
    5    3
3   7    1
4   8    1
dtype: int64

There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.

If you're not interested in it, you can do .reset_index(level=1, drop=True) to get rid of it altogether.

(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series and SeriesGroupBy.)

What is bootstrapping?

See on the Wikipedia article on bootstrapping.

There is a section and links explaining what it means in Computing. It has four different uses in the field.

Here are some quotes, but for a more in depth explanation, and alternative meanings, consult the links above.

"...is a technique by which a simple computer program activates a more complicated system of programs."

"A different use of the term bootstrapping is to use a compiler to compile itself, by first writing a small part of a compiler of a new programming language in an existing language to compile more programs of the new compiler written in the new language."

Select the values of one property on all objects of an array in PowerShell

I think you might be able to use the ExpandProperty parameter of Select-Object.

For example, to get the list of the current directory and just have the Name property displayed, one would do the following:

ls | select -Property Name

This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm).

ls | select -Property Name | gm

So, to expand the object to be that of the type of property you're looking at, you can do the following:

ls | select -ExpandProperty Name

In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:

$objects = ls | select -ExpandProperty Name

How do I check whether a file exists without exceptions?

Unlike isfile(), exists() will return True for directories. So depending on if you want only plain files or also directories, you'll use isfile() or exists(). Here is some simple REPL output:

>>> os.path.isfile("/etc/password.txt")
True
>>> os.path.isfile("/etc")
False
>>> os.path.isfile("/does/not/exist")
False
>>> os.path.exists("/etc/password.txt")
True
>>> os.path.exists("/etc")
True
>>> os.path.exists("/does/not/exist")
False

1030 Got error 28 from storage engine

Drop the problem database, then reboot mysql service (sudo service mysql restart, for example).

Ajax Success and Error function failure

One also may use the following to catch the errors:

$.ajax({
    url: url, 
    success: function (data) {
        // Handle success here
        $('#editor-content-container').html(data);
        $('#editor-container').modal('show');
    },
    cache: false
}).fail(function (jqXHR, textStatus, error) {
    // Handle error here
    $('#editor-content-container').html(jqXHR.responseText);
    $('#editor-container').modal('show');
});

The APK file does not exist on disk

Go to Build option on the top bar of android studio>create 'Build APK(s)', once build has created, open the folder where it has available(app\build\outputs\apk) then close the folder, that's all....then try to install the app.

How to have stored properties in Swift, the same way I had on Objective-C?

The solution pointed out by jou doesn't support value types, this works fine with them as well

Wrappers

import ObjectiveC

final class Lifted<T> {
    let value: T
    init(_ x: T) {
        value = x
    }
}

private func lift<T>(x: T) -> Lifted<T>  {
    return Lifted(x)
}

func setAssociatedObject<T>(object: AnyObject, value: T, associativeKey: UnsafePointer<Void>, policy: objc_AssociationPolicy) {
    if let v: AnyObject = value as? AnyObject {
        objc_setAssociatedObject(object, associativeKey, v,  policy)
    }
    else {
        objc_setAssociatedObject(object, associativeKey, lift(value),  policy)
    }
}

func getAssociatedObject<T>(object: AnyObject, associativeKey: UnsafePointer<Void>) -> T? {
    if let v = objc_getAssociatedObject(object, associativeKey) as? T {
        return v
    }
    else if let v = objc_getAssociatedObject(object, associativeKey) as? Lifted<T> {
        return v.value
    }
    else {
        return nil
    }
}

A possible Class extension (Example of usage):

extension UIView {

    private struct AssociatedKey {
        static var viewExtension = "viewExtension"
    }

    var referenceTransform: CGAffineTransform? {
        get {
            return getAssociatedObject(self, associativeKey: &AssociatedKey.viewExtension)
        }

        set {
            if let value = newValue {
                setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.viewExtension, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}

This is really such a great solution, I wanted to add another usage example that included structs and values that are not optionals. Also, the AssociatedKey values can be simplified.

struct Crate {
    var name: String
}

class Box {
    var name: String

    init(name: String) {
        self.name = name
    }
}

extension UIViewController {

    private struct AssociatedKey {
        static var displayed:   UInt8 = 0
        static var box:         UInt8 = 0
        static var crate:       UInt8 = 0
    }

    var displayed: Bool? {
        get {
            return getAssociatedObject(self, associativeKey: &AssociatedKey.displayed)
        }

        set {
            if let value = newValue {
                setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.displayed, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }

    var box: Box {
        get {
            if let result:Box = getAssociatedObject(self, associativeKey: &AssociatedKey.box) {
                return result
            } else {
                let result = Box(name: "")
                self.box = result
                return result
            }
        }

        set {
            setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.box, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var crate: Crate {
        get {
            if let result:Crate = getAssociatedObject(self, associativeKey: &AssociatedKey.crate) {
                return result
            } else {
                let result = Crate(name: "")
                self.crate = result
                return result
            }
        }

        set {
            setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.crate, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

Creating a generic method in C#

You can use sort of Maybe monad (though I'd prefer Jay's answer)

public class Maybe<T>
{
    private readonly T _value;

    public Maybe(T value)
    {
        _value = value;
        IsNothing = false;
    }

    public Maybe()
    {
        IsNothing = true;
    }

    public bool IsNothing { get; private set; }

    public T Value
    {
        get
        {
            if (IsNothing)
            {
                throw new InvalidOperationException("Value doesn't exist");
            }
            return _value;
        }
    }

    public override bool Equals(object other)
    {
        if (IsNothing)
        {
            return (other == null);
        }
        if (other == null)
        {
            return false;
        }
        return _value.Equals(other);
    }

    public override int GetHashCode()
    {
        if (IsNothing)
        {
            return 0;
        }
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        if (IsNothing)
        {
            return "";
        }
        return _value.ToString();
    }

    public static implicit operator Maybe<T>(T value)
    {
        return new Maybe<T>(value);
    }

    public static explicit operator T(Maybe<T> value)
    {
        return value.Value;
    }
}

Your method would look like:

    public static Maybe<T> GetQueryString<T>(string key) where T : IConvertible
    {
        if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
        {
            string value = HttpContext.Current.Request.QueryString[key];

            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                //Could not convert.  Pass back default value...
                return new Maybe<T>();
            }
        }

        return new Maybe<T>();
    }

Autoplay audio files on an iPad with HTML5

As of iOS 4.2.1, neither the fake click nor the .load() trick will work to autoplay audio on any iOS device. The only option I know of is to have the user actually perform a click action and begin playback in the click event handler without wrapping the .play() call in anything asynchronous (ajax, setTimeout, etc).

Someone please tell me if I'm mistaken. I had working loopholes for both iPad and iPhone before the most recent update, and all of them look like they've been closed.

Omitting the second expression when using the if-else shorthand

If you're not doing the else, why not do:

if (x==2) doSomething();

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Virtual box version 4.3.28 worked with Genymotion 2.5.2 for me. Nothing else seemed to work.

Why can't overriding methods throw exceptions broader than the overridden method?

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

Example:

class Super {
    public void throwCheckedExceptionMethod() throws IOException {
        FileReader r = new FileReader(new File("aFile.txt"));
        r.close();
    }
}

class Sub extends Super {    
    @Override
    public void throwCheckedExceptionMethod() throws FileNotFoundException {
        // FileNotFoundException extends IOException
        FileReader r = new FileReader(new File("afile.txt"));
        try {
            // close() method throws IOException (that is unhandled)
            r.close();
        } catch (IOException e) {
        }
    }
}

class Sub2 extends Sub {
    @Override
    public void throwCheckedExceptionMethod() {
        // Overriding method can throw no exception
    }
}

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

jQuery convert line breaks to br (nl2br equivalent)

to improve @Luca Filosofi's accepted answer,

if needed, changing the beginning clause of this regex to be /([^>[\s]?\r\n]?) will also ingore the cases where the newline comes after a tag AND some whitespace, instead of just a tag immediately followed by a newline

Compare object instances for equality by their attributes

Depending on your specific case, you could do:

>>> vars(x) == vars(y)
True

See Python dictionary from an object's fields

Xml serialization - Hide null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

How to use glob() to find files recursively?

Here is a solution that will match the pattern against the full path and not just the base filename.

It uses fnmatch.translate to convert a glob-style pattern into a regular expression, which is then matched against the full path of each file found while walking the directory.

re.IGNORECASE is optional, but desirable on Windows since the file system itself is not case-sensitive. (I didn't bother compiling the regex because docs indicate it should be cached internally.)

import fnmatch
import os
import re

def findfiles(dir, pattern):
    patternregex = fnmatch.translate(pattern)
    for root, dirs, files in os.walk(dir):
        for basename in files:
            filename = os.path.join(root, basename)
            if re.search(patternregex, filename, re.IGNORECASE):
                yield filename

log4j:WARN No appenders could be found for logger (running jar file, not web app)

Move Your log4j.properties file into the src folder. Open Windows explorer, browse to the directory where your project resides in. Browse to bin directory and delete all the folders with in it.

Now in eclipse click project---->clean---->OK

This would force it to build the project again,all the contents delete from bin directory will be recreated.

I took while to figure this out. At times directly clicking clean doesn't work

How do I make background-size work in IE?

There is a good polyfill for that: louisremi/background-size-polyfill

To quote the documentation:

Upload backgroundsize.min.htc to your website, along with the .htaccess that will send the mime-type required by IE (Apache only — it's built in nginx, node and IIS).

Everywhere you use background-size in your CSS, add a reference to this file.

.selector { 
    background-size: cover;
    /* The url is relative to the document, not to the css file! */
    /* Prefer absolute urls to avoid confusion. */
    -ms-behavior: url(/backgroundsize.min.htc);
}

Upload file to FTP using C#

public void UploadFtpFile(string folderName, string fileName)
{

    FtpWebRequest request;

    string folderName; 
    string fileName;
    string absoluteFileName = Path.GetFileName(fileName);

    request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/{2}", "127.0.0.1", folderName, absoluteFileName))) as FtpWebRequest;
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UseBinary = 1;
    request.UsePassive = 1;
    request.KeepAlive = 1;
    request.Credentials =  new NetworkCredential(user, pass);
    request.ConnectionGroupName = "group"; 

    using (FileStream fs = File.OpenRead(fileName))
    {
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        fs.Close();
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(buffer, 0, buffer.Length);
        requestStream.Flush();
        requestStream.Close();
    }
}

How to use

UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img");

use this in your foreach

and you only need to create folder one time

to create a folder

request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/", "127.0.0.1", "testFolder"))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse();

How to add a button dynamically in Android?

Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);

How can I get the assembly file version

When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used

versionlabel.Text = "Version " + Application.ProductVersion;

This approach requires a reference to System.Windows.Forms.

Python check if website exists

You can simply use stream method to not download the full file. As in latest Python3 you won't get urllib2. It's best to use proven request method. This simple function will solve your problem.

def uri_exists(uri):
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        return True
    else:
        return False

Node/Express file upload

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

npm install --save multer


in app.js

    var multer  =   require('multer');
    var storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './public/uploads');
      },
      filename: function (req, file, callback) {
        console.log(file);
        callback(null, Date.now()+'-'+file.originalname)
      }
    });

    var upload = multer({storage: storage}).single('photo');

    router.route("/storedata").post(function(req, res, next){

        upload(req, res, function(err) {
          if(err) {
            console.log('Error Occured');
            return;
          }
          var userDetail = new mongoOp.User({
            'name':req.body.name,
            'email':req.body.email,
            'mobile':req.body.mobile,
            'address':req.body.address
          });

          console.log(req.file);

          res.end('Your File Uploaded');
          console.log('Photo Uploaded');

          userDetail.save(function(err,result){
          if (err) {
            return console.log(err)
          }
          console.log('saved to database') 
        })
      })

      res.redirect('/')

    });

How to make a dropdown readonly using jquery?

As @Kanishka said , if we disable a form element it will not be submitted . I have created a snippet for this problem . When the select element is disabled it creates a hidden input field and store the value . When it is enabled it delete the created hidden input fields .

More info

_x000D_
_x000D_
jQuery(document).ready(function($) {_x000D_
  var $dropDown = $('#my-select'),_x000D_
    name = $dropDown.prop('name'),_x000D_
    $form = $dropDown.parent('form');_x000D_
_x000D_
  $dropDown.data('original-name', name); //store the name in the data attribute _x000D_
_x000D_
  $('#toggle').on('click', function(event) {_x000D_
    if ($dropDown.is('.disabled')) {_x000D_
      //enable it _x000D_
      $form.find('input[type="hidden"][name=' + name + ']').remove(); // remove the hidden fields if any_x000D_
      $dropDown.removeClass('disabled') //remove disable class _x000D_
        .prop({_x000D_
          name: name,_x000D_
          disabled: false_x000D_
        }); //restore the name and enable _x000D_
    } else {_x000D_
      //disable it _x000D_
      var $hiddenInput = $('<input/>', {_x000D_
        type: 'hidden',_x000D_
        name: name,_x000D_
        value: $dropDown.val()_x000D_
      });_x000D_
      $form.append($hiddenInput); //append the hidden field with same name and value from the dropdown field _x000D_
      $dropDown.addClass('disabled') //disable class_x000D_
        .prop({_x000D_
          'name': name + "_1",_x000D_
          disabled: true_x000D_
        }); //change name and disbale _x000D_
    }_x000D_
  });_x000D_
});
_x000D_
/*Optional*/_x000D_
_x000D_
select.disabled {_x000D_
  color: graytext;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form action="#" name="my-form">_x000D_
  <select id="my-select" name="alpha">_x000D_
    <option value="A">A</option>_x000D_
    <option value="B">B</option>_x000D_
    <option value="C">C</option>_x000D_
  </select>_x000D_
</form>_x000D_
<br/>_x000D_
<button id="toggle">toggle enable/disable</button>
_x000D_
_x000D_
_x000D_

Encode a FileStream to base64 with c#

An easy one as an extension method

public static class Extensions
{
    public static Stream ConvertToBase64(this Stream stream)
    {
        byte[] bytes;
        using (var memoryStream = new MemoryStream())
        {
            stream.CopyTo(memoryStream);
            bytes = memoryStream.ToArray();
        }

        string base64 = Convert.ToBase64String(bytes);
        return new MemoryStream(Encoding.UTF8.GetBytes(base64));
    }
}

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

how to break the _.each function in underscore.js

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

Permission denied for relation

Posting Ron E answer for grant privileges on all tables as it might be useful to others.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

.ssh/config file for windows (git)

These instructions work fine in Linux. In Windows, they are not working for me today.

I found an answer that helps for me, maybe this will help OP. I kissed a lot of frogs trying to solve this. You need to add your new non-standard-named key file with "ssh-add"! Here's instruction for the magic bullet: Generating a new SSH key and adding it to the ssh-agent. Once you know the magic search terms are "add key with ssh-add in windows" you find plenty of other links.

If I were using Windows often, I'd find some way to make this permanent. https://github.com/raeesbhatti/ssh-agent-helper.

The ssh key agent looks for default "id_rsa" and other keys it knows about. The key you create with a non-standard name must be added to the ssh key agent.

First, I start the key agent in the Git BASH shell:

$ eval $(ssh-agent -s)
Agent pid 6276

$ ssh-add ~/.ssh/Paul_Johnson-windowsvm-20180318
Enter passphrase for /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318:
Identity added: /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318 (/c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318)

Then I change to the directory where I want to clone the repo

$ cd ~/Documents/GIT/

$ git clone [email protected]:test/spr2018.git
Cloning into 'spr2018'...
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.

I fought with this for a long long time.

Here are other things I tried along the way

At first I was certain it is because of file and folder permissions. On Linux, I have seen .ssh settings rejected if the folder is not set at 700. Windows has 711. In Windows, I cannot find any way to make permissions 700.

After fighting with that, I think it must not be the problem. Here's why. If the key is named "id_rsa" then git works! Git is able to connect to server. However, if I name the key file something else, and fix the config file in a consistent way, no matter what, then git fails to connect. That makes me think permissions are not the problem.

A thing you can do to debug this problem is to watch verbose output from ssh commands using the configured key.

In the git bash shell, run this

$ ssh -T git@name-of-your-server

Note, the user name should be "git" here. If your key is set up and the config file is found, you see this, as I just tested in my Linux system:

$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!

On the other hand, in Windows I have same trouble you do before applying "ssh-add". It wants git's password, which is always a fail.

$ ssh -T [email protected]
[email protected]'s password:

Again, If i manually copy my key to "id_rsa" and "id_rsa.pub", then this works fine. After running ssh-add, observe the victory in Windows Git BASH:

$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!

You would hear the sound of me dancing with joy if you were here.

To figure out what was going wrong, you can I run 'ssh' with "-Tvv"

In Linux, I see this when it succeeds:

debug1: Offering RSA public key: pauljohn@pols124
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp SHA256:bCoIWSXE5fkOID4Kj9Axt2UOVsRZz9JW91RQDUoasVo
debug1: Authentication succeeded (publickey).

In Windows, when this fails, I see it looking for default names:

debug1: Found key in /c/Users/pauljohn32/.ssh/known_hosts:1
debug2: set_newkeys: mode 1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 4294967296 blocks
debug2: key: /c/Users/pauljohn32/.ssh/id_rsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_dsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ecdsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ed25519 (0x0)
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_rsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_dsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ed25519
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
[email protected]'s password:

That was the hint I needed, it says it finds my ~/.ssh/config file but never tries the key I want it to try.

I only use Windows once in a long while and it is frustrating. Maybe the people who use Windows all the time fix this and forget it.

Interview question: Check if one string is a rotation of other string

Another python example (based on THE answer):

def isrotation(s1,s2):
     return len(s1)==len(s2) and s1 in 2*s2

OSX - How to auto Close Terminal window after the "exit" command executed.

in Terminal.app

Preferences > Profiles > (Select a Profile) > Shell.

on 'When the shell exits' chosen 'Close the window'

How to view file diff in git before commit

The best way I found, aside of using a dedicated commit GUI, is to use git difftool -d - This opens your diff tool in directory comparison mode, comparing HEAD with current dirty folder.

Return the most recent record from ElasticSearch index

If you are using python elasticsearch5 module or curl:

  1. make sure each document that gets inserted has
    • a timestamp field that is type datetime
    • and you are monotonically increasing the timestamp value for each document
  2. from python you do

    es = elasticsearch5.Elasticsearch('my_host:my_port')
    es.search(
        index='my_index', 
        size=1,
        sort='my_timestamp:desc'
        )
    

If your documents are not inserted with any field that is of type datetime, then I don't believe you can get the N "most recent".

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Plotting a 3d cube, a sphere and a vector in Matplotlib

For drawing just the arrow, there is an easier method:-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

quiver(X, Y, Z, U, V, W, **kwargs)

Arguments:

X, Y, Z: The x, y and z coordinates of the arrow locations

U, V, W: The x, y and z components of the arrow vectors

The arguments could be array-like or scalars.

Keyword arguments:

length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes

arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3

pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’

normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.

How to get just the parent directory name of a specific file

    //get the parentfolder name
    File file = new File( System.getProperty("user.dir") + "/.");
    String parentPath = file.getParentFile().getName();

Regular expression for extracting tag attributes

Update (2020), Gyum Fox proposes https://regex101.com/r/U9Yqqg/2 (note regex101.com did not exist when I wrote originally this answer)

(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|\s*\/?[>"']))+.)["']?

Applied to:

<a href=test.html class=xyz>
<a href="test.html" class="xyz">
<a href='test.html' class="xyz">
<script type="text/javascript" defer async id="something" onload="alert('hello');"></script>
<img src="test.png">
<img src="a test.png">
<img src=test.png />
<img src=a test.png />
<img src=test.png >
<img src=a test.png >
<img src=test.png alt=crap >
<img src=a test.png alt=crap >

Original answer (2008): If you have an element like

<name attribute=value attribute="value" attribute='value'>

this regex could be used to find successively each attribute name and value

(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?

Applied on:

<a href=test.html class=xyz>
<a href="test.html" class="xyz">
<a href='test.html' class="xyz">

it would yield:

'href' => 'test.html'
'class' => 'xyz'

Note: This does not work with numeric attribute values e.g. <div id="1"> won't work.

Edited: Improved regex for getting attributes with no value and values with " ' " inside.

([^\r\n\t\f\v= '"]+)(?:=(["'])?((?:.(?!\2?\s+(?:\S+)=|\2))+.)\2?)?

Applied on:

<script type="text/javascript" defer async id="something" onload="alert('hello');"></script>

it would yield:

'type' => 'text/javascript'
'defer' => ''
'async' => ''
'id' => 'something'
'onload' => 'alert(\'hello\');'

Convert ndarray from float64 to integer

While astype is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr in the following examples:

>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1.,  2.,  3.,  4.])

The int* functions from NumPy

>>> np.int64(arr)
array([1, 2, 3, 4])

>>> np.int_(arr)
array([1, 2, 3, 4])

The NumPy *array functions themselves:

>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])

The astype method (that was already mentioned but for completeness sake):

>>> arr.astype(int)
array([1, 2, 3, 4])

Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32 or np.int64.

Change the color of a checked menu item in a navigation drawer

I believe app:itemBackground expects a drawable. So follow the steps below :

Make a drawable file highlight_color.xml with following contents :

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <solid android:color="YOUR HIGHLIGHT COLOR"/>
</shape>

Make another drawable file nav_item_drawable.xml with following contents:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/highlight_color" android:state_checked="true"/>
</selector>

Finally add app:itemBackground tag in the NavView :

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
app:itemBackground="@drawable/nav_item_drawable"
app:menu="@menu/menu_drawer">

here the highlight_color.xml file defines a solid color drawable for the background. Later this color drawable is assigned to nav_item_drawable.xml selector.

This worked for me. Hopefully this will help.

********************************************** UPDATED **********************************************

Though the above mentioned answer gives you fine control over some properties, but the way I am about to describe feels more SOLID and is a bit COOLER.

So what you can do is, you can define a ThemeOverlay in the styles.xml for the NavigationView like this :

    <style name="ThemeOverlay.AppCompat.navTheme">

        <!-- Color of text and icon when SELECTED -->
        <item name="colorPrimary">@color/color_of_your_choice</item> 

        <!-- Background color when SELECTED -->
        <item name="colorControlHighlight">@color/color_of_your_choice</item> 

    </style>

now apply this ThemeOverlay to app:theme attribute of NavigationView, like this:

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:theme="@style/ThemeOverlay.AppCompat.navTheme"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/menu_drawer">

I hope this will help.

Triggering a checkbox value changed event in DataGridView

"EditingControlShowing" event doesn't fire on checkbox value change. Because display style of the checkbox cell doesn't not change.

The workaround i have used is as below. (I have used CellContentClick event)

    private void gGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (string.Compare(gGridView1.CurrentCell.OwningColumn.Name, "CheckBoxColumn") == 0)
        {
            bool checkBoxStatus = Convert.ToBoolean(gGridView1.CurrentCell.EditedFormattedValue);
            //checkBoxStatus gives you whether checkbox cell value of selected row for the
            //"CheckBoxColumn" column value is checked or not. 
            if(checkBoxStatus)
            {
                //write your code
            }
            else
            {
               //write your code
            }
        }
    }

The above has worked for me. Please let me know if need more help.

How to count digits, letters, spaces for a string in Python?

INPUT :

1

26

sadw96aeafae4awdw2 wd100awd

import re

a=int(input())
for i in range(a):
    b=int(input())
    c=input()

    w=re.findall(r'\d',c)
    x=re.findall(r'\d+',c)
    y=re.findall(r'\s+',c)
    z=re.findall(r'.',c)
    print(len(x))
    print(len(y))
    print(len(z)-len(y)-len(w))

OUTPUT :

4

1

19

The four digits are 96, 4, 2, 100 The number of spaces = 1 number of letters = 19

Asynchronous Requests with Python requests

You can use httpx for that.

import httpx

async def get_async(url):
    async with httpx.AsyncClient() as client:
        return await client.get(url)

urls = ["http://google.com", "http://wikipedia.org"]

# Note that you need an async context to use `await`.
await asyncio.gather(*map(get_async, urls))

if you want a functional syntax, the gamla lib wraps this into get_async.

Then you can do


await gamla.map(gamla.get_async(10))(["http://google.com", "http://wikipedia.org"])

The 10 is the timeout in seconds.

(disclaimer: I am its author)

Class has no objects member

First install pylint-django using following command

$ pip install pylint-django

Then run the second command as follows:

$ pylint test_file.py --load-plugins pylint_django

--load-plugins pylint_django is necessary for correctly review a code of django

SQL statement to select all rows from previous day

subdate(now(),1) will return yesterdays timestamp The below code will select all rows with yesterday's timestamp

Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)

Python: For each list element apply a function across the list

You can do this using list comprehensions and min() (Python 3.0 code):

>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)

Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division so that 1/5 correctly equals 0.2 instead of 0.

Bootstrap Modal sitting behind backdrop

None of the answers worked well enough for me. The problem appeared to lie where the modal windows needs to be outside of the body.and it is not best

So this code done the job just prefectly:

_x000D_
_x000D_
$('.modal ').insertAfter($('body'));
_x000D_
_x000D_
_x000D_

$('#product_' + product_id + ' .modal ').insertAfter($('body'));

How can I import Swift code to Objective-C?

Checkout the pre-release notes about Swift and Objective C in the same project

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_75

You should be importing

#import "SCLAlertView-Swift.h"

Adding Permissions in AndroidManifest.xml in Android Studio?

It's quite simple.

All you need to do is:

  • Right click above application tag and click on Generate
  • Click on XML tag
  • Click on user-permission
  • Enter the name of your permission.

Regex to remove letters, symbols except numbers

Use /[^0-9.,]+/ if you want floats.

Easy login script without database

It's not an ideal solution but here's a quick and dirty example that shows how you could store login info in the PHP code:

<?php
session_start();

$userinfo = array(
                'user1'=>'password1',
                'user2'=>'password2'
                );

if(isset($_GET['logout'])) {
    $_SESSION['username'] = '';
    header('Location:  ' . $_SERVER['PHP_SELF']);
}

if(isset($_POST['username'])) {
    if($userinfo[$_POST['username']] == $_POST['password']) {
        $_SESSION['username'] = $_POST['username'];
    }else {
        //Invalid Login
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Login</title>
    </head>
    <body>
        <?php if($_SESSION['username']): ?>
            <p>You are logged in as <?=$_SESSION['username']?></p>
            <p><a href="?logout=1">Logout</a></p>
        <?php endif; ?>
        <form name="login" action="" method="post">
            Username:  <input type="text" name="username" value="" /><br />
            Password:  <input type="password" name="password" value="" /><br />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

How can I detect keydown or keypress event in angular.js?

You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.

The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):

var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
             // this next line will convert the string
             // function name into an actual function
             var functionToCall = scope.$eval(attrs.ngKeydown);
             elem.on('keydown', function(e){
                  // on the keydown event, call my function
                  // and pass it the keycode of the key
                  // that was pressed
                  // ex: if ENTER was pressed, e.which == 13
                  functionToCall(e.which);
             });
        }
    };
});

The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:

<input type="text" on-keydown="onKeydown">

And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:

$scope.onKeydown = function(keycode){
    // do something with the keycode
}

Hopefully that helps either you or someone else who wants to know

How can I check if a file exists in Perl?

Use:

if (-f $filePath)
{
  # code
}

-e returns true even if the file is a directory. -f will only return true if it's an actual file

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

std::string to float or double

If you don't want to drag in all of boost, go with strtod(3) from <cstdlib> - it already returns a double.

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;

int main()  {
    std::string  num = "0.6";
    double temp = ::strtod(num.c_str(), 0);

    cout << num << " " << temp << endl;
    return 0;
}

Outputs:

$ g++ -o s s.cc
$ ./s
0.6 0.6
$

Why atof() doesn't work ... what platform/compiler are you on?

Android open camera from button

I have created a libray for pick image from camera or galley and cropping also

Try this,

ImagePro.Java

public class ImagePro
{
    public static String TAG = "ImagePro";
    Activity activity;
    Uri mImageCaptureUri;
    public static int CAMERA_CODE = 64;
    public static int GALLERY_CODE = 74;
    public static int CROPPING_CODE = 84;
    private final static int REQUEST_PERMISSION_REQ_CODE = 704;

    public ImagePro(Activity activity) {

        this.activity = activity;
        this.outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
        }
    }

    private void LogToast(String message) {

        try {
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.d(TAG, message);
    }

    private void Toast(String message) {

        try {
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Log(String message) {

        Log.d(TAG, message);
    }

    /**
     * This function return captured image path
     *
     * @param requestCode on activity result requestCode
     * @param resultCode on activity result resultCode
     * @param intent on activity result intent
     * @return ImageDetails values
     */
    public ImageDetails getImagePath(int requestCode, int resultCode, Intent intent) {

        ImageDetails imageDetails = new ImageDetails();

        if(resultCode == Activity.RESULT_OK) {

            if(requestCode == CAMERA_CODE) {
                imageDetails.setUri(mImageCaptureUri);
                imageDetails.setPath(mImageCaptureUri.getPath());
                Bitmap bitmap = null;

                try {
                    bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), mImageCaptureUri);
                } catch (IOException e) {
                    LogToast(e.getMessage());
                    e.printStackTrace();
                }
                imageDetails.setBitmap(bitmap);
                imageDetails.setFile(new File(mImageCaptureUri.getPath()));

            } else if(requestCode == GALLERY_CODE) {

                Uri uri = intent.getData();

                imageDetails.setUri(uri);
                Bitmap bitmap = null;

                try {
                    bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
                } catch (IOException e) {
                    LogToast(e.getMessage());
                    e.printStackTrace();
                }

                imageDetails.setBitmap(bitmap);
                imageDetails.setFile(new File(uri.getPath()));
                imageDetails.setPath(uri.getPath());

            } else if(requestCode == CROPPING_CODE) {
                try {
                    if(outPutFile.exists()){

                        imageDetails.setUri(Uri.fromFile(outPutFile));
                        imageDetails.setFile(outPutFile);
                        imageDetails.setPath(outPutFile.getPath());
                        Bitmap photo = decodeFile(outPutFile);
                        imageDetails.setBitmap(photo);
                    }
                    else {
                        LogToast("Error while save image");
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                    LogToast(e.getMessage());
                }
            }

        } else {
            LogToast("user cancelled.");
        }

        return imageDetails;
    }

    /**
     * Open image pick dialog.<br/>
     * CAMERA_CODE</br>
     * GALLERY_CODE
     */
    public void openImagePickOption() {

        final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {

                if (items[item].equals("Capture Photo")) {

                    captureImage();

                } else if (items[item].equals("Choose from Gallery")) {

                    pickImage();

                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    /**
     * decode from file to bitmap
     * @param f file
     * @return Bitmap data
     */
    private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 512;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {

            Log(e.getMessage());
        }
        return null;
    }

    /**
     * Capture image using camera <br/>
     * REQUEST_CODE = ImagePro.CAMERA_CODE
     */
    public void captureImage() {

        if(activity != null) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
            mImageCaptureUri = Uri.fromFile(f);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
            activity.startActivityForResult(intent, CAMERA_CODE);

        } else {

            LogToast("Activity not assigned");
        }
    }

    /**
     * pick image from gallery
     */
    public void pickImage() {

        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(i, GALLERY_CODE);
    }

    /**
     * cropping the uri image
     * @param uri - open cropping dialog using the uri data
     */
    public void croppingImage(Uri uri) {

        CroppingIMG(uri);
    }

    int CROP_IMG_X=512;
    int CROP_IMG_Y=512;

    public void croppingImage(Uri uri, int cropX, int cropY) {

        CROP_IMG_X = cropX;
        CROP_IMG_Y = cropY;

        CroppingIMG(uri);
    }

    File outPutFile=null;

    private void CroppingIMG(Uri uri) {

        final ArrayList<CroppingOption> cropOptions = new ArrayList<>();

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");

        List<ResolveInfo> list = activity.getPackageManager().queryIntentActivities( intent, 0 );
        int size = list.size();
        if (size == 0) {
            LogToast("Can't find image croping app");
        } else {
            intent.setData(uri);
            intent.putExtra("outputX", CROP_IMG_X);
            intent.putExtra("outputY", CROP_IMG_Y);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);

            //Create output file here
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));

            if (size == 1) {
                Intent i   = new Intent(intent);
                ResolveInfo res = list.get(0);

                i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                activity.startActivityForResult(i, CROPPING_CODE);
            } else {
                for (ResolveInfo res : list) {
                    final CroppingOption co = new CroppingOption();

                    co.title = activity.getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                    co.icon = activity.getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                    co.appIntent = new Intent(intent);
                    co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                    cropOptions.add(co);
                }

                CropingOptionAdapter adapter = new CropingOptionAdapter(activity.getApplicationContext(), cropOptions);

                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setTitle("Choose Cropping App");
                builder.setCancelable(false);
                builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                    public void onClick( DialogInterface dialog, int item ) {
                        activity.startActivityForResult( cropOptions.get(item).appIntent, CROPPING_CODE);
                    }
                });

                builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel( DialogInterface dialog ) {

                        if (mImageCaptureUri != null ) {
                            activity.getContentResolver().delete(mImageCaptureUri, null, null );
                            mImageCaptureUri = null;
                        }
                    }
                } );

                AlertDialog alert = builder.create();
                alert.show();
            }
        }
    }

    /**
     * Capture image using camera<br/>
     * REQUEST_CODE = User defined code<br/>
     * <br/>
     * @param iRequestCode User defined code
     */
    public void captureImage(int iRequestCode) {

        CAMERA_CODE = iRequestCode;
        captureImage();
    }

    /**
     * get path, bitmap, file and uri from image details object
     */
    public class ImageDetails {

        String path="";
        Bitmap bitmap=null;
        File file=null;
        Uri uri=null;

        public Uri getUri() {
            return uri;
        }

        public void setUri(Uri uri) {
            this.uri = uri;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public Bitmap getBitmap() {
            return bitmap;
        }

        public void setBitmap(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        public File getFile() {
            return file;
        }

        public void setFile(File file) {
            this.file = file;
        }
    }

    /**
     * Created by DP on 7/12/2016.
     */
    public class CroppingOption {
        public CharSequence title;
        public Drawable icon;
        public Intent appIntent;
    }

    public class CropingOptionAdapter extends ArrayAdapter {
        private ArrayList<CroppingOption> mOptions;
        private LayoutInflater mInflater;

        public CropingOptionAdapter(Context context, ArrayList<CroppingOption> options) {

            super(context, R.layout.croping_selector, options);
            mOptions  = options;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup group) {
            if (convertView == null)
                convertView = mInflater.inflate(R.layout.croping_selector, null);

            CroppingOption item = mOptions.get(position);

            if (item != null) {
                ((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
                ((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);

                return convertView;
            }

            return null;
        }
    }
}

MainActivity.java

ImagePro imagePro;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imagePro = new ImagePro(this);
    }

    public void onClickUploadImageButton(View view) {

        imagePro.openImagePickOption();
    }

onActivityResult

if(requestCode == CAMERA_CODE && resultCode == RESULT_OK) {

            imageDetails = imagePro.getImagePath(CAMERA_CODE, RESULT_OK, data);
            ivCrop.setImageBitmap(imageDetails.getBitmap());
//imageDetails.getPath(), imageDetails.getBitmap(), imageDetails.getUri(), imageDetails.getFile
        }

How to check if the URL contains a given string?

like so:

    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
            {
                 alert("your url contains the name franky");
            }
        });
    </script>

display HTML page after loading complete

Hide the body initially, and then show it with jQuery after it has loaded.

body {
    display: none;
}

$(function () {
    $('body').show();
}); // end ready

Also, it would be best to have $('body').show(); as the last line in your last and main .js file.

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

How to make a variadic macro (variable number of arguments)

__VA_ARGS__ is the standard way to do it. Don't use compiler-specific hacks if you don't have to.

I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.