Programs & Examples On #Binomial coefficients

Convert an integer to a float number

Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

Which means that you need to use float64(integer_value).

Android: How to detect double-tap?

you can implement double-tap using the GestureDetectorCompat class. in this sample when double-tap on textview you can do your logic.

public class MainActivity extends AppCompatActivity {

GestureDetectorCompat gestureDetectorCompat;
TextView textElement;

@Override
protected void onCreate(Bundle savedInstanceState) { 
    .....
    textElement = findViewById(R.id.textElement);
    gestureDetectorCompat = new GestureDetectorCompat(this, new MyGesture());
    textElement.setOnTouchListener(onTouchListener);

}

 View.OnTouchListener onTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        gestureDetectorCompat.onTouchEvent(event);
        return true;
    }
};
    class MyGesture extends GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        // whatever on double click
        return true;
    }
}

Execute command on all files in a directory

I'm doing this on my raspberry pi from the command line by running:

for i in *;do omxplayer "$i";done

PHP: cannot declare class because the name is already in use

Class Parent cannot be declared because it is PHP reserved keyword so in effect it's already in use

Shorter syntax for casting from a List<X> to a List<Y>?

If X can really be cast to Y you should be able to use

List<Y> listOfY = listOfX.Cast<Y>().ToList();

Some things to be aware of (H/T to commenters!)

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

You need to write a little PHP code. When user first click tab you can check is he like the page or not. Below is the sample code

include_once("facebook.php");

    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => FACEBOOK_APP_ID,
      'secret' => FACEBOOK_SECRET,
      'cookie' => true,
    ));

$signed_request = $facebook->getSignedRequest();

// Return you the Page like status
$like_status = $signed_request["page"]["liked"];

if($like_status)
{
    echo 'User Liked the page';
    // Place some content you wanna show to user

}else{
    echo 'User do not liked the page';
    // Place some content that encourage user to like the page
}

How to split CSV files as per number of rows specified?

I have a one-liner answer (this example gives you 999 lines of data and one header row per file)

cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'

https://stackoverflow.com/a/53062251/401226

How do I verify that an Android apk is signed with a release certificate?

    1. unzip apk
    1. keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk to obtain the hash md5
  • keytool -list -v -keystore clave-release.jks
  • compare the md5

https://www.eovao.com/en/a/signature%20apk%20android/3/how-to-verify-signature-of-.apk-android-archive

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Datatable select with multiple conditions

Dim dr As DataRow()


dr = dt.Select("A="& a & "and B="& b & "and C=" & c,"A",DataViewRowState.CurrentRows)

Where A,B,C are the column names where second parameter is for sort expression

How can I tell Moq to return a Task?

Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync

Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods

Few examples found in previous responses done with SetupAsync extension:

mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());

How to get a file directory path from file path?

I was playing with this and came up with an alternative.

$ VAR=/home/me/mydir/file.c

$ DIR=`echo $VAR |xargs dirname`

$ echo $DIR
/home/me/mydir

The part I liked is it was easy to extend backup the tree:

$ DIR=`echo $VAR |xargs dirname |xargs dirname |xargs dirname`

$ echo $DIR
/home

Is there a way to catch the back button event in javascript?

Use the hashchange event:

window.addEventListener("hashchange", function(e) {
  // ...
})

If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.

Move the mouse pointer to a specific position?

  1. Run a small web server on the client machine. Can be a small 100kb thing. A Python / Perl script, etc.
  2. Include a small, pre-compiled C executable that can move the mouse.
  3. Run it as a CGI-script via a simple http call, AJAX, whatever - with the coordinates you want to move the mouse to, eg:

    http://localhost:9876/cgi/mousemover?x=200&y=450

PS: For any problem, there are hundreds of excuses as to why, and how - it can't, and shouldn't - be done.. But in this infinite universe, it's really just a matter of determination - as to whether YOU will make it happen.

How to know Hive and Hadoop versions from command prompt?

You can not get hive version from command line.

You can checkout hadoop version as mentioned by Dave.

Also if you are using cloudera distribution, then look directly at the libs:

ls /usr/lib/hive/lib/ and check for hive library

hive-hwi-0.7.1-cdh3u3.jar

You can also check the compatible versions here:

http://www.cloudera.com/content/cloudera/en/documentation/cdh5/v5-1-x/CDH-Version-and-Packaging-Information/CDH-Version-and-Packaging-Information.html

Is there an equivalent of 'which' on the Windows command line?

I have created tool similar to Ned Batchelder:

Searching .dll and .exe files in PATH

While my tool is primarly for searching of various dll versions it shows more info (date, size, version) but it do not use PATHEXT (I hope to update my tool soon).

Stop an input field in a form from being submitted

The easiest thing to do would be to insert the elements with the disabled attribute.

<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />

This way you can still access them as children of the form.

Disabled fields have the downside that the user can't interact with them at all- so if you have a disabled text field, the user can't select the text. If you have a disabled checkbox, the user can't change its state.

You could also write some javascript to fire on form submission to remove the fields you don't want to submit.

What's the difference between equal?, eql?, ===, and ==?

Equality operators: == and !=

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.

"koan" == "koan" # Output: => true

The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.

"koan" != "discursive thought" # Output: => true

Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.

When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.

2 == 2.0 # Output: => true

equal?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.

Example: a = "zen" b = "zen"

a.object_id  # Output: => 20139460
b.object_id  # Output :=> 19972120

a.equal? b  # Output: => false

In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.

Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.

a = "zen"
b = a

a.object_id  # Output: => 18637360
b.object_id  # Output: => 18637360

a.equal? b  # Output: => true

eql?

In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.

Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).

"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547

The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.

Symbol.instance_method(:hash).owner  # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel

String.instance_method(:hash).owner  # Output: => String
Hash.instance_method(:hash).owner  # Output: => Hash

In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.

"zen".eql? "zen"    # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true

In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.

2 == 2.0    # Output: => true
2.eql? 2.0    # Output: => false
2.hash == 2.0.hash  # Output: => false

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.

The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:

Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/

Implicit usage of the === operator on case/when statements

This operator is also used under the hood on case/when statements. That is its most common use.

minutes = 15

case minutes
  when 10..20
    puts "match"
  else
    puts "no match"
end

# Output: match

In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:

if (10..20) === minutes
  puts "match"
else
  puts "no match"
end

Pattern matching operators: =~ and !~

The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.

The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.

"practice zazen" =~ /zen/   # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil

:zazen =~ /zen/    # Output: => 2
:zazen =~ /discursive thought/  # Output: => nil

The implementation in the Regexp class expects a string or a symbol as an argument.

/zen/ =~ "practice zazen"  # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil

In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.

puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes

Pattern-matching operators are also useful for writing shorter if statements. Example:

if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
  true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
  true
end

The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.

More info is available at this blog post.

missing private key in the distribution certificate on keychain

For person who are afraid on re-creating AppStore distribution certificate Apple documentation says:

Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the App Store nor does it affect your ability to update them.

But it affects apps for Apple Developer Enterprise ecosystem.

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I don't know if this will help, but here's the SWT FAQ question How do I use Mozilla as the Browser's underlying renderer?

Edit: Having researched this further, it sounds like this isn't possible in Eclipse 3.4, but may be slated for a later release.

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

How to add external fonts to android application

One more point in addition to the above answers. When using a font inside a fragment, the typeface instantiation should be done in the onAttach method ( override ) as given below:

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}

Reason:
There is a short span of time before a fragment is attached to an activity. If CreateFromAsset method is called before attaching fragment to an activity an error occurs.

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".

and install the package. it will resolve the issue for me.

using sql count in a case statement

Close... try:

select 
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

Finding the second highest number in array

My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.

   public static int getMax22(int[] arr){
    int max1 = arr[0];
    int max2 = arr[1];
    for (int i = 2; i < arr.length; i++){
        if (arr[i] > max2)
        {
            max2 = arr[i];
        }

        if (max2 > max1)
        {
            int temp = max1;
            max1 = max2;
            max2 = temp;
        }
    }
     return max2;
}

How can I check if string contains characters & whitespace, not just whitespace?

Simplest answer if your browser supports the trim() function

if (myString && !myString.trim()) {
    //First condition to check if string is not empty
    //Second condition checks if string contains just whitespace
}

Failed to load the JNI shared Library (JDK)

I had same problem

I resolved it by installing 64 bit JVM from

http://www.java.com/en/download/manual.jsp

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

How to disable button in React.js

very simple solution for this is by using useRef hook

const buttonRef = useRef();

const disableButton = () =>{
  buttonRef.current.disabled = true; // this disables the button
 }

<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
    Add
</button>

Similarly you can enable the button by using buttonRef.current.disabled = false

How can I access each element of a pair in a pair list?

When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0] or [1] after its name. So all you have to do to get the first element of the first element of pair is say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].

Associating enums with strings in C#

Have you considered a lookup table using a Dictionary?

enum GroupTypes
{
    TheGroup,
    TheOtherGroup
}

Dictionary<string, GroupTypes> GroupTypeLookup = new Dictionary<string, GroupTypes>();
// initialize lookup table:
GroupTypeLookup.Add("OEM", TheGroup);
GroupTypeLookup.Add("CMB", TheOtherGroup);

You can then use GroupTypeLookup.TryGetValue() to look up a string when you read it.

'npm' is not recognized as internal or external command, operable program or batch file

You might have already received a response but this might help others since I experienced the same issue recently and this is what I did:

  1. Provided a path entry to powershell. For me the path was C:\Windows\System32\WindowsPowerShell\v1.0
  2. Then I opened cmd prompt with administrative privileges and copied this

    @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin

into the cmd prompt.

  1. Next, choco install nodejs
  2. Restart and everything worked fine. Try opening cmd without admin privileges and run npm -v Cheers.

Best place to insert the Google Analytics code

Google used to recommend putting it just before the </body> tag, because the original method they provided for loading ga.js was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head> tag.

<head> will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.

As a matter of personal preference, I like to include it in the <head>, but its really a matter of preference.

Dropping Unique constraint from MySQL table

while dropping unique key we use index

ALTER TABLE tbl
DROP INDEX  unique_address;

Is there an equivalent of CSS max-width that works in HTML emails?

There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.

<!--[if gte mso 9]>
<style>
#tableForOutlook {
  width:800px;
}
</style>
<![endif]-->

<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
  <table id="tableForOutlook"><tr><td>
<![endif]-->
    <tr><td>
    [Your Content Goes Here]
    </td></tr>
<!--[if gte mso 9]>
  </td></tr></table>
<![endif]-->
<table>

How to add empty spaces into MD markdown readme on GitHub?

I'm surprised no one mentioned the HTML entities &ensp; and &emsp; which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than &nbsp;.

  1. no space
  2.  &nbsp;
  3. &ensp;
  4. &emsp;

Along with <space> and &thinsp;, these are the five entities HTML provides for horizontal white space.

Note that except for &nbsp;, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With &nbsp; it would wrap to a new line as a block even if the text before &nbsp; could fit on the previous line.

Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John&nbsp;Doe), addresses or references (see eq.&nbsp;5), breaking as a block is usually undesired.

What is Func, how and when is it used

Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.

Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2); 

So, Func is a built-in delegate which brings some functional programming features and helps reduce code verbosity.

How to SHA1 hash a string in Android?

final MessageDigest digest = MessageDigest.getInstance("SHA-1");
result = digest.digest(stringToHash.getBytes("UTF-8"));

// Another way to construct HEX, my previous post was only the method like your solution
StringBuilder sb = new StringBuilder();

for (byte b : result) // This is your byte[] result..
{
    sb.append(String.format("%02X", b));
}

String messageDigest = sb.toString();

Git: add vs push vs commit

I find this image very meaningful :

enter image description here

(from : Oliver Steele -My Git Workflow (2008) )

Select first empty cell in column F starting from row 1. (without using offset )

I just wrote this one-liner to select the first empty cell found in a column based on a selected cell. Only works on first column of selected cells. Modify as necessary

Selection.End(xlDown).Range("A2").Select

open() in Python does not create a file if it doesn't exist

My answer:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

How do I remove javascript validation from my eclipse project?

I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.

That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.

  1. Right-click your project.
  2. Navigate to: Properties ? JavaScript ? Include Path
  3. Select Source tab. (It looks identical to Java Build Path Source tab.)
  4. Expand JavaScript source folder.
  5. Highlight Excluded pattern.
  6. Press the Edit button.
  7. Press the Add button next to Exclusion patterns box.
  8. You may either type Ant-style wildcard pattern, or click Browse button to mention the JavaScript source by name.

The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope file. Do not forget to add it to your SCM.

Here is how configuration looks with jQuery files removed from validation:

Eclipse - Project Properties - JavaScript - Include Path

JQuery style display value

If you want to check the display value, https://stackoverflow.com/a/1189281/5622596 already posted the answer.

However if instead of checking whether an element has a style of style="display:none" you want to know if that element is visible. Then use .is(":visible")

For example: $('#idDetails').is(":visible");

This will be true if it is visible & false if it is not.

How to delete from multiple tables in MySQL?

Use a JOIN in the DELETE statement.

DELETE p, pa
      FROM pets p
      JOIN pets_activities pa ON pa.id = p.pet_id
     WHERE p.order > :order
       AND p.pet_id = :pet_id

Alternatively you can use...

DELETE pa
      FROM pets_activities pa
      JOIN pets p ON pa.id = p.pet_id
 WHERE p.order > :order
   AND p.pet_id = :pet_id

...to delete only from pets_activities

See this.

For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS, NOT EXISTS, IN, NOT IN and etc. But the one above where you specify from which tables to delete with an alias before the FROM clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.

jQuery: select all elements of a given class, except for a particular Id

Or take the .not() method

https://api.jquery.com/not/

$(".thisClass").not("#thisId").doAction();

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

I have a solution which is not specified here

z = {}
z.update(x) or z.update(y)

This will not update x as well as y. Performance? I don't think it will be terribly slow.

MySQL Error 1215: Cannot add foreign key constraint

when try to make foreign key when using laravel migration

like this example:

user table

    public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->TinyInteger('color_id')->unsigned();
        $table->foreign('color_id')->references('id')->on('colors');
        $table->timestamps();
    });
}

colors table

    public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('color');
        $table->timestamps();
    });
}

sometimes properties didn't work

[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

this error happened because the foreign key (type) in [user table] is deferent from primary key (type) in [colors table]

To solve this problem should change the primary key in [colors table]

$table->tinyIncrements('id');


When you use primary key $table->Increments('id');

you should use Integer as a foreign key

    $table-> unsignedInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->tinyIncrements('id');

you should use unsignedTinyInteger as a foreign key

    $table-> unsignedTinyInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->smallIncrements('id');

you should use unsignedSmallInteger as a foreign key

    $table-> unsignedSmallInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->mediumIncrements('id');

you should use unsignedMediumInteger as a foreign key

    $table-> unsignedMediumInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

How do I make the text box bigger in HTML/CSS?

If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>).

Text areas are resizable by default. If you want to disable that, just use the resize css rule:

#signin textarea {
    resize: none;
}

A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input> tags as well.

<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>

This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

document.body.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
  event.preventDefault();
  console.log('clicked ;)');
}
});

DEMO

https://jsfiddle.net/muratkezli/51rnc9ug/6/

convert string to date in sql server

Write a function

CREATE FUNCTION dbo.SAP_TO_DATETIME(@input VARCHAR(14))
RETURNS datetime
AS BEGIN
    DECLARE @ret datetime
    DECLARE @dtStr varchar(19)

    SET @dtStr = substring(@input,1,4) + '-' +  substring(@input,5,2) + '-' + substring(@input,7,2)
                + ' ' + substring(@input,9,2) + ':' + substring(@input,11,2) + ':' + substring(@input,13,2);        

    SET @ret = COALESCE(convert(DATETIME, @dtStr, 20),null);
    RETURN @ret
END

How to pass arguments to Shell Script through docker run

with this script in file.sh

#!/bin/bash
echo Your container args are: "$@"

and this Dockerfile

FROM ubuntu:14.04
COPY ./file.sh /
ENTRYPOINT ["/file.sh"]

you should be able to:

% docker build -t test .
% docker run test hello world
Your container args are: hello world

Invoke(Delegate)

It means that the delegate will run on the UI thread, even if you call that method from a background worker or thread-pool thread. UI elements have thread affinity - they only like talking directly to one thread: the UI thread. The UI thread is defined as the thread that created the control instance, and is therefore associated with the window handle. But all of that is an implementation detail.

The key point is: you would call this method from a worker thread so that you can access the UI (to change the value in a label, etc) - since you are not allowed to do that from any other thread than the UI thread.

Determine if a String is an Integer in Java

You can use Integer.parseInt() or Integer.valueOf() to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException it can throw.

It may be helpful to note that valueOf() will return an Integer object, not the primitive int.

Apply jQuery datepicker to multiple instances

When adding datepicker at runtime generated input textboxes you have to check if it already contains datepicker then first remove class hasDatepicker then apply datePicker to it.

function convertTxtToDate() {
        $('.dateTxt').each(function () {
            if ($(this).hasClass('hasDatepicker')) {
                $(this).removeClass('hasDatepicker');
            } 
             $(this).datepicker();
        });
    } 

UIScrollView scroll to bottom programmatically

In swift:

   if self.mainScroll.contentSize.height > self.mainScroll.bounds.size.height {
        let bottomOffset = CGPointMake(0, self.mainScroll.contentSize.height - self.mainScroll.bounds.size.height);
        self.mainScroll.setContentOffset(bottomOffset, animated: true)
    }

Measuring execution time of a function in C++

  • It is a very easy to use method in C++11.
  • We can use std::chrono::high_resolution_clock from header
  • We can write a method to print the method execution time in a much readable form.

For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:

Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds

The code is here:

#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

typedef high_resolution_clock Clock;
typedef Clock::time_point ClockTime;

void findPrime(long n, string file);
void printExecutionTime(ClockTime start_time, ClockTime end_time);

int main()
{
    long n = long(1E+8);  // N = 100 million

    ClockTime start_time = Clock::now();

    // Write all the prime numbers from 1 to N to the file "prime.txt"
    findPrime(n, "C:\\prime.txt"); 

    ClockTime end_time = Clock::now();

    printExecutionTime(start_time, end_time);
}

void printExecutionTime(ClockTime start_time, ClockTime end_time)
{
    auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
    auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
    auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
    auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
    auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();

    cout << "\nExecution Time: ";
    if(execution_time_hour > 0)
    cout << "" << execution_time_hour << " Hours, ";
    if(execution_time_min > 0)
    cout << "" << execution_time_min % 60 << " Minutes, ";
    if(execution_time_sec > 0)
    cout << "" << execution_time_sec % 60 << " Seconds, ";
    if(execution_time_ms > 0)
    cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
    if(execution_time_ns > 0)
    cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
}

What is Parse/parsing?

Parsing can be considered as a synonym of "Breaking down into small pieces" and then analysing what is there or using it in a modified way. In Java, Strings are parsed into Decimal, Octal, Binary, Hexadecimal, etc. It is done if your application is taking input from the user in the form of string but somewhere in your application you want to use that input in the form of an integer or of double type. It is not same as type casting. For type casting the types used should be compatible in order to caste but nothing such in parsing.

Has anyone gotten HTML emails working with Twitter Bootstrap?

I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link: http://zurb.com/ink/

Hope it helps someone.

Ninja edit: It has since been renamed to Foundation for Emails and the new link is: https://foundation.zurb.com/emails.html

Silent but deadly edit: New link https://get.foundation/emails.html

Import text file as single character string

readChar doesn't have much flexibility so I combined your solutions (readLines and paste).

I have also added a space between each line:

con <- file("/Users/YourtextFile.txt", "r", blocking = FALSE)
singleString <- readLines(con) # empty
singleString <- paste(singleString, sep = " ", collapse = " ")
close(con)

Open terminal here in Mac OS finder

There is an updated version of the very nice and slim Open Terminal Here posted by vgm64 and d0k. The change was made by james david low. He published the new version on his site. Just download OpenTerminalHere.zip, extract it, move the bundle to your Library/Scripts folder and drag it from there to your Finder toolbar.

What is special about it is that it always opens a new tab if a Terminal.app window is already open. Very useful! I also noted that the style of the button of the application better fits the Snow Leopard Finder.app style than cdto posted by redacted did.

How to retrieve data from sqlite database in android and display it in TextView

TextView tekst = (TextView) findViewById(R.id.editText1); 

You cannot cast EditText to TextView.

Get file size, image width and height before upload

A working jQuery validate example:

   $(function () {
        $('input[type=file]').on('change', function() {
            var $el = $(this);
            var files = this.files;
            var image = new Image();
            image.onload = function() {
                $el
                    .attr('data-upload-width', this.naturalWidth)
                    .attr('data-upload-height', this.naturalHeight);
            }

            image.src = URL.createObjectURL(files[0]);
        });

        jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
            var params = {
                imageminwidth: options.params.imageminwidth.split(',')
            };

            options.rules['imageminwidth'] = params;
            if (options.message) {
                options.messages['imageminwidth'] = options.message;
            }
        });

        jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
            var $el = $(element);
            if(!element.files && element.files[0]) return true;
            return parseInt($el.attr('data-upload-width')) >=  parseInt(param["imageminwidth"][0]);
        });

    } (jQuery));

Failure [INSTALL_FAILED_INVALID_APK]

There seems to be multiple reasons for this failure. For me, the issue was that in AndroidManifest file I had referenced a non-existing library(only in this particular device) using the 'uses-library' tag. After removing the library which this device did not have the apk got installed properly.

Difference between \b and \B in regex

\b is used as word boundary

word = "categorical cat"

Find all "cat" in the above word

without \b

re.findall(r'cat',word)
['cat', 'cat']

with \b

re.findall(r'\bcat\b',word)
['cat']

What could cause java.lang.reflect.InvocationTargetException?

  1. List all jar files from the Eclipse Navigator mode
  2. Verify that all the jar files are in binary mode

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP - add 1 day to date format mm-dd-yyyy

The format you've used is not recognized by strtotime(). Replace

$date = "04-15-2013";

by

$date = "04/15/2013";

Or if you want to use - then use the following line with the year in front:

$date = "2013-04-15";

nginx showing blank PHP pages

For reference, I am attaching my location block for catching files with the .php extension:

location ~ \.php$ {
    include /path/to/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}

Double-check the /path/to/fastcgi-params, and make sure that it is present and readable by the nginx user.

Error running android: Gradle project sync failed. Please fix your project and try again

It is a very common issue and the solution is very easy... Just update the SDK in SDK manager(see full instructions below)

  1. Open Android Studio and go to your SDK Manager(File>Settings>SDK Manager)
  2. Check for (-) icon in front of any package and click on it.
  3. Click OK to start updating the SDK.

Thanks for asking that question :)

MSSQL Error 'The underlying provider failed on Open'

I had a similar problem: In my test-cases executions I always got this error. I found out, that my "Distributed Transaction Service" was not started (run: services.msc -> start "Distributed Transaction Service" (best to set it to start automatic)). After I did that, it worked like a charm...

Convert True/False value read from file to boolean

If your data is from json, you can do that

import json

json.loads('true')

True

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

How to hide TabPage from TabControl

Create a new empty class and past this inside it:

using System.Windows.Forms;

namespace ExtensionMethods
{
    public static class TabPageExtensions
    {

        public static bool IsVisible(this TabPage tabPage)
        {
            if (tabPage.Parent == null)
                return false;
            else if (tabPage.Parent.Contains(tabPage))
                return true;
            else
                return false;
        }

        public static void HidePage(this TabPage tabPage)
        {
            TabControl parent = (TabControl)tabPage.Parent;
            parent.TabPages.Remove(tabPage);
        }

        public static void ShowPageInTabControl(this TabPage tabPage,TabControl parent)
        {
            parent.TabPages.Add(tabPage);
        }
    }
}

2- Add reference to ExtensionMethods namespace in your form code:

using ExtensionMethods;

3- Now you can use yourTabPage.IsVisible(); to check its visibility, yourTabPage.HidePage(); to hide it, and yourTabPage.ShowPageInTabControl(parentTabControl); to show it.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

First, if you are unfamiliar with the command line, try using phpmyadmin from your webbrowser. This will make sure you actually have a mysql database created and a username.

This is how you connect from the command line (bash):

mysql -h hostname -u username -p database_name

For example:

fabio@crunchbang ~ $ mysql -h 127.0.0.1 -u fabio -p fabiodb

Importing packages in Java

Take out the method name from in your import statement. e.g.

import Dan.Vik.disp;

becomes:

import Dan.Vik;

Select query to get data from SQL Server

You should use ExecuteScalar() (which returns the first row first column) instead of ExecuteNonQuery() (which returns the no. of rows affected).

You should refer differences between executescalar and executenonquery for more details.

Hope it helps!

How do I get the day month and year from a Windows cmd.exe script?

LANGUAGE INDEPENDENCY:

The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:

set Year=%yy%%aa%
set Month=%mm%
set Day=%dd%

Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.

Well, the full script could be:

@echo off
setlocal enabledelayedexpansion

:: Extract date fields - language dependent
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
        set v1=%%i& set v2=%%j& set v3=%%k
        if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)

        for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
            set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
    )
)

:: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
set year=%yy%%aa%
set month=%mm%
set day=%dd%


:: Testing
echo Year:[%year%] - month:[%month%] - day:[%day%]

endlocal
pause

I hope this helps someone that deal with diferent languages.

How to use JavaScript variables in jQuery selectors?

$("#" + $(this).attr("name")).hide();

How do I format date in jQuery datetimepicker?

Here you go.

$('#timePicker').datetimepicker({
   // dateFormat: 'dd-mm-yy',
   format:'DD/MM/YYYY HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

function getFormattedDate(date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear().toString().slice(2);
    return day + '-' + month + '-' + year;
}

You need to pass datepicker() the date formatted correctly.

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

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

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

It sounds to me that you really want to limit the rows being returned in your query and page through the results. If so, you can do something like:

select * from (select rownum myrow, a.* from TEST1 a )
where myrow between 5 and 10 ;

You just have to determine your boundaries.

C# How to determine if a number is a multiple of another?

there are some syntax errors to your program heres a working code;

#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is  multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}

}

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

Where is the IIS Express configuration / metabase file found?

Since the introduction of Visual Studio 2015, this location has changed and is added into your solution root under the following location:

C:\<Path\To\Solution>\.vs\config\applicationhost.config

I hope this saves you some time!

Get everything after and before certain character in SQL Server

SELECT SUBSTRING('[email protected]',1,(CHARINDEX('@','[email protected]')-1)) Before, RIGHT('[email protected]',(CHARINDEX('@','[email protected]')+1)) After

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.

You can use JavaScript/Canvas to do the job but it is still experimental.

How to do a PUT request with curl?

Using the -X flag with whatever HTTP verb you want:

curl -X PUT -d arg=val -d arg2=val2 localhost:8080

This example also uses the -d flag to provide arguments with your PUT request.

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

It's been a while, but last time I had something similar:

ROLLBACK TRAN

or trying to

COMMIT

what had allready been done free'd everything up so I was able to clear things out and start again.

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

PUT

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H answer

DELETE

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

Can an ASP.NET MVC controller return an Image?

UPDATE: There are better options than my original answer. This works outside of MVC quite well but it's better to stick with the built-in methods of returning image content. See up-voted answers.

You certainly can. Try out these steps:

  1. Load the image from disk in to a byte array
  2. cache the image in the case you expect more requests for the image and don't want the disk I/O (my sample doesn't cache it below)
  3. Change the mime type via the Response.ContentType
  4. Response.BinaryWrite out the image byte array

Here's some sample code:

string pathToFile = @"C:\Documents and Settings\some_path.jpg";
byte[] imageData = File.ReadAllBytes(pathToFile);
Response.ContentType = "image/jpg";
Response.BinaryWrite(imageData);

Hope that helps!

Where is the web server root directory in WAMP?

this is the path to the web root directory c:\wamp\www

you can create different projects by adding different folders to this directory and call them like:

localhost/project1 from browser

this will run the index.html or index.php, lying inside project1

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

Android : Capturing HTTP Requests with non-rooted android device

You can use fiddler as webdebugger http://www.telerik.com/fiddler/web-debugging

Fiddler is a debugging tool from telerik software, which helps you to intercept every request that is initiated from your machine.

Embed website into my site

You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.

Rails where condition using NOT NIL

The canonical way to do this with Rails 3:

Foo.includes(:bar).where("bars.id IS NOT NULL")

ActiveRecord 4.0 and above adds where.not so you can do this:

Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })

When working with scopes between tables, I prefer to leverage merge so that I can use existing scopes more easily.

Foo.includes(:bar).merge(Bar.where.not(id: nil))

Also, since includes does not always choose a join strategy, you should use references here as well, otherwise you may end up with invalid SQL.

Foo.includes(:bar)
   .references(:bar)
   .merge(Bar.where.not(id: nil))

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Go to Path C:\ProgramData\Oracle\Java\javapath (This path is in my case might be different in your case). Rename the folder ORACLE with other name line ORACLE_OLD. And Restart the STS/IDE . This works for me

It is more efficient to use if-return-return or if-else-return?

Regarding coding style:

Most coding standards no matter language ban multiple return statements from a single function as bad practice.

(Although personally I would say there are several cases where multiple return statements do make sense: text/data protocol parsers, functions with extensive error handling etc)

The consensus from all those industry coding standards is that the expression should be written as:

int result;

if(A > B)
{
  result = A+1;
}
else
{
  result = A-1;
}
return result;

Regarding efficiency:

The above example and the two examples in the question are all completely equivalent in terms of efficiency. The machine code in all these cases have to compare A > B, then branch to either the A+1 or the A-1 calculation, then store the result of that in a CPU register or on the stack.

EDIT :

Sources:

  • MISRA-C:2004 rule 14.7, which in turn cites...:
  • IEC 61508-3. Part 3, table B.9.
  • IEC 61508-7. C.2.9.

:not(:empty) CSS selector is not working?

You may approach this differently; omit the use of the :empty pseudo-class and utilize input events to detect a significant value in the <input> field and style it accordingly:

_x000D_
_x000D_
var inputs = document.getElementsByTagName('input');_x000D_
_x000D_
for (var i = 0; i < inputs.length; i++) {_x000D_
  var input = inputs[i];_x000D_
  input.addEventListener('input', function() {_x000D_
    var bg = this.value ? 'green' : 'red';_x000D_
    this.style.backgroundColor = bg;_x000D_
  });_x000D_
}
_x000D_
body {_x000D_
  padding: 40px;_x000D_
}_x000D_
#inputList li {_x000D_
  list-style-type: none;_x000D_
  padding-bottom: 1.5em;_x000D_
}_x000D_
#inputList li input,_x000D_
#inputList li label {_x000D_
  float: left;_x000D_
  width: 10em;_x000D_
}_x000D_
#inputList li input {_x000D_
  color: white;_x000D_
  background-color: red;_x000D_
}_x000D_
#inputList li label {_x000D_
  text-align: right;_x000D_
  padding-right: 1em;_x000D_
}
_x000D_
<ul id="inputList">_x000D_
  <li>_x000D_
    <label for="username">Enter User Name:</label>_x000D_
    <input type="text" id="username" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <label for="password">Enter Password:</label>_x000D_
    <input type="password" id="password" />_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Related


Disclaimer: note that input events are currently experimental, and probably not widely supported.

Convert String to Calendar Object in Java

tl;dr

The modern approach uses the java.time classes.

YearMonth.from(
    ZonedDateTime.parse( 
        "Mon Mar 14 16:02:37 GMT 2011" , 
        DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
     )
).toString()

2011-03

Avoid legacy date-time classes

The modern way is with java.time classes. The old date-time classes such as Calendar have proven to be poorly-designed, confusing, and troublesome.

Define a custom formatter to match your string input.

String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );

Parse as a ZonedDateTime.

ZonedDateTime zdt = ZonedDateTime.parse( input , f );

You are interested in the year and month. The java.time classes include YearMonth class for that purpose.

YearMonth ym = YearMonth.from( zdt );

You can interrogate for the year and month numbers if needed.

int year = ym.getYear();
int month = ym.getMonthValue();

But the toString method generates a string in standard ISO 8601 format.

String output = ym.toString();

Put this all together.

String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );

input: Mon Mar 14 16:02:37 GMT 2011

zdt: 2011-03-14T16:02:37Z[GMT]

ym: 2011-03

Live code

See this code running in IdeOne.com.

Conversion

If you must have a Calendar object, you can convert to a GregorianCalendar using new methods added to the old classes.

GregorianCalendar gc = GregorianCalendar.from( zdt );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

CSS ''background-color" attribute not working on checkbox inside <div>

The Best solution to change background checkbox color

_x000D_
_x000D_
input[type=checkbox] {_x000D_
    margin-right: 5px;_x000D_
    cursor: pointer;_x000D_
    font-size: 14px;_x000D_
    width: 15px;_x000D_
    height: 12px;_x000D_
    position: relative;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:after {_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 15px;_x000D_
    top: 0;_x000D_
    content: " ";_x000D_
    background-color: #ff0000;_x000D_
    color: #fff;_x000D_
    display: inline-block;_x000D_
    visibility: visible;_x000D_
    padding: 0px 3px;_x000D_
    border-radius: 3px;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:checked:after {_x000D_
   content: "?";_x000D_
   font-size: 12px;_x000D_
  }
_x000D_
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>
_x000D_
_x000D_
_x000D_

How to append a char to a std::string?

Also adding insert option, as not mentioned yet.

std::string str("Hello World");
char ch;

str.push_back(ch);  //ch is the character to be added
OR
str.append(sizeof(ch),ch);
OR
str.insert(str.length(),sizeof(ch),ch) //not mentioned above

LaTeX: Prevent line break in a span of text

\mbox is the simplest answer. Regarding the update:

TeX prefers overlong lines to adding too much space between words on a line; I think the idea is that you will notice the lines that extend into the margin (and the black boxes it inserts after such lines), and will have a chance to revise the contents, whereas if there was too much space, you might not notice it.

Use \sloppy or \begin{sloppypar}...\end{sloppypar} to adjust this behavior, at least a little. Another possibility is \raggedright (or \begin{raggedright}...\end{raggedright}).

iOS: present view controller programmatically

Try this code:

[self.navigationController presentViewController:controller animated:YES completion:nil];

CSS Equivalent of the "if" statement

No you can't do if in CSS, but you can choose which style sheet you will use

Here is an example :

<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->

will use only for IE 6 here is the website where it is from http://www.quirksmode.org/css/condcom.html , only IE has conditional comments. Other browser do not, although there are some properties you can use for Firefox starting with -moz or for safari starting with -webkit. You can use javascript to detect which browser you're using and use javascript if for whatever actions you want to perform but that is a bad idea, since it can be disabled.

How to wait for 2 seconds?

How about this?

WAITFOR DELAY '00:00:02';

If you have "00:02" it's interpreting that as Hours:Minutes.

Java: how to represent graphs?

A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html

Explanation copied from the above page.

The Graph class represents an undirected graph of vertices named 0 through V - 1.

It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.

This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

How to uninstall Eclipse?

There is no automated uninstaller.

You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.

Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~ refers to the user home directory even on Windows.

Why is there no uninstaller?

According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.

How to quickly uninstall Eclipse

Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.

In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.

How to completely uninstall Eclipse

If you really want to remove Eclipse without leaving any traces, you have to manually delete

  • all desktop and start menu shortcuts
  • the installation directory (e.g. ~/eclipse/photon/)
  • the p2 bundle pool (which is often shared with other eclipse installations)

The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/).

If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/ directory.

Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/ contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.

How to delete all projects

If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata directory to get all Eclipse workspaces on your machine.

If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/ directory.

Div with margin-left and width:100% overflowing on the right side

If some other portion of your layout is influencing the div width you can set width:auto and the div (which is a block element) will fill the space

<div style="width:auto">
    <div style="margin-left:45px;width:auto">
        <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>

If that's still not working we may need to see more of your layout HTML/CSS

Switch on ranges of integers in JavaScript

If you need check ranges you are probably better off with if and else if statements, like so:

if (range > 0 && range < 5)
{
    // ..
}
else if (range > 5 && range < 9)
{
    // ..
}
else
{
    // Fall through
}

A switch could get large on bigger ranges.

String format currency

I strongly suspect the problem is simply that the current culture of the thread handling the request isn't set appropriately.

You can either set it for the whole request, or specify the culture while formatting. Either way, I would suggest not use string.Format with a composite format unless you really have more than one thing to format (or a wider message). Instead, I'd use:

@price.ToString("C", culture)

It just makes it somewhat simpler.

EDIT: Given your comment, it sounds like you may well want to use a UK culture regardless of the culture of the user. So again, either set the UK culture as the thread culture for the whole request, or possibly introduce your own helper class with a "constant":

public static class Cultures
{
    public static readonly CultureInfo UnitedKingdom = 
        CultureInfo.GetCultureInfo("en-GB");
}

Then:

@price.ToString("C", Cultures.UnitedKingdom)

In my experience, having a "named" set of cultures like this makes the code using it considerably simpler to read, and you don't need to get the string right in multiple places.

Wrap text in <td> tag

table-layout:fixed will resolve the expanding cell problem, but will create a new one. IE by default will hide the overflow but Mozilla will render it outside the box.

Another solution would be to use: overflow:hidden;width:?px

<table style="table-layout:fixed; width:100px">
 <tr>
   <td style="overflow:hidden; width:50px;">fearofthedarkihaveaconstantfearofadark</td>
   <td>
     test
   </td>
 </tr>
</table>

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

Java count occurrence of each item in an array

You can do it by using Arrays.sort and Recursion. The same wine but in a different bottle....

import java.util.Arrays;

public class ArrayTest {
public static int mainCount=0;

public static void main(String[] args) {
    String prevItem = "";
    String[] array = {"name1","name1","name2","name2", "name2"};
    Arrays.sort(array);

    for(String item:array){
        if(! prevItem.equals(item)){
            mainCount = 0;
            countArray(array, 0, item);
            prevItem = item;
        }
    }
}

private static void countArray(String[] arr, int currentPos, String item) {
    if(currentPos == arr.length){
        System.out.println(item + " " +  mainCount);
        return;
    }
    else{
        if(arr[currentPos].toString().equals(item)){
            mainCount += 1;
        }
        countArray(arr, currentPos+1, item);
    }
  }
}

How to prevent IFRAME from redirecting top-level window

Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.

Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

In HTML5 you can use sandbox property. Please see Pankrat's answer below. http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is

 lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row

Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

With ws
    lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
  1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
  2. .Cells(.Rows.Count, "A") returns the bottom most cell in column "A" in the worksheet

Then there is the End method. The documentation is ambiguous as to what it does.

Returns a Range object that represents the cell at the end of the region that contains the source range

Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:

  • If the range is multiple cells, it will use the region of rng.cells(1,1).
  • If the range isn't in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
  • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

So Range.End is not a trivial function.

  1. .row returns the row index of that cell.

load jquery after the page is fully loaded

For your problem, the solution might be to attach CDN hosted by google with certain library:

https://developers.google.com/speed/libraries/devguide

Also, you can add this at the bottom of page (just before </body>):

<script type="text/javascript">
(function() {
    var script = document.createElement('script')
    script.setAttribute("type", "text/javascript")
    script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
    document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>

However, this is risky in my opinion. You have an asynchronous call for jquery, thus your jquery has to wait until it loads (ie. $(document).ready won't work in this case). So my answer would be: use a CDN like google suggests; put your javascript on the bottom just before </body>; and, ignore flags from profilers.

PHP: Read Specific Line From File

I searched for a one line solution to read specific line from a file. Here my solution:

echo file('dayInt.txt')[1]

Is there a Social Security Number reserved for testing/examples?

If your testing requires pulling quasi-real credit reports from the bureaus, the inactive SSNs of other answers won't work and you'll need designated test numbers.

I found this site Which appears to contain test social security numbers with associated test names and credit card numbers.

Transunion has a test environment you can link and send data to, including associated dummy credit reports. Sending a SSN to them with certain numbers in certain positions will automatically route the inquiry to their test environment Other credit bureaus will have similar systems in place.

Set textarea width to 100% in bootstrap modal

Try add min-width: 100% to style of your textarea:

<textarea class="form-control" style="min-width: 100%"></textarea>

Reporting Services Remove Time from DateTime in Expression

My solution for a Date/Time parameter:

=CDate(Today())

The trick is to convert back to a DateTime as recommend Perhentian.

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

Chrome changed a lot since the times facebook could disable console...

As per March 2017 this doesn't work anymore.

Best you can do is disable some of the console functions, example:

if(!window.console) window.console = {};
var methods = ["log", "debug", "warn", "info", "dir", "dirxml", "trace", "profile"];
for(var i=0;i<methods.length;i++){
    console[methods[i]] = function(){};
}

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

How can I call a shell command in my Perl script?

You might want to look into open2 and open3 in case you need bidirectional communication.

Readably print out a python dict() sorted by key

Actually pprint seems to sort the keys for you under python2.5

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}

But not always under python 2.4

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}
>>> 

Reading the source code of pprint.py (2.5) it does sort the dictionary using

items = object.items()
items.sort()

for multiline or this for single line

for k, v in sorted(object.items()):

before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.

So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.

Python3 Update

Pretty print by sorted keys (lambda x: x[0]):

for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
    print("{} : {}".format(key, value))

Pretty print by sorted values (lambda x: x[1]):

for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
    print("{} : {}".format(key, value))

How to ignore ansible SSH authenticity checking?

forward to nikobelia

For those who using jenkins to run the play book, I just added to my jenkins job before running the ansible-playbook the he environment variable ANSIBLE_HOST_KEY_CHECKING = False For instance this:

export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook 'playbook.yml' \
--extra-vars="some vars..." \
--tags="tags_name..." -vv

SELECT DISTINCT on one column

Here is a version, basically the same as a couple of the other answers, but that you can copy paste into your SQL server Management Studio to test, (and without generating any unwanted tables), thanks to some inline values.

WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
    SELECT *
    FROM (
        VALUES
        (1,   'FOO-23',  'Orange'),
        (2,   'BAR-23',  'Orange'),
        (3,   'FOO-24',  'Apple'),
        (4,   'FOO-25',  'Orange')
    )
    AS [TestData]([ID],[SKU],[PRODUCT])
)

SELECT * FROM [TestData] WHERE [ID] IN 
(
    SELECT MIN([ID]) 
    FROM [TestData] 
    GROUP BY [PRODUCT]
)

Result

ID  SKU     PRODUCT
1   FOO-23  Orange
3   FOO-24  Apple

I have ignored the following ...

WHERE ([SKU] LIKE 'FOO-%')

as its only part of the authors faulty code and not part of the question. It's unlikely to be helpful to people looking here.

How to draw a rectangle around a region of interest in python

please don't try with the old cv module, use cv2:

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)


x1,y1 ------
|          |
|          |
|          |
--------x2,y2

[edit] to append the follow-up questions below:

cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

Zero-pad digits in string

First of all, your description is misleading. Double is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:

$s = sprintf('%02d', $digit);

For more information, refer to the documentation of sprintf.

What is the maximum recursion depth in Python, and how to increase it?

I'm not sure I'm repeating someone but some time ago some good soul wrote Y-operator for recursively called function like:

def tail_recursive(func):
  y_operator = (lambda f: (lambda y: y(y))(lambda x: f(lambda *args: lambda: x(x)(*args))))(func)
  def wrap_func_tail(*args):
    out = y_operator(*args)
    while callable(out): out = out()
    return out
  return wrap_func_tail

and then recursive function needs form:

def my_recursive_func(g):
  def wrapped(some_arg, acc):
    if <condition>: return acc
    return g(some_arg, acc)
  return wrapped

# and finally you call it in code

(tail_recursive(my_recursive_func))(some_arg, acc)

for Fibonacci numbers your function looks like this:

def fib(g):
  def wrapped(n_1, n_2, n):
    if n == 0: return n_1
    return g(n_2, n_1 + n_2, n-1)
  return wrapped

print((tail_recursive(fib))(0, 1, 1000000))

output:

..684684301719893411568996526838242546875

(actually tones of digits)

How can I apply styles to multiple classes at once?

just seperate the class name with a comma.

.a,.b{
your styles
}

How to convert numbers between hexadecimal and decimal

It looks like you can say

Convert.ToInt64(value, 16)

to get the decimal from hexdecimal.

The other way around is:

otherVar.ToString("X");

Aren't Python strings immutable? Then why does a + " " + b work?

Variables can point to anywhere they want.. An error will be thrown if you do the following:

a = "dog"
print a                   #dog
a[1] = "g"                #ERROR!!!!!! STRINGS ARE IMMUTABLE

How to get a unix script to run every 15 seconds?

Use nanosleep(2). It uses structure timespec that is used to specify intervals of time with nanosecond precision.

struct timespec {
           time_t tv_sec;        /* seconds */
           long   tv_nsec;       /* nanoseconds */
       };

How do I ignore ampersands in a SQL script running from SQL Plus?

I had a CASE statement with WHEN column = 'sometext & more text' THEN ....

I replaced it with WHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...

you could also use WHEN column LIKE 'sometext _ more text' THEN ...

(_ is the wildcard for a single character)

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".

$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];

http://jsbin.com/ewitun/1/edit

The same with plain ES6:

$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]

Remove decimal values using SQL query

Your data type is DECIMAL with decimal places, say DECIMAL(10,2). The values in your database are 12, 15, 18, and 20.

12 is the same as 12.0 and 12.00 and 12.000 . It is up to the tool you are using to select the data with, how to display the numbers. Yours either defaults to two digits for decimals or it takes the places from your data definition.

If you only want integers in your column, then change its data type to INT. It makes no sense to use DECIMAL then.

If you want integers and decimals in that column then stay with the DECIMAL type. If you don't like the way you are shown the values, then format them in your application. It's up to that client program to decide for instance if to display point or comma for the decimal separator. (The database can be used from different locations.)

Also don't rely on any database or session settings like a decimal separator being a point and not a comma and then use REPLACE on it. That can work for one person and not for the other.

How can I find whitespace in a String?

You can basically do this

if(s.charAt(i)==32){
   return true;
}

You must write boolean method.Whitespace char is 32.

How to fix Invalid AES key length?

You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.

This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;

public class Encrypt {

    static byte [] arr = {1,2,3,4,5,6,7,8,9};

    // static byte [] arr = new byte[16];

      public static void main(String...args) {
        try {
         //   System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
            Base64.Decoder decoder = Base64.getDecoder();
            // static byte [] arr = new byte[16];
            Security.setProperty("crypto.policy", "unlimited");
            String key = "Your key";
       //     System.out.println("-------" + key);

            String value = "Hey, i am adnan";
            String IV = "0123456789abcdef";
       //     System.out.println(value);
            // log.info(value);
          IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            //    IvParameterSpec iv = new IvParameterSpec(arr);

        //    System.out.println(key);
            SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
         //   System.out.println(skeySpec);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //    System.out.println("ddddddddd"+IV);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
       //     System.out.println(cipher.getIV());

            byte[] encrypted = cipher.doFinal(value.getBytes());
            String encryptedString = Base64.getEncoder().encodeToString(encrypted);

            System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
            // vars.put("input-1",encryptedString);
            //  log.info("beanshell");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}

Javascript "Not a Constructor" Exception while creating objects

In my case I was using the prototype name as the object name. For e.g.

function proto1()
{}

var proto1 = new proto1();

It was a silly mistake but might be of help to someone like me ;)

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Docker is installed but Docker Compose is not ? why?

On Linux, you can download the Docker Compose binary from the Compose repository release page on GitHub. Follow the instructions from the link, which involve running the curl command in your terminal to download the binaries. These step-by-step instructions are also included below.

1:Run this command to download the current stable release of Docker Compose:

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

To install a different version of Compose, substitute 1.26.2 with the version of Compose you want to use.

2:Apply executable permissions to the binary:

sudo chmod +x /usr/local/bin/docker-compose

Note: If the command docker-compose fails after installation, check your path. You can also create a symbolic link to /usr/bin or any other directory in your path.

What exactly is a Context in Java?

since you capitalized the word, I assume you are referring to the interface javax.naming.Context. A few classes implement this interface, and at its simplest description, it (generically) is a set of name/object pairs.

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

My solution is

fig = plt.figure()
fig.add_subplot(1, 2, 1)   #top and bottom left
fig.add_subplot(2, 2, 2)   #top right
fig.add_subplot(2, 2, 4)   #bottom right 
plt.show()

2x2 grid with 1 and 3 merge

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

Some months ago I ran into an odd situation where I also needed to send some Json-formatted date back to my controller. Here's what I came up with after pulling my hair out:

My class looks like this :

public class NodeDate
{
    public string nodedate { get; set; }
}
public class NodeList1
{
    public List<NodeDate> nodedatelist { get; set; }
}

and my c# code as follows :

        public string getTradeContribs(string Id, string nodedates)
    {            
        //nodedates = @"{""nodedatelist"":[{""nodedate"":""01/21/2012""},{""nodedate"":""01/22/2012""}]}";  // sample Json format
        System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
        NodeList1 nodes = (NodeList1)ser.Deserialize(nodedates, typeof(NodeList1));
        string thisDate = "";
        foreach (var date in nodes.nodedatelist)
        {  // iterate through if needed...
            thisDate = date.nodedate;
        }   
    }

and so I was able to Deserialize my nodedates Json object parameter in the "nodes" object; naturally of course using the class "NodeList1" to make it work.

I hope this helps.... Bob

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

Get full path of the files in PowerShell

Try this:

Get-ChildItem C:\windows\System32 -Include *.txt -Recurse | select -ExpandProperty FullName

<Django object > is not JSON serializable

From version 1.9 Easier and official way of getting json

from django.http import JsonResponse
from django.forms.models import model_to_dict


return JsonResponse(  model_to_dict(modelinstance) )

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

Swift 2.0

Pass info using userInfo which is a optional Dictionary of type [NSObject : AnyObject]?

  let imageDataDict:[String: UIImage] = ["image": image]

  // Post a notification
  NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

 // Register to receive notification in your class
 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

 // handle notification
 func showSpinningWheel(notification: NSNotification) { 

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
 }

Swift 3.0 version and above

The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift

  let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 // For swift 4.0 and above put @objc attribute in front of function Definition  
 func showSpinningWheel(_ notification: NSNotification) {

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
 }

NOTE: Notification “names” are no longer strings, but are of type Notification.Name, hence why we are using NSNotification.Name(rawValue:"notificationName") and we can extend Notification.Name with our own custom notifications.

extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}

// and post notification like this
NotificationCenter.default.post(name: .myNotification, object: nil)

How can I find last row that contains data in a specific column?

Public Function GetLastRow(ByVal SheetName As String) As Integer
    Dim sht As Worksheet
    Dim FirstUsedRow As Integer     'the first row of UsedRange
    Dim UsedRows As Integer         ' number of rows used

    Set sht = Sheets(SheetName)
    ''UsedRange.Rows.Count for the empty sheet is 1
    UsedRows = sht.UsedRange.Rows.Count
    FirstUsedRow = sht.UsedRange.Row
    GetLastRow = FirstUsedRow + UsedRows - 1

    Set sht = Nothing
End Function

sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used

if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.

This function calculate the first row number of UsedRange plus number of UsedRange rows.

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

I had a directory of files that I wanted to check. I created an Excel macro to determine ANSI vs. UTF-8. This worked for me.

        Sub GetTextFileEncoding()
        Dim sFile As String
        Dim sPath As String
        Dim sTextLine As String
        Dim iRow As Integer

        'Set Defaults and Initial Values
        iRow = 1
        sPath = "C:textfiles\"
        sFile = Dir(sPath & "*.txt")

        Do While Len(sFile) > 0
            'Get FileType
            'Debug.Print sFile & " - " & FileEncodeType(sPath & sFile)

            'Show on Excel Worksheet
            Cells(iRow, 1).Value = sFile
            Cells(iRow, 2).Value = FileEncodeType(sPath & sFile)

            'Get next file
            sFile = Dir

            'Increment Row
            iRow = iRow + 1
        Loop
    End Sub

    Function FileEncodeType(sFile As String) As String
        Dim bEF As Boolean
        Dim bBB As Boolean
        Dim bBF As Boolean

        bEF = False
        bBB = False
        bBF = False

        Open sFile For Input As #1
            If Not EOF(1) Then
                'Read first line
                Line Input #1, textline
                'Debug.Print textline
                For i = 1 To 3
                    'Debug.Print Asc(Mid(textline, i, 1)) & " - " & Mid(textline, i, 1)
                    Select Case i
                        Case 1
                            If Asc(Mid(textline, i, 1)) = 239 Then
                                bEF = True
                            End If
                        Case 2
                             If Asc(Mid(textline, i, 1)) = 187 Then
                                bBB = True
                            End If
                        Case 3
                             If Asc(Mid(textline, i, 1)) = 191 Then
                                bBF = True
                            End If
                        Case 4

                    End Select
                Next
            End If
        Close #1

        If bEF And bBB And bBF Then
            FileEncodeType = "UTF-8"
        Else
            FileEncodeType = "ANSI"
        End If
    End Function

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

In many case It is java facet problem ,jdk or jre or jsp version is difference than maven project face.

mvn command not found in OSX Mavrerick

Solutions above are good but they require ~/.bash_profile. /usr/local/bin is already in the $PATH and it can be confirmed by doing echo $PATH. Download maven and run the following commands -

$ cd ~/Downloads
$ tar xvf apache-maven-3.5.3-bin.tar.gz
$ mv apache-maven-3.5.3 /usr/local/
$ cd /usr/local/bin
$ sudo ln -s ../apache-maven-3.5.3/bin/mvn mvn
$ mvn -version
$ which mvn

Note: The version of apache maven would be the one you will download.

How to get Maven project version to the bash command line

I need exactly this requirement during my Travis job but with multiple values. I start with this solution but when calling multiple time this is very slow (I need 5 expresions).

I wrote a simple maven plugin to extract pom.xml's values into .sh file.

https://github.com/famaridon/ci-tools-maven-plugin

mvn com.famaridon:ci-tools-maven-plugin:0.0.1-SNAPSHOT:environment -Dexpressions=project.artifactId,project.version,project.groupId,project.build.sourceEncoding

Will produce that:

#!/usr/bin/env bash
CI_TOOLS_PROJECT_ARTIFACTID='ci-tools-maven-plugin';
CI_TOOLS_PROJECT_VERSION='0.0.1-SNAPSHOT';
CI_TOOLS_PROJECT_GROUPID='com.famaridon';
CI_TOOLS_PROJECT_BUILD_SOURCEENCODING='UTF-8';

now you can simply source the file

source .target/ci-tools-env.sh

Have fun.

Converting Integer to Long

This is null-safe

Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : tmp.longValue();

How to create a sticky footer that plays well with Bootstrap 3

For those who are searching for a light answer, you can get a simple working example from here:

html {
    position: relative;
    min-height: 100%;
}
body {
    margin-bottom: 60px /* Height of the footer */
}
footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px /* Example value */
}

Just play with the body's margin-bottom for adding space between the content and footer.

How to determine whether a year is a leap year?

From 1700 to 1917, official calendar was the Julian calendar. Since then they we use the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that 32nd day in 1918, was the February 14th.

In both calendar systems, February is the only month with a variable amount of days, it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 while in the Gregorian calendar, leap years are either of the following:

Divisible by 400.

Divisible by 4 and not divisible by 100.

So the program for leap year will be:

def leap_notleap(year):

    yr = ''
    if year <= 1917:
        if year % 4 == 0:
            yr = 'leap'
        else:
            yr = 'not leap'
    elif year >= 1919:
        if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
            yr = 'leap'
        else:
            yr = 'not leap'
    else:
        yr = 'none actually, since feb had only 14 days'

    return yr

How do I clear a C++ array?

If only to 0 then you can use memset:

int* a = new int[6];

memset(a, 0, 6*sizeof(int));

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

How to print a list with integers without the brackets, commas and no quotes?

Something like this should do it:

for element in list_:
   sys.stdout.write(str(element))

POST unchecked HTML checkboxes

you don't need to create a hidden field for all checkboxes just copy my code. it will change the value of checkbox if not checked the value will assign 0 and if checkbox checked then assign value into 1

$("form").submit(function () {

    var this_master = $(this);

    this_master.find('input[type="checkbox"]').each( function () {
        var checkbox_this = $(this);


        if( checkbox_this.is(":checked") == true ) {
            checkbox_this.attr('value','1');
        } else {
            checkbox_this.prop('checked',true);
            //DONT' ITS JUST CHECK THE CHECKBOX TO SUBMIT FORM DATA    
            checkbox_this.attr('value','0');
        }
    })
})

SQL query for a carriage return in a string and ultimately removing carriage return

Something like this seems to work for me:

SELECT * FROM Parameters WHERE Name LIKE '%\n%'

What are the differences between type() and isinstance()?

To summarize the contents of other (already good!) answers, isinstance caters for inheritance (an instance of a derived class is an instance of a base class, too), while checking for equality of type does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).

Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so isinstance is less bad than checking identity of types because it seamlessly supports inheritance.

It's not that isinstance is good, mind you—it's just less bad than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument as if it was of a certain desired type, do it in a try/except statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the except clause, try something else (using the argument "as if" it was of some other type).

basestring is, however, quite a special case—a builtin type that exists only to let you use isinstance (both str and unicode subclass basestring). Strings are sequences (you could loop over them, index them, slice them, ...), but you generally want to treat them as "scalar" types—it's somewhat incovenient (but a reasonably frequent use case) to treat all kinds of strings (and maybe other scalar types, i.e., ones you can't loop on) one way, all containers (lists, sets, dicts, ...) in another way, and basestring plus isinstance helps you do that—the overall structure of this idiom is something like:

if isinstance(x, basestring)
  return treatasscalar(x)
try:
  return treatasiter(iter(x))
except TypeError:
  return treatasscalar(x)

You could say that basestring is an Abstract Base Class ("ABC")—it offers no concrete functionality to subclasses, but rather exists as a "marker", mainly for use with isinstance. The concept is obviously a growing one in Python, since PEP 3119, which introduces a generalization of it, was accepted and has been implemented starting with Python 2.6 and 3.0.

The PEP makes it clear that, while ABCs can often substitute for duck typing, there is generally no big pressure to do that (see here). ABCs as implemented in recent Python versions do however offer extra goodies: isinstance (and issubclass) can now mean more than just "[an instance of] a derived class" (in particular, any class can be "registered" with an ABC so that it will show as a subclass, and its instances as instances of the ABC); and ABCs can also offer extra convenience to actual subclasses in a very natural way via Template Method design pattern applications (see here and here [[part II]] for more on the TM DP, in general and specifically in Python, independent of ABCs).

For the underlying mechanics of ABC support as offered in Python 2.6, see here; for their 3.1 version, very similar, see here. In both versions, standard library module collections (that's the 3.1 version—for the very similar 2.6 version, see here) offers several useful ABCs.

For the purpose of this answer, the key thing to retain about ABCs (beyond an arguably more natural placement for TM DP functionality, compared to the classic Python alternative of mixin classes such as UserDict.DictMixin) is that they make isinstance (and issubclass) much more attractive and pervasive (in Python 2.6 and going forward) than they used to be (in 2.5 and before), and therefore, by contrast, make checking type equality an even worse practice in recent Python versions than it already used to be.

How to get next/previous record in MySQL?

Select top 1 * from foo where id > 4 order by id asc

How to use executeReader() method to retrieve the value of just one cell

using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
    cmd.Parameters.AddWithValue("@id", index);
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
        }
    }
}

typedef struct vs struct definitions

In C (not C++), you have to declare struct variables like:

struct myStruct myVariable;

In order to be able to use myStruct myVariable; instead, you can typedef the struct:

typedef struct myStruct someStruct;
someStruct myVariable;

You can combine struct definition and typedefs it in a single statement which declares an anonymous struct and typedefs it.

typedef struct { ... } myStruct;

Get all unique values in a JavaScript array (remove duplicates)

Do it with lodash and identity lambda function, just define it before use your object

const _ = require('lodash');
...    
_.uniqBy([{a:1,b:2},{a:1,b:2},{a:1,b:3}], v=>v.a.toString()+v.b.toString())
_.uniq([1,2,3,3,'a','a','x'])

and will have:

[{a:1,b:2},{a:1,b:3}]
[1,2,3,'a','x']

(this is the simplest way )

ScrollTo function in AngularJS

An angular solution using $anchorScroll taken from a now archived blog post by Ben Lesh, which is also reproduced in some detail at this SO answer he contributed (including a rewrite of how to do this within a routing):

app.controller('MainCtrl', function($scope, $location, $anchorScroll) {
  var i = 1;
  
  $scope.items = [{ id: 1, name: 'Item 1' }];
  
  $scope.addItem = function (){
    i++;
    //add the item.
    $scope.items.push({ id: i, name: 'Item ' + i});
    //now scroll to it.
    $location.hash('item' + i);
    $anchorScroll();
  };
});

And here is the plunker, from the blog that provided this solution: http://plnkr.co/edit/xi2r8wP6ZhQpmJrBj1jM?p=preview

Important to note that the template at that plunker includes this, which sets up the id that you're using $anchorScroll to scroll to:

<li ng-repeat="item in items" 
    id="item{{item.id}}"
>{{item.name}</li>

And if you care for a pure javascript solution, here is one:

Invoke runScroll in your code with parent container id and target scroll id:

function runScroll(parentDivId,targetID) {
    var longdiv;
    longdiv = document.querySelector("#" + parentDivId);
    var div3pos = document.getElementById(targetID).offsetTop;
    scrollTo(longdiv, div3pos, 600);
}


function scrollTo(element, to, duration) {
    if (duration < 0) return;
    var difference = to - element.scrollTop;
    var perTick = difference / duration * 10;

    setTimeout(function () {
        element.scrollTop = element.scrollTop + perTick;
        if (element.scrollTop == to) return;
        scrollTo(element, to, duration - 10);
    }, 10);
}

Reference: Cross browser JavaScript (not jQuery...) scroll to top animation

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

Of course that works; when @item1 = N'', it IS NOT NULL.

You can define @item1 as NULL by default at the top of your stored procedure, and then not pass in a parameter.

Copy tables from one database to another in SQL Server

If it’s one table only then all you need to do is

  • Script table definition
  • Create new table in another database
  • Update rules, indexes, permissions and such
  • Import data (several insert into examples are already shown above)

One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.

Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

Tomcat Server Error - Port 8080 already in use

In case of MAC users, go to Terminal and do the following

lsof -i :8080 //returns the PID (process id) that runs on port 8080
kill 1234 //kill the process using PID (used dummy PID here)
lsof -i :8443
kill 4321

8080 is HTTP port and 8443 is HTTPS port, by default.

How can I detect when an Android application is running in the emulator?

I found the new emulator Build.HARDWARE = "ranchu".

Reference:https://groups.google.com/forum/#!topic/android-emulator-dev/dltBnUW_HzU

And also I found the Android official way to check whether emulator or not.I think it's good reference for us.

Since Android API Level 23 [Android 6.0]

package com.android.internal.util;

/**
 * @hide
 */
public class ScreenShapeHelper {
    private static final boolean IS_EMULATOR = Build.HARDWARE.contains("goldfish");
}

We have ScreenShapeHelper.IS_EMULATOR to check whether emulator.

Since Android API Level 24 [Android 7.0]

package android.os;

/**
 * Information about the current build, extracted from system properties.
 */
public class Build {


    /**
     * Whether this build was for an emulator device.
     * @hide
     */
    public static final boolean IS_EMULATOR = getString("ro.kernel.qemu").equals("1");

}

We have Build.IS_EMULATOR to check whether emulator.

The way the official to check whether emulator is not new,and also maybe not enough,the answers above also mentioned.

But this maybe show us that the official will provide the way of official to check whether emulator or not.

As using the above all ways mentioned,right now we can also use the two ways about to check whether emulator.

How to access the com.android.internal package and @hide

and wait for the official open SDK.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

Controlling Spacing Between Table Cells

Use the border-spacing property on the table element to set the spacing between cells.

Make sure border-collapse is set to separate (or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).

How to get the number of days of difference between two dates on mysql?

Get days between Current date to destination Date

 SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;

output

days

 335

Loading a properties file from Java package

To add to Joachim Sauer's answer, if you ever need to do this in a static context, you can do something like the following:

static {
  Properties prop = new Properties();
  InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
  prop.load(in);
  in.close()
}

(Exception handling elided, as before.)

How to use opencv in using Gradle?

You can do this very easily in Android Studio.

Follow the below steps to add Open CV in your project as library.

  1. Create a libraries folder underneath your project main directory. For example, if your project is OpenCVExamples, you would create a OpenCVExamples/libraries folder.

  2. Go to the location where you have SDK "\OpenCV-2.4.8-android-sdk\sdk" here you will find the java folder, rename it to opencv.

  3. Now copy the complete opencv directory from the SDK into the libraries folder you just created.

  4. Now create a build.gradle file in the opencv directory with the following contents

    apply plugin: 'android-library'
    
    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.9.+'
        }
    }
    
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.1"
    
        defaultConfig {
            minSdkVersion 8
            targetSdkVersion 19
            versionCode 2480
            versionName "2.4.8"
        }
    
        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                resources.srcDirs = ['src']
                res.srcDirs = ['res']
                aidl.srcDirs = ['src']
            }
        }
    }
    
  5. Edit your settings.gradle file in your application’s main directory and add this line:

    include ':libraries:opencv'
    
  6. Sync your project with Gradle and it should looks like this

    screen 1

  7. Right click on your project then click on the Open Module Settings then Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new module dependency.

    enter image description here

  8. Choose Module dependency. It will open a dialog with a list of modules to choose from; select “:libraries:opencv”.

    enter image description here

  9. Create a jniLibs folder in the /app/src/main/ location and copy the all the folder with *.so files (armeabi, armeabi-v7a, mips, x86) in the jniLibs from the OpenCV SDK.

    enter image description here

  10. Click OK. Now everything done, go and enjoy with OpenCV.

Can't install Scipy through pip

Microsoft Windows users of 64 bit Python installations will need to download the 64 bit .whl of Scipy from here, then simply cd into the folder you've downloaded the .whl file and run:

pip install scipy-0.16.1-cp27-none-win_amd64.whl

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Excel export script works on IE7+, Firefox and Chrome.

function fnExcelReport()
{
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('headerTable'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

Just create a blank iframe:

<iframe id="txtArea1" style="display:none"></iframe>

Call this function on:

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>

INSERT INTO...SELECT for all MySQL columns

More Examples & Detail

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

Javascript: How to loop through ALL DOM elements on a page?

Andy E. gave a good answer.

I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.

For an example, I needed to just parse "visual" part of the web page, so I just made this

var visualDomElts = document.body.getElementsByTagName('*');

This will never take in consideration the head part.

How can I check if a scrollbar is visible?

Here's an improved version of Evan's answer which seems to properly account for overflow logic.

            function element_scrollbars(node) {
                var element = $(node);
                var overflow_x = element.css("overflow-x");
                var overflow_y = element.css("overflow-y");
                var overflow = element.css("overflow");
                if (overflow_x == "undefined") overflow_x == "";
                if (overflow_y == "undefined") overflow_y == "";
                if (overflow == "undefined") overflow == "";
                if (overflow_x == "") overflow_x = overflow;
                if (overflow_y == "") overflow_y = overflow;
                var scrollbar_vertical = (
                    (overflow_y == "scroll")
                    || (
                        (
                            (overflow_y == "hidden")
                            || (overflow_y == "visible")
                        )
                        && (
                            (node.scrollHeight > node.clientHeight)
                        )
                    )
                );
                var scrollbar_horizontal = (
                    (overflow_x == "scroll")
                    || (
                        (
                            (overflow_x == "hidden")
                            || (overflow_x == "visible")
                        )
                        && (
                            (node.scrollWidth > node.clientWidth)
                        )
                    )
                );
                return {
                    vertical: scrollbar_vertical,
                    horizontal: scrollbar_horizontal
                };
            }

Extension exists but uuid_generate_v4 fails

Looks like the extension is not installed in the particular database you require it.

You should connect to this particular database with

 \CONNECT my_database

Then install the extension in this database

 CREATE EXTENSION "uuid-ossp";

How to add parameters to HttpURLConnection using POST using NameValuePair

There's a much easier approach using PrintWriter (see here)

Basically all you need is:

// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// write out form parameters
String postParamaters = "param1=value1&param2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

// connect
urlConnection.connect();

How to get main window handle from process id?

I don't believe Windows (as opposed to .NET) provides a direct way to get that.

The only way I know of is to enumerate all the top level windows with EnumWindows() and then find what process each belongs to GetWindowThreadProcessID(). This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Application_Error having issue with Ajax requests. If error handled in Action which called by Ajax - it will display your Error View inside the resulting container.

How do you make an element "flash" in jQuery

$("#someElement").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1); 

3000 is 3 seconds

From opacity 1 it is faded to 0.3, then to 1 and so on.

You can stack more of these.

Only jQuery is needed. :)