Programs & Examples On #Cssadapter

How to quietly remove a directory with content in PowerShell

Remove-Item -LiteralPath "foldertodelete" -Force -Recurse

CSS performance relative to translateZ(0)

I can attest to the fact that -webkit-transform: translate3d(0, 0, 0); will mess with the new position: -webkit-sticky; property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.

Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased on the html element. I was testing this behavior in iOS7 and Android.

Preventing SQL injection in Node.js

Mysql-native has been outdated so it became MySQL2 that is a new module created with the help of the original MySQL module's team. This module has more features and I think it has what you want as it has prepared statements(by using.execute()) like in PHP for more security.

It's also very active(the last change was from 2-1 days) I didn't try it before but I think it's what you want and more.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

How to resize superview to fit all subviews with autolayout?

This can be done for a normal subview inside a larger UIView, but it doesn't work automatically for headerViews. The height of a headerView is determined by what's returned by tableView:heightForHeaderInSection: so you have to calculate the height based on the height of the UILabel plus space for the UIButton and any padding you need. You need to do something like this:

-(CGFloat)tableView:(UITableView *)tableView 
          heightForHeaderInSection:(NSInteger)section {
    NSString *s = self.headeString[indexPath.section];
    CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17] 
                constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
                    lineBreakMode:NSLineBreakByWordWrapping];
    return size.height + 60;
}

Here headerString is whatever string you want to populate the UILabel, and the 281 number is the width of the UILabel (as setup in Interface Builder)

Error C1083: Cannot open include file: 'stdafx.h'

There are two solutions for it.

Solution number one: 1.Recreate the project. While creating a project ensure that precompiled header is checked(Application settings... *** Do not check empty project)

Solution Number two: 1.Create stdafx.h and stdafx.cpp in your project 2 Right click on project -> properties -> C/C++ -> Precompiled Headers 3.select precompiled header to create(/Yc) 4.Rebuild the solution

Drop me a message if you encounter any issue.

How to display pandas DataFrame of floats using a format string for columns?

I like using pandas.apply() with python format().

import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])

make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)

Also, it can be easily used with multiple columns...

df = pd.concat([s, s * 2], axis=1)

make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

Completely nothing worked out for me from these answers. Had to create the project again by running cordova platform add ios. What I've noticed, even freshly generated project with (in my case) Firebase pods caused the error message over and over again. In my opinion looks like a bug for some (Firebase, RestKit) pods in Xcode or CocoaPods. To have the pods included I could simply edit my config.xml and run cordova platform add iOS, which did everything for me automatically. Not sure if it will work in all scenarios though.

Edit: I had a Podfile from previous iOS/Xcode, but the newest as of today have # DO NOT MODIFY -- auto-generated by Apache Cordova in the Podfile. This turned on a light in my head to try the approach. Looks a bit trivial, but works and my Firebase features worked out.

Unfamiliar symbol in algorithm: what does ? mean?

The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.

If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.

The meaning of NoInitialContextException error

you need to use jboss-client.jar in your client project and you need to use jnp-client jar in your ejb project

Fastest way to determine if an integer's square root is an integer

I like the idea to use an almost correct method on some of the input. Here is a version with a higher "offset". The code seems to work and passes my simple test case.

Just replace your:

if(n < 410881L){...}

code with this one:

if (n < 11043908100L) {
    //John Carmack hack, converted to Java.
    // See: http://www.codemaestro.com/reviews/9
    int i;
    float x2, y;

    x2 = n * 0.5F;
    y = n;
    i = Float.floatToRawIntBits(y);
    //using the magic number from 
    //http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf
    //since it more accurate
    i = 0x5f375a86 - (i >> 1);
    y = Float.intBitsToFloat(i);
    y = y * (1.5F - (x2 * y * y));
    y = y * (1.5F - (x2 * y * y)); //Newton iteration, more accurate

    sqrt = Math.round(1.0F / y);
} else {
    //Carmack hack gives incorrect answer for n >= 11043908100.
    sqrt = (long) Math.sqrt(n);
}

What's the best UML diagramming tool?

I recommend Software Ideas Modeler. It has a lot of features and an intuitive GUI.

Making a mocked method return an argument that was passed to it

This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:

@Test
fun demo() {
  // mock a sample function
  val aMock: (String) -> (String) = mockk()

  // make it return the same as the argument on every invocation
  every {
    aMock.invoke(any())
  } answers {
    firstArg()
  }

  // test it
  assertEquals("senko", aMock.invoke("senko"))
  assertEquals("senko1", aMock.invoke("senko1"))
  assertNotEquals("not a senko", aMock.invoke("senko"))
}

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000 to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

In Chrome:

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.

For me, this error was triggered by a trailing space in the URL of this call.

jQuery.getJSON( url, function( response, status, xhr ) {
   ...
}

How do I download the Android SDK without downloading Android Studio?

I downloaded Android Studio and installed it. The installer said:-

Android Studio => ( 500 MB )

Android SDK => ( 2.3 GB )

Android Studio installer is actually an "Android SDK Installer" along with a sometimes useful tool called "Android Studio".

Most importantly:- Android Studio Installer will not just install the SDK. It will also:-

  • Install the latest build-tools.
  • Install the latest platform-tools.
  • Install the latest AVD Manager which you cannot do without.

Things which you will have to do manually if you install the SDK from its zip file.

Just take it easy. Install the Android Studio.

****************************** Edit ******************************

So, being inspired by the responses in the comments I would like to update my answer.

The update is that only (and only) if 500MB of hard disk space does not matter much to you than you should go for Android Studio otherwise other answers would be better for you.

Android Studio worked for me as I had a 1TB hard disk which is 2000 times 500MB.

Also, note: that RAM sizse should not a restriction for you as you would not even be running Android Studio.

I came to this solution as I was myself stuck in this problem. I tried other answers but for some reason (maybe my in-competencies) they did not work for me. I decided to go for Android Studio and realized that it was merely 18% of the total installation and SDK was 82% of it. While I used to think otherwise. I am not deleting the answers inspite of negative rating as the answer worked for me. I might work for someone elese with a 1 TB hard disk (which is pretty common these days).

ArrayList or List declaration in Java

It is easy to change the implementation to List to Set:

Collection<String> stringList = new ArrayList<String>();
//Client side
stringList = new LinkedList<String>();

stringList = new HashSet<String>();
//stringList = new HashSet<>(); java 1.7 and 1.8

Select rows from a data frame based on values in a vector

Have a look at ?"%in%".

dt[dt$fct %in% vc,]
   fct X
1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

You could also use ?is.element:

dt[is.element(dt$fct, vc),]

Can we locate a user via user's phone number in Android?

I checked play.google.com/store/apps/details?id=and.p2l&hl=en They are not locating the user's current location at all. So based on the number itself they are judging the location of the user. Like if the number starts from 240 ( in US) they they are saying location is Maryland but the person can be in California. So i don't think they are getting the user's location through LocationListner of Java at all.

how to check if the input is a number or not in C?

I was struggling with this for awhile, so I thought I'd just add my two cents:

1) Create a separate function to check if an fgets input consists entirely of numbers:

int integerCheck(){
char myInput[4];
fgets(myInput, sizeof(myInput), stdin);
    int counter = 0;
    int i;
    for (i=0; myInput[i]!= '\0'; i++){
        if (isalpha(myInput[i]) != 0){
            counter++;
            if(counter > 0){
                printf("Input error: Please try again. \n ");
                return main();
            }
        }

    }
    return atoi(myInput); 
}

The above starts a loop through every unit of an fgets input until the ending NULL value. If it comes across a letter or an operator, it adds "1" to the int "counter" which is initially set to 0. Once the counter becomes greater than 0, the nested if statement instructs the loop to print an error message & then restart the program. When the loops completes, if int 'counter' is still the value of 0, it returns the initially inputted integer to be used in the main function ...

2) the main function would be:

int main(void){
unsigned int numberOne;
unsigned int numberTwo;
numberOne = integerCheck();
numberTwo = integerCheck();
return numberOne*numberTwo;

}

Assuming both integers are inputted correctly, the example provided will yield the result of int "numberOne" multiplied by int "numberTwo". The program will repeat for however long it takes to get two properly inputted integers.

Remove all special characters, punctuation and spaces from string

Here is a regex to match a string of characters that are not a letters or numbers:

[^A-Za-z0-9]+

Here is the Python command to do a regex substitution:

re.sub('[^A-Za-z0-9]+', '', mystring)

How to select label for="XYZ" in CSS?

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

How can I reuse a navigation bar on multiple pages?

I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.

First, create a page with all the navigation bar's HTML content.

Next, use jQuery's $.get method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html and added a placeholder tag (Like <div id="nav-placeholder">) in your index.html, then you would use the following code:

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
    $("#nav-placeholder").replaceWith(data);
});
</script>

C/C++ line number

Use __LINE__, but what is its type?

LINE The presumed line number (within the current source file) of the current source line (an integer constant).

As an integer constant, code can often assume the value is __LINE__ <= INT_MAX and so the type is int.

To print in C, printf() needs the matching specifier: "%d". This is a far lesser concern in C++ with cout.

Pedantic concern: If the line number exceeds INT_MAX1 (somewhat conceivable with 16-bit int), hopefully the compiler will produce a warning. Example:

format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]

Alternatively, code could force wider types to forestall such warnings.

printf("Not logical value at line number %ld\n", (long) __LINE__);
//or
#include <stdint.h>
printf("Not logical value at line number %jd\n", INTMAX_C(__LINE__));

Avoid printf()

To avoid all integer limitations: stringify. Code could directly print without a printf() call: a nice thing to avoid in error handling2 .

#define xstr(a) str(a)
#define str(a) #a

fprintf(stderr, "Not logical value at line number %s\n", xstr(__LINE__));
fputs("Not logical value at line number " xstr(__LINE__) "\n", stderr);

1 Certainly poor programming practice to have such a large file, yet perhaps machine generated code may go high.

2 In debugging, sometimes code simply is not working as hoped. Calling complex functions like *printf() can itself incur issues vs. a simple fputs().

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

mongodb how to get max value from collections

db.collection.findOne().sort({age:-1}) //get Max without need for limit(1)

How to round a floating point number up to a certain decimal place?

8.833333333339 (or 8.833333333333334, the result of 106.00/12) properly rounded to two decimal places is 8.83. Mathematically it sounds like what you want is a ceiling function. The one in Python's math module is named ceil:

import math

v = 8.8333333333333339
print(math.ceil(v*100)/100)  # -> 8.84

Respectively, the floor and ceiling functions generally map a real number to the largest previous or smallest following integer which has zero decimal places — so to use them for 2 decimal places the number is first multiplied by 102 (or 100) to shift the decimal point and is then divided by it afterwards to compensate.

If you don't want to use the math module for some reason, you can use this (minimally tested) implementation I just wrote:

def ceiling(x):
    n = int(x)
    return n if n-1 < x <= n else n+1

How all this relates to the linked Loan and payment calculator problem:

screenshot of loan calculator output

From the sample output it appears that they rounded up the monthly payment, which is what many call the effect of the ceiling function. This means that each month a little more than 1/12 of the total amount is being paid. That made the final payment a little smaller than usual — leaving a remaining unpaid balance of only 8.76.

It would have been equally valid to use normal rounding producing a monthly payment of 8.83 and a slightly higher final payment of 8.87. However, in the real world people generally don't like to have their payments go up, so rounding up each payment is the common practice — it also returns the money to the lender more quickly.

How to leave space in HTML

As others already answered, $nbsp; will output no-break space character. Here is w3 docs for &nbsp and others.

However there is other ways to do it and nowdays i would prefer using CSS stylesheets. There is also w3c tutorials for beginners.

With CSS you can do it like this:

<html>
    <head>
        <title>CSS test</title>
        <style type="text/css">
            p { word-spacing: 40px; }
        </style>
    </head>
    <body>
        <p>Hello World! Enough space between words, what do you think about it?</p>
    </body>
</html>

Pip freeze vs. pip list

The main difference is that the output of pip freeze can be dumped into a requirements.txt file and used later to re-construct the "frozen" environment.

In other words you can run: pip freeze > frozen-requirements.txt on one machine and then later on a different machine or on a clean environment you can do: pip install -r frozen-requirements.txt and you'll get the an identical environment with the exact same dependencies installed as you had in the original environment where you generated the frozen-requirements.txt.

How do you count the elements of an array in java

What do you mean by "the count"? The number of elements with a non-zero value? You'd just have to count them.

There's no distinction between that array and one which has explicitly been set with zero values. For example, these arrays are indistinguishable:

int[] x = { 0, 0, 0 };
int[] y = new int[3];

Arrays in Java always have a fixed size - accessed via the length field. There's no concept of "the amount of the array currently in use".

jQuery UI " $("#datepicker").datepicker is not a function"

I know that this post is quite old, but for reference I fixed this issue by updating the version of datepicker

It is worth trying that too to avoid hours of debugging.

https://cdnjs.com/libraries/bootstrap-datepicker

Generate list of all possible permutations of a string

Recursive Solution with driver main() method.

public class AllPermutationsOfString {
public static void stringPermutations(String newstring, String remaining) {
    if(remaining.length()==0)
        System.out.println(newstring);

    for(int i=0; i<remaining.length(); i++) {
        String newRemaining = remaining.replaceFirst(remaining.charAt(i)+"", "");
        stringPermutations(newstring+remaining.charAt(i), newRemaining);
    }
}

public static void main(String[] args) {
    String string = "abc";
    AllPermutationsOfString.stringPermutations("", string); 
}

}

Terminating a Java Program

  1. System.exit() is a method that causes JVM to exit.
  2. return just returns the control to calling function.
  3. return 8 will return control and value 8 to calling method.

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

How to create new folder?

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)

Git error on commit after merge - fatal: cannot do a partial commit during a merge

  1. go to your project directory
    1. display hidden files (.git folder will appear)
    2. open .git folder
    3. remove MERGE_HEAD
    4. commit again
    5. if git told you that git is locked go back to .git folder and remove index.lock
    6. commit again everything will work fine this time .

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I've used Wiredesignz's MY_Language class with great success.

I've just published it on github, as I can't seem to find a trace of it anywhere.

https://github.com/meigwilym/CI_Language

My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
    ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;

Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

How to dismiss a Twitter Bootstrap popover by clicking outside?

This is late to the party... but I thought I'd share it. I love the popover but it has so little built-in functionality. I wrote a bootstrap extension .bubble() that is everything I'd like popover to be. Four ways to dismiss. Click outside, toggle on the link, click the X, and hit escape.

It positions automatically so it never goes off the page.

https://github.com/Itumac/bootstrap-bubble

This is not a gratuitous self promo...I've grabbed other people's code so many times in my life, I wanted to offer my own efforts. Give it a whirl and see if it works for you.

How to copy file from HDFS to the local file system

In order to copy files from HDFS to the local file system the following command could be run:

hadoop dfs -copyToLocal <input> <output>

  • <input>: the HDFS directory path (e.g /mydata) that you want to copy
  • <output>: the destination directory path (e.g. ~/Documents)

How to remove all white space from the beginning or end of a string?

String.Trim() removes all whitespace from the beginning and end of a string. To remove whitespace inside a string, or normalize whitespace, use a Regular Expression.

How to implement the Softmax function in Python

I was curious to see the performance difference between these

import numpy as np

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    return np.exp(x) / np.sum(np.exp(x), axis=0)

def softmaxv2(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum()

def softmaxv3(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / np.sum(e_x, axis=0)

def softmaxv4(x):
    """Compute softmax values for each sets of scores in x."""
    return np.exp(x - np.max(x)) / np.sum(np.exp(x - np.max(x)), axis=0)



x=[10,10,18,9,15,3,1,2,1,10,10,10,8,15]

Using

print("----- softmax")
%timeit  a=softmax(x)
print("----- softmaxv2")
%timeit  a=softmaxv2(x)
print("----- softmaxv3")
%timeit  a=softmaxv2(x)
print("----- softmaxv4")
%timeit  a=softmaxv2(x)

Increasing the values inside x (+100 +200 +500...) I get consistently better results with the original numpy version (here is just one test)

----- softmax
The slowest run took 8.07 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 17.8 µs per loop
----- softmaxv2
The slowest run took 4.30 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23 µs per loop
----- softmaxv3
The slowest run took 4.06 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23 µs per loop
----- softmaxv4
10000 loops, best of 3: 23 µs per loop

Until.... the values inside x reach ~800, then I get

----- softmax
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: overflow encountered in exp
  after removing the cwd from sys.path.
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in true_divide
  after removing the cwd from sys.path.
The slowest run took 18.41 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23.6 µs per loop
----- softmaxv2
The slowest run took 4.18 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 22.8 µs per loop
----- softmaxv3
The slowest run took 19.44 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23.6 µs per loop
----- softmaxv4
The slowest run took 16.82 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 22.7 µs per loop

As some said, your version is more numerically stable 'for large numbers'. For small numbers could be the other way around.

Read XML file into XmlDocument

Hope you dont mind Xml.Linq and .net3.5+

XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);

Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

How do I find the distance between two points?

Let's not forget math.hypot:

dist = math.hypot(x2-x1, y2-y1)

Here's hypot as part of a snippet to compute the length of a path defined by a list of (x, y) tuples:

from math import hypot

pts = [
    (10,10),
    (10,11),
    (20,11),
    (20,10),
    (10,10),
    ]

# Py2 syntax - no longer allowed in Py3
# ptdiff = lambda (p1,p2): (p1[0]-p2[0], p1[1]-p2[1])
ptdiff = lambda p1, p2: (p1[0]-p2[0], p1[1]-p2[1])

diffs = (ptdiff(p1, p2) for p1, p2 in zip (pts, pts[1:]))
path = sum(hypot(*d) for d in  diffs)
print(path)

Finding duplicate rows in SQL Server

select o.orgName, oc.dupeCount, o.id
from organizations o
inner join (
    SELECT orgName, COUNT(*) AS dupeCount
    FROM organizations
    GROUP BY orgName
    HAVING COUNT(*) > 1
) oc on o.orgName = oc.orgName

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

JavaScript listener, "keypress" doesn't detect backspace?

event.key === "Backspace"

More recent and much cleaner: use event.key. No more arbitrary number codes!

note.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace") {
        // Do something
    }
});

Mozilla Docs

Supported Browsers

Check if user is using IE

Many answers here, and I'd like to add my input. IE 11 was being such an ass concerning flexbox (see all its issues and inconsistencies here) that I really needed an easy way to check if a user is using any IE browser (up to and including 11) but excluding Edge, because Edge is actually pretty nice.

Based on the answers given here, I wrote a simple function returning a global boolean variable which you can then use down the line. It's very easy to check for IE.

var isIE;
(function() {
    var ua = window.navigator.userAgent,
        msie = ua.indexOf('MSIE '),
        trident = ua.indexOf('Trident/');

    isIE = (msie > -1 || trident > -1) ? true : false;
})();

if (isIE) {
    alert("I am an Internet Explorer!");
}

This way you only have to do the look up once, and you store the result in a variable, rather than having to fetch the result on each function call. (As far as I know you don't even have to wait for document ready to execute this code as the user-agent is not related to the DOM.)

How can I delay a method call for 1 second?

There are already a lot of answers and they are all correct. In case you want to use the dispatch_after you should be looking for the snippet which is included inside the Code Snippet Library at the right bottom (where you can select the UI elements).

enter image description here

So you just need to call this snippet by writing dispatch in code:

enter image description here

Java switch statement multiple cases

According to this question, it's totally possible.

Just put all cases that contain the same logic together, and don't put break behind them.

switch (var) {
    case (value1):
    case (value2):
    case (value3):
        //the same logic that applies to value1, value2 and value3
        break;
    case (value4):
        //another logic
        break;
}

It's because case without break will jump to another case until break or return.

EDIT:

Replying the comment, if we really have 95 values with the same logic, but a way smaller number of cases with different logic, we can do:

switch (var) {
     case (96):
     case (97):
     case (98):
     case (99):
     case (100):
         //your logic, opposite to what you put in default.
         break;
     default: 
         //your logic for 1 to 95. we enter default if nothing above is met. 
         break;
}

If you need finer control, if-else is the choice.

Using C++ base class constructors?

Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used

  B( int v) : A( v )
  {
  }

Getting the WordPress Post ID of current post

you can use $post->ID for current id.

Eclipse - java.lang.ClassNotFoundException

All I did was Properties -> Java Build Path -> Order and Export -> Enabled all unchecked boxes -> moved Junit all the way up

Create the perfect JPA entity

Entity interface

public interface Entity<I> extends Serializable {

/**
 * @return entity identity
 */
I getId();

/**
 * @return HashCode of entity identity
 */
int identityHashCode();

/**
 * @param other
 *            Other entity
 * @return true if identities of entities are equal
 */
boolean identityEquals(Entity<?> other);
}

Basic implementation for all Entities, simplifies Equals/Hashcode implementations:

public abstract class AbstractEntity<I> implements Entity<I> {

@Override
public final boolean identityEquals(Entity<?> other) {
    if (getId() == null) {
        return false;
    }
    return getId().equals(other.getId());
}

@Override
public final int identityHashCode() {
    return new HashCodeBuilder().append(this.getId()).toHashCode();
}

@Override
public final int hashCode() {
    return identityHashCode();
}

@Override
public final boolean equals(final Object o) {
    if (this == o) {
        return true;
    }
    if ((o == null) || (getClass() != o.getClass())) {
        return false;
    }

    return identityEquals((Entity<?>) o);
}

@Override
public String toString() {
    return getClass().getSimpleName() + ": " + identity();
    // OR 
    // return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

Room Entity impl:

@Entity
@Table(name = "ROOM")
public class Room extends AbstractEntity<Integer> {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Integer id;

@Column(name = "number") 
private String number; //immutable

@Column(name = "capacity")
private Integer capacity;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "building_id")
private Building building; //immutable

Room() {
    // default constructor
}

public Room(Building building, String number) {
    // constructor with required field
    notNull(building, "Method called with null parameter (application)");
    notNull(number, "Method called with null parameter (name)");

    this.building = building;
    this.number = number;
}

public Integer getId(){
    return id;
}

public Building getBuilding() {
    return building;
}

public String getNumber() {
    return number;
}


public void setCapacity(Integer capacity) {
    this.capacity = capacity;
}

//no setters for number, building nor id
}

I don't see a point of comparing equality of entities based on business fields in every case of JPA Entities. That might be more of a case if these JPA entities are thought of as Domain-Driven ValueObjects, instead of Domain-Driven Entities (which these code examples are for).

How to get Locale from its String representation in Java?

If you are using Spring framework in your project you can also use:

org.springframework.util.StringUtils.parseLocaleString("en_US");

Documentation:

Parse the given String representation into a Locale

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

How to identify a strong vs weak relationship on ERD?

The relationship Room to Class is considered weak (non-identifying) because the primary key components CID and DATE of entity Class doesn't contain the primary key RID of entity Room (in this case primary key of Room entity is a single component, but even if it was a composite key, one component of it also fulfills the condition).

However, for instance, in the case of the relationship Class and Class_Ins we see that is a strong (identifying) relationship because the primary key components EmpID and CID and DATE of Class_Ins contains a component of the primary key Class (in this case it contains both components CID and DATE).

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

keep using the id


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserVerification extends Model
{
    protected $table = 'user_verification';
    protected $fillable =   [
                            'id',
                            'email',
                            'verification_token'
                            ];
    //$timestamps = false;
    protected $primaryKey = 'verification_token';
}

and get the email :

$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);

CSS Animation and Display None

How do I have a div not take up space until it is timed to come in (using CSS for the timing.)

Here is my solution to the same problem.

Moreover I have an onclick on the last frame loading another slideshow, and it must not be clickable until the last frame is visible.

Basically my solution is to keep the div 1 pixel high using a scale(0.001), zooming it when I need it. If you don't like the zoom effect you can restore the opacity to 1 after zooming the slide.

#Slide_TheEnd {

    -webkit-animation-delay: 240s;
    animation-delay: 240s;

    -moz-animation-timing-function: linear;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;

    -moz-animation-duration: 20s;
    -webkit-animation-duration: 20s;
    animation-duration: 20s;

    -moz-animation-name: Slide_TheEnd;
    -webkit-animation-name: Slide_TheEnd;
    animation-name: Slide_TheEnd;

    -moz-animation-iteration-count: 1;
    -webkit-animation-iteration-count: 1;
    animation-iteration-count: 1;

    -moz-animation-direction: normal;
    -webkit-animation-direction: normal;
    animation-direction: normal;

    -moz-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;

    transform: scale(0.001);
    background: #cf0;
    text-align: center;
    font-size: 10vh;
    opacity: 0;
}

@-moz-keyframes Slide_TheEnd {
    0% { opacity: 0;  transform: scale(0.001); }
    10% { opacity: 1; transform: scale(1); }
    95% { opacity: 1; transform: scale(1); }
    100% { opacity: 0;  transform: scale(0.001); }
}

Other keyframes are removed for the sake of bytes. Please disregard the odd coding, it is made by a php script picking values from an array and str_replacing a template: I'm too lazy to retype everything for every proprietary prefix on a 100+ divs slideshow.

Select subset of columns in data.table R

This seems an improvement:

> cols<-!(colnames(dt) %in% c("V1","V2","V3","V5"))
> new_dt<-subset(dt,,cols)
> cor(new_dt)
            V4          V6          V7          V8         V9         V10
V4   1.0000000  0.14141578 -0.44466832  0.23697216 -0.1020074  0.48171747
V6   0.1414158  1.00000000 -0.21356218 -0.08510977 -0.1884202 -0.22242274
V7  -0.4446683 -0.21356218  1.00000000 -0.02050846  0.3209454 -0.15021528
V8   0.2369722 -0.08510977 -0.02050846  1.00000000  0.4627034 -0.07020571
V9  -0.1020074 -0.18842023  0.32094540  0.46270335  1.0000000 -0.19224973
V10  0.4817175 -0.22242274 -0.15021528 -0.07020571 -0.1922497  1.00000000

This one is not quite as easy to grasp but might have use for situations there there were a need to specify columns by a numeric vector:

subset(dt, , !grepl(paste0("V", c(1:3,5),collapse="|"),colnames(dt) ))

URL string format for connecting to Oracle database with JDBC

String host = <host name>
String port = <port>
String service = <service name>
String dbName = <db schema>+"."+service
String url = "jdbc:oracle:thin:@"+host+":"+"port"+"/"+dbName

How to initialize an array in Java?

you are trying to set the 10th element of the array to the array try

data = new int[] {10,20,30,40,50,60,71,80,90,91};

FTFY

Retrieve a single file from a repository

for bitbucket directly from browser (I used safari...) right-click on 'View Raw" and choose "Download Linked File":

enter image description here

How do you get a directory listing sorted by creation date in python?

this is a basic step for learn:

import os, stat, sys
import time

dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

listdir = os.listdir(dirpath)

for i in listdir:
    os.chdir(dirpath)
    data_001 = os.path.realpath(i)
    listdir_stat1 = os.stat(data_001)
    listdir_stat2 = ((os.stat(data_001), data_001))
    print time.ctime(listdir_stat1.st_ctime), data_001

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I solved just by: given correct host and port so:

  1. Open oracle net manager
  2. Local
  3. Listener

in Listener on address 2 then copy host to Oracle Developer

finally connect to oracle

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.

Example:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Deleting array elements in JavaScript - delete vs splice

delete Vs splice

when you delete an item from an array

_x000D_
_x000D_
var arr = [1,2,3,4]; delete arr[2]; //result [1, 2, 3:, 4]_x000D_
console.log(arr)
_x000D_
_x000D_
_x000D_

when you splice

_x000D_
_x000D_
var arr = [1,2,3,4]; arr.splice(1,1); //result [1, 3, 4]_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

in case of delete the element is deleted but the index remains empty

while in case of splice element is deleted and the index of rest elements is reduced accordingly

The import javax.persistence cannot be resolved

I solved the problem by adding the following dependency

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>2.2</version>
</dependency>

Together with

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

Do you use source control for your database items?

I use ActiveRecord Migrations. This Ruby gem can be used outside of a Rails project and there are adapters to handle most databases you'll come across. My tip: if you are able to run your project off Postgres, you get transactional schema migrations. That means you don't end up with a broken database if a migration only half-applies.

How do I update a Mongo document after inserting it?

In pymongo you can update with:
mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)
Upsert parameter will insert instead of updating if the post is not found in the database.
Documentation is available at mongodb site.

UPDATE For version > 3 use update_one instead of update:

mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)

Remove 'b' character do in front of a string literal in Python 3

Here u Go

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)

Tried to Load Angular More Than Once

For anyone that has this issue in the future, for me it was caused by an arrow function instead of a function literal in a run block:

// bad
module('a').run(() => ...)

// good
module('a').run(function() {...})

Laravel Eloquent compare date from datetime field

Have you considered using:

where('date', '<', '2014-08-11')

You should avoid using the DATE() function on indexed columns in MySQL, as this prevents the engine from using the index.

UPDATE

As there seems to be some disagreement about the importance of DATE() and indexes, I have created a fiddle that demonstrates the difference, see POSSIBLE KEYS.

PHP regular expression - filter number only

Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:

$output = preg_replace( '/[^0-9]/', '', $string );

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

Git Bash is extremely slow on Windows 7 x64

Combined answers:

  1. Wilbert's - what info to include in PS1
  2. sinelaw's - (<branch_name>) or (<sha>)
# https://unix.stackexchange.com/questions/140610/using-variables-to-store-terminal-color-codes-for-ps1/140618#140618
# https://unix.stackexchange.com/questions/124407/what-color-codes-can-i-use-in-my-ps1-prompt
# \033 is the same as \e
# 0;32 is the same as 32
CYAN="$(echo -e "\e[1;36m")"
GREEN="$(echo -e "\e[32m")"
YELLOW="$(echo -e "\e[33m")"
RESET="$(echo -e "\e[0m")"

# https://stackoverflow.com/questions/4485059/git-bash-is-extremely-slow-in-windows-7-x64/19500237#19500237
# https://stackoverflow.com/questions/4485059/git-bash-is-extremely-slow-in-windows-7-x64/13476961#13476961
# https://stackoverflow.com/questions/39518124/check-if-directory-is-git-repository-without-having-to-cd-into-it/39518382#39518382
fast_git_ps1 ()
{
    git -C . rev-parse 2>/dev/null && echo " ($((git symbolic-ref --short -q HEAD || git rev-parse -q --short HEAD) 2> /dev/null))"
}

# you need \] at the end for colors
# Don't set \[ at the beginning or ctrl+up for history will work strangely
PS1='${GREEN}\u@\h ${YELLOW}\w${CYAN}$(fast_git_ps1)${RESET}\] $ '

Result:

frolowr@RWAMW36650 /c/projects/elm-math-kids (master) $

What is "loose coupling?" Please provide examples

Coupling has to do with dependencies between systems, which could be modules of code (functions, files, or classes), tools in a pipeline, server-client processes, and so forth. The less general the dependencies are, the more "tightly coupled" they become, since changing one system required changing the other systems that rely on it. The ideal situation is "loose coupling" where one system can be changed and the systems depending on it will continue to work without modification.

The general way to achieve loose coupling is through well defined interfaces. If the interaction between two systems is well defined and adhered to on both sides, then it becomes easier to modify one system while ensuring that the conventions are not broken. It commonly occurs in practice that no well-defined interface is established, resulting in a sloppy design and tight coupling.

Some examples:

  • Application depends on a library. Under tight coupling, app breaks on newer versions of the lib. Google for "DLL Hell".

  • Client app reads data from a server. Under tight coupling, changes to the server require fixes on the client side.

  • Two classes interact in an Object-Oriented hierarchy. Under tight coupling, changes to one class require the other class to be updated to match.

  • Multiple command-line tools communicate in a pipe. If they are tightly coupled, changes to the version of one command-line tool will cause errors in the tools that read its output.

How to modify memory contents using GDB?

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

Could not find a part of the path ... bin\roslyn\csc.exe

As already noted by https://stackoverflow.com/questions/32780315#34391473, the quick fix is to use the package manager, Tools > Nuget Package Manager > Package Manager Console, to run

Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r

Packet Manager Console - how to open

But an alternative solution (which automatically and silently recreates your packages if they are missing) is to remove an attribute of your project's Web.config file.
(Web.config is in the same directory as your .csproj file.)

Open the Web.config file in a text editor (or inside Visual Studio).
- In the tag configuration > system.codedom > compilers > compiler language="c#;cs;csharp", completely remove the type attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- ... -->
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

In short, remove the line that starts with type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.

(Presumably, the same fix works for Visual Basic as well as for Csharp, but I have not tried it.)

Visual Studio will take care of the rest. No more Server Error in '/' Application.

In the example code I provided in the zip file above you will now get HTTP Error 403 when you hit Ctrl+F5.

HTTP Error 403.14 - Forbidden

Try replacing http://localhost:64195 in your web browser with http://localhost:64195/api/products.
The web API now displays as it should:

A web API containing products

As a provocation, I tried removing the whole package directory of my Visual Studio solution.
It was automatically and silently recreated as soon as I (re-)built it.


Last but not least, here is code that reproduces the error: http://schulze.000webhostapp.com/vs/SrvrErr-reproduce.zip (Originally from https://github.com/aspnet/AspNetDocs/tree/master/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client/sample/server/ProductsApp)

Server Error

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

PowerShell - Start-Process and Cmdline Switches

Warning

If you run PowerShell from a cmd.exe window created by Powershell, the 2nd instance no longer waits for jobs to complete.

cmd>  PowerShell
PS> Start-Process cmd.exe -Wait 

Now from the new cmd window, run PowerShell again and within it start a 2nd cmd window: cmd2> PowerShell

PS> Start-Process cmd.exe -Wait
PS>   

The 2nd instance of PowerShell no longer honors the -Wait request and ALL background process/jobs return 'Completed' status even thou they are still running !

I discovered this when my C# Explorer program is used to open a cmd.exe window and PS is run from that window, it also ignores the -Wait request. It appears that any PowerShell which is a 'win32 job' of cmd.exe fails to honor the wait request.

I ran into this with PowerShell version 3.0 on windows 7/x64

Git Symlinks in Windows

The most recent version of git scm (testet 2.11.1) allows to enable symbolic links. But you have to clone the repository with the symlinks again git clone -c core.symlinks=true <URL>. You need to run this command with administrator rights. It is also possible to create symlinks on Windows with mklink. Check out the wiki.

enter image description here

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

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

File name without extension name VBA

To be verbose it the removal of extension is demonstrated for workbooks.. which now have a variety of extensions . . a new unsaved Book1 has no ext . works the same for files

Function WorkbookIsOpen(FWNa$, Optional AnyExt As Boolean = False) As Boolean

Dim wWB As Workbook, WBNa$, PD%
FWNa = Trim(FWNa)
If FWNa <> "" Then
    For Each wWB In Workbooks
        WBNa = wWB.Name
        If AnyExt Then
            PD = InStr(WBNa, ".")
            If PD > 0 Then WBNa = Left(WBNa, PD - 1)
            PD = InStr(FWNa, ".")
            If PD > 0 Then FWNa = Left(FWNa, PD - 1)
            '
            ' the alternative of using split..  see commented out  below
            ' looks neater but takes a bit longer then the pair of instr and left
            ' VBA does about 800,000  of these small splits/sec
            ' and about 20,000,000  Instr Lefts per sec
            ' of course if not checking for other extensions they do not matter
            ' and to any reasonable program
            ' THIS DISCUSSIONOF TIME TAKEN DOES NOT MATTER
            ' IN doing about doing 2000 of this routine per sec

            ' WBNa = Split(WBNa, ".")(0)
            'FWNa = Split(FWNa, ".")(0)
        End If

        If WBNa = FWNa Then
            WorkbookIsOpen = True
            Exit Function
        End If
    Next wWB
End If

End Function

Python class input argument

>>> class name(object):
...     def __init__(self, name):
...         self.name = name
... 
>>> person1 = name("jean")
>>> person2 = name("dean")
>>> person1.name
'jean'
>>> person2.name
'dean'
>>>

.NET Core vs Mono

This is one of my favorite topics and the content here was just amazing. I was thinking if it would be worth while or effective to compare the methods available in Runtime vs. Mono. I hope I got my terms right, but I think you know what I mean. In order to have a somewhat better understanding of what each Runtime supports currently, would it make sense to compare the methods they provide? I realize implementations may vary, and I have not considered the Framework Class libraries or the slew of other libraries available in one environment vs. the other. I also realize someone might have already done this work even more efficiently. I would be most grateful if you would let me know so I can review it. I feel doing a diff between the outcome of such activity would be of value, and wanted to see how more experienced developers feel about it, and would they provide useful guidance. While back I was playing with reflection, and wrote some lines that traverse the .net directory, and list the assemblies.

How can I specify a [DllImport] path at runtime?

If you need a .dll file that is not on the path or on the application's location, then I don't think you can do just that, because DllImport is an attribute, and attributes are only metadata that is set on types, members and other language elements.

An alternative that can help you accomplish what I think you're trying, is to use the native LoadLibrary through P/Invoke, in order to load a .dll from the path you need, and then use GetProcAddress to get a reference to the function you need from that .dll. Then use these to create a delegate that you can invoke.

To make it easier to use, you can then set this delegate to a field in your class, so that using it looks like calling a member method.

EDIT

Here is a code snippet that works, and shows what I meant.

class Program
{
    static void Main(string[] args)
    {
        var a = new MyClass();
        var result = a.ShowMessage();
    }
}

class FunctionLoader
{
    [DllImport("Kernel32.dll")]
    private static extern IntPtr LoadLibrary(string path);

    [DllImport("Kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public static Delegate LoadFunction<T>(string dllPath, string functionName)
    {
        var hModule = LoadLibrary(dllPath);
        var functionAddress = GetProcAddress(hModule, functionName);
        return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof (T));
    }
}

public class MyClass
{
    static MyClass()
    {
        // Load functions and set them up as delegates
        // This is just an example - you could load the .dll from any path,
        // and you could even determine the file location at runtime.
        MessageBox = (MessageBoxDelegate) 
            FunctionLoader.LoadFunction<MessageBoxDelegate>(
                @"c:\windows\system32\user32.dll", "MessageBoxA");
    }

    private delegate int MessageBoxDelegate(
        IntPtr hwnd, string title, string message, int buttons); 

    /// <summary>
    /// This is the dynamic P/Invoke alternative
    /// </summary>
    static private MessageBoxDelegate MessageBox;

    /// <summary>
    /// Example for a method that uses the "dynamic P/Invoke"
    /// </summary>
    public int ShowMessage()
    {
        // 3 means "yes/no/cancel" buttons, just to show that it works...
        return MessageBox(IntPtr.Zero, "Hello world", "Loaded dynamically", 3);
    }
}

Note: I did not bother to use FreeLibrary, so this code is not complete. In a real application, you should take care to release the loaded modules to avoid a memory leak.

Jenkins - Configure Jenkins to poll changes in SCM

I believe best practice these days is H/5 * * * *, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.

Is it possible to interactively delete matching search pattern in Vim?

http://vim.wikia.com/wiki/Search_and_replace

Try this search and replace:

:%s/foo/bar/gc

Change each 'foo' to 'bar', but ask for confirmation first.

Press y or n to change or keep your text.

Set SSH connection timeout

The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".

The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.

MySQL "between" clause not inclusive?

Is the field you are referencing in your query a Date type or a DateTime type?

A common cause of the behavior you describe is when you use a DateTime type where you really should be using a Date type. That is, unless you really need to know what time someone was born, just use the Date type.

The reason the final day is not being included in your results is the way that the query is assuming the time portion of the dates that you did not specify in your query.

That is: Your query is being interpreted as up to Midnight between 2011-01-30 and 2011-01-31, but the data may have a value sometime later in the day on 2011-01-31.

Suggestion: Change the field to the Date type if it is a DateTime type.

Hibernate SessionFactory vs. JPA EntityManagerFactory

Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration.

Using similar callbacks while using SessionFactory will require extra efforts.

Related Hibernate docs can be found here and here.

Related SOF Question and Spring Forum discussion

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

Rounding to two decimal places in Python 2.7?

The best, I think, is to use the format() function:

>>> print("financial return of outcome 1 = $ " + format(str(out1), '.2f'))
// Should print: financial return of outcome 1 = $ 752.60

But I have to say: don't use round or format when working with financial values.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The is keyword is a test for object identity while == is a value comparison.

If you use is, the result will be true if and only if the object is the same object. However, == will be true any time the values of the object are the same.

How can I replace a regex substring match in Javascript?

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);

Or if you're sure there won't be any other digits in the string:

var str   = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);

How to use `@ts-ignore` for a block

If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx

Android Fragment no view found for ID?

This issue also happens when you don't put <include layout="@layout/your_fragment_layout"/> in your app_bar_main.xml

Rethrowing exceptions in Java without losing the stack trace

something like this

try 
{
  ...
}
catch (FooException e) 
{
  throw e;
}
catch (Exception e)
{
  ...
}

How to create a zip archive of a directory in Python?

As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:

#!/usr/bin/env python
import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..')))
  
if __name__ == '__main__':
    zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('tmp/', zipf)
    zipf.close()
 

Adapted from: http://www.devshed.com/c/a/Python/Python-UnZipped/

CSS: Set Div height to 100% - Pixels

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

Demo
+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +-- Application.java
|    ¦   
|    +-- test
|
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
EXPOSE 8080
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.5</version>
        <configuration>
            <imageName>springdocker</imageName>
            <baseImage>java</baseImage>
            <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
            <resources>
                <resource>
                    <targetPath>/</targetPath>
                    <directory>${project.build.directory}</directory>
                    <include>${project.build.finalName}.jar</include>
                </resource>
            </resources>
        </configuration>
    </plugin>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

Python Database connection Close

You might try turning off pooling, which is enabled by default. See this discussion for more information.

import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
del csr

Log4j2 configuration - No log4j2 configuration file found

Additionally to what Tomasz W wrote, by starting your application you could use settings:

-Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE 

to get most of configuration problems.

For details see Log4j2 FAQ: How do I debug my configuration?

yii2 redirect in controller action does not work?

You can redirect by this method also:

return Yii::$app->response->redirect(['user/index', 'id' => 10]);

If you want to send the Header information immediately use with send().This method adds a Location header to the current response.

return Yii::$app->response->redirect(['user/index', 'id' => 10])->send();

If you want the complete URL then use like Url::to(['user/index', 'id' => 302]) with the header of use yii\helpers\Url;.

For more information check Here. Hope this will help someone.

Python check if list items are integers?

The usual way to check whether something can be converted to an int is to try it and see, following the EAFP principle:

try:
    int_value = int(string_value)
except ValueError:
    # it wasn't an int, do something appropriate
else:
    # it was an int, do something appropriate

So, in your case:

for item in mylist:
    try:
        int_value = int(item)
    except ValueError:
        pass
    else:
        mynewlist.append(item) # or append(int_value) if you want numbers

In most cases, a loop around some trivial code that ends with mynewlist.append(item) can be turned into a list comprehension, generator expression, or call to map or filter. But here, you can't, because there's no way to put a try/except into an expression.

But if you wrap it up in a function, you can:

def raises(func, *args, **kw):
    try:
        func(*args, **kw)
    except:
        return True
    else:
        return False

mynewlist = [item for item in mylist if not raises(int, item)]

… or, if you prefer:

mynewlist = filter(partial(raises, int), item)

It's cleaner to use it this way:

def raises(exception_types, func, *args, **kw):
    try:
        func(*args, **kw)
    except exception_types:
        return True
    else:
        return False

This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True, but if any unexpected exceptions are raised, they'll propagate out. So:

mynewlist = [item for item in mylist if not raises(ValueError, int, item)]

… will do what you want, but:

mynewlist = [item for item in mylist if not raises(ValueError, item, int)]

… will raise a TypeError, as it should.

How to send a Post body in the HttpClient request in Windows Phone 8?

This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

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

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

How to execute raw SQL in Flask-SQLAlchemy app

Have you tried using connection.execute(text( <sql here> ), <bind params here> ) and bind parameters as described in the docs? This can help solve many parameter formatting and performance problems. Maybe the gateway error is a timeout? Bind parameters tend to make complex queries execute substantially faster.

Retrieving the output of subprocess.call()

I have the following solution. It captures the exit code, the stdout, and the stderr too of the executed external command:

import shlex
from subprocess import Popen, PIPE

def get_exitcode_stdout_stderr(cmd):
    """
    Execute the external command and get its exitcode, stdout and stderr.
    """
    args = shlex.split(cmd)

    proc = Popen(args, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    exitcode = proc.returncode
    #
    return exitcode, out, err

cmd = "..."  # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)

I also have a blog post on it here.

Edit: the solution was updated to a newer one that doesn't need to write to temp. files.

Rails: Default sort order for a rails model?

default_scope

This works for Rails 4+:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

For Rails 2.3, 3, you need this instead:

default_scope order('created_at DESC')

For Rails 2.x:

default_scope :order => 'created_at DESC'

Where created_at is the field you want the default sorting to be done on.

Note: ASC is the code to use for Ascending and DESC is for descending (desc, NOT dsc !).

scope

Once you're used to that you can also use scope:

class Book < ActiveRecord::Base
  scope :confirmed, :conditions => { :confirmed => true }
  scope :published, :conditions => { :published => true }
end

For Rails 2 you need named_scope.

:published scope gives you Book.published instead of Book.find(:published => true).

Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed.

With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.

You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:

scope :recent_books, lambda 
  { |since_when| where("created_at >= ?", since_when) }
  # Note the `where` is making use of AREL syntax added in Rails 3.

Finally you can disable default scope with:

Book.with_exclusive_scope { find(:all) } 

or even better:

Book.unscoped.all

which will disable any filter (conditions) or sort (order by).

Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+


So ... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!

In fact they are Class level methods as they operate on the 1 set of 'all' records.

Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }.

As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published where published is a named scope.

In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

PHP cURL not working - WAMP on Windows 7 64 bit

This work for me: http://www.mediafire.com/?3ay381k3cq59cm2 download a paste the file in ext folder PHP 5.4.3

Resize an Array while keeping current elements in Java?

It is not possible to change the Array Size. But you can copy the element of one array into another array by creating an Array of bigger size.

It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full

public class ResizingArrayStack1 {
    private String[] s;
    private int size = 0;
    private int index = 0;

    public void ResizingArrayStack1(int size) {
        this.size = size;
        s = new String[size];
    }


    public void push(String element) {
        if (index == s.length) {
            resize(2 * s.length);
        }
        s[index] = element;
        index++;
    }

    private void resize(int capacity) {
        String[] copy = new String[capacity];
        for (int i = 0; i < s.length; i++) {
            copy[i] = s[i];
            s = copy;
        }
    }

    public static void main(String[] args) {
        ResizingArrayStack1 rs = new ResizingArrayStack1();
        rs.push("a");
        rs.push("b");
        rs.push("c");
        rs.push("d");
    }
}

How to read until EOF from cin in C++

After researching KeithB's solution using std::istream_iterator, I discovered the std:istreambuf_iterator.

Test program to read all piped input into a string, then write it out again:

#include <iostream>
#include <iterator>
#include <string>

int main()
{
  std::istreambuf_iterator<char> begin(std::cin), end;
  std::string s(begin, end);
  std::cout << s;
}

Failed to execute removeChild on Node

Your myCoolDiv element isn't a child of the player container. It's a child of the div you created as a wrapper for it (markerDiv in the first part of the code). Which is why it fails, removeChild only removes children, not descendants.

You'd want to remove that wrapper div, or not add it at all.

Here's the "not adding it at all" option:

_x000D_
_x000D_
var markerDiv = document.createElement("div");_x000D_
markerDiv.innerHTML = "<div id='MyCoolDiv' style='color: #2b0808'>123</div>";_x000D_
document.getElementById("playerContainer").appendChild(markerDiv.firstChild);_x000D_
// -------------------------------------------------------------^^^^^^^^^^^_x000D_
_x000D_
setTimeout(function(){ _x000D_
    var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Or without using the wrapper (although it's quite handy for parsing that HTML):

_x000D_
_x000D_
var myCoolDiv = document.createElement("div");_x000D_
// Don't reall need this: myCoolDiv.id = "MyCoolDiv";_x000D_
myCoolDiv.style.color = "#2b0808";_x000D_
myCoolDiv.appendChild(_x000D_
  document.createTextNode("123")_x000D_
);_x000D_
document.getElementById("playerContainer").appendChild(myCoolDiv);_x000D_
_x000D_
setTimeout(function(){ _x000D_
    // No need for this, we already have it from the above:_x000D_
    // var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Recursive file search using PowerShell

Try this:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse | Where-Object { $_.Attributes -ne "Directory"}

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

Break a previous commit into multiple commits

git rebase --interactive can be used to split a commit into smaller commits. The Git docs on rebase have a concise walkthrough of the process - Splitting Commits:

In interactive mode, you can mark commits with the action "edit". However, this does not necessarily mean that git rebase expects the result of this edit to be exactly one commit. Indeed, you can undo the commit, or you can add other commits. This can be used to split a commit into two:

  • Start an interactive rebase with git rebase -i <commit>^, where <commit> is the commit you want to split. In fact, any commit range will do, as long as it contains that commit.

  • Mark the commit you want to split with the action "edit".

  • When it comes to editing that commit, execute git reset HEAD^. The effect is that the HEAD is rewound by one, and the index follows suit. However, the working tree stays the same.

  • Now add the changes to the index that you want to have in the first commit. You can use git add (possibly interactively) or git gui (or both) to do that.

  • Commit the now-current index with whatever commit message is appropriate now.

  • Repeat the last two steps until your working tree is clean.

  • Continue the rebase with git rebase --continue.

If you are not absolutely sure that the intermediate revisions are consistent (they compile, pass the testsuite, etc.) you should use git stash to stash away the not-yet-committed changes after each commit, test, and amend the commit if fixes are necessary.

How to display special characters in PHP

After much banging-head-on-table, I have a bit better understanding of the issue that I wanted to post for anyone else who may have had this issue.

While the UTF-8 character set will display special characters on the client, the server, on the other hand, may not be so accomodating and would print special characters such as à and è as ? and ?.

To make sure your server will print them correctly, use the ISO-8859-1 charset:

<?php
    /*Just for your server-side code*/
    header('Content-Type: text/html; charset=ISO-8859-1');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"><!-- Your HTML file can still use UTF-8-->
        <title>Untitled Document</title>
    </head>
    <body>
        <?= "àè" ?>
    </body>
</html>

This will print correctly: àè


Edit (4 years later):

I have a little better understanding now. The reason this works is that the client (browser) is being told, through the response header(), to expect an ISO-8859-1 text/html file. (As others have mentioned, you can also do this by updating your .ini or .htaccess files.) Then, once the browser begins to parse that given file into the DOM, the output will obey any <meta charset=""> rule but keep your ISO characters intact.

Force decimal point instead of comma in HTML5 number input (client-side)

As far as I understand it, the HTML5 input type="number always returns input.value as a string.

Apparently, input.valueAsNumber returns the current value as a floating point number. You could use this to return a value you want.

See http://diveintohtml5.info/forms.html#type-number

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.

Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.

cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.

Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.

Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

How to get N rows starting from row M from sorted table in T-SQL

@start = 3
@records = 2

Select ID, Value 
From
(SELECT ROW_NUMBER() OVER(ORDER BY ID) AS RowNum, ID,Value 
From MyTable) as sub
Where sub.RowNum between @start and @start+@records

This is one way. there are a lot of others if you google SQL Paging.

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...

@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)

This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...

model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;

May not be the best way, but it does work.

make bootstrap twitter dialog modal draggable

i did this:

$("#myModal").modal({}).draggable();

and it make my very standard/basic modal draggable.

not sure how/why it worked, but it did.

Detecting iOS orientation change instantly

Add a notifier in the viewWillAppear function

-(void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:)    name:UIDeviceOrientationDidChangeNotification  object:nil];
}

The orientation change notifies this function

- (void)orientationChanged:(NSNotification *)notification{
   [self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}

which in-turn calls this function where the moviePlayerController frame is orientation is handled

- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {

    switch (orientation)
    {
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
        { 
        //load the portrait view    
        }

            break;
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
        {
        //load the landscape view 
        }
            break;
        case UIInterfaceOrientationUnknown:break;
    }
}

in viewDidDisappear remove the notification

-(void)viewDidDisappear:(BOOL)animated{
   [super viewDidDisappear:animated];
   [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}

I guess this is the fastest u can have changed the view as per orientation

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

how to open a page in new tab on button click in asp.net?

Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.

<asp:LinkButton OnClientClick="openInNewTab();" .../>

In javaScript:

<script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank'; 
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</script>

Check if AJAX response data is empty/blank/null/undefined/0

$.ajax({
    type:"POST",
    url: "<?php echo admin_url('admin-ajax.php'); ?>",
    data: associated_buildsorprojects_form,
    success:function(data){
        // do console.log(data);
        console.log(data);
        // you'll find that what exactly inside data 
        // I do not prefer alter(data); now because, it does not 
        // completes requirement all the time 
        // After that you can easily put if condition that you do not want like
        // if(data != '')
        // if(data == null)
        // or whatever you want 
    },
    error: function(errorThrown){
        alert(errorThrown);
        alert("There is an error with AJAX!");
    }               
});

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

jQuery set checkbox checked

<div class="custom-control custom-switch">
      <input type="checkbox" class="custom-control-input" name="quiz_answer" id="customSwitch0">
      <label class="custom-control-label" for="customSwitch0"><span class="fa fa-minus fa-lg mt-1"></span></label>
  </div>

Remember to increment the the id and for attribute respectively. For Dynamically added bootstrap check box.

$(document).on('change', '.custom-switch', function(){
    let parent = $(this);
    parent.find('.custom-control-label > span').remove();
    let current_toggle = parent.find('.custom-control-input').attr('id');
    if($('#'+current_toggle+'').prop("checked") == true){
        parent.find('.custom-control-label').append('<span class="fa fa-check fa-lg mt-1"></span>');
    }
    else if($('#'+current_toggle+'').prop("checked") == false){
        parent.find('.custom-control-label').append('<span class="fa fa-minus fa-lg mt-1"></span>');
    }
})

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

Find out a Git branch creator

We can find out based upon authorname

git for-each-ref --format='%(authorname) %09 %(if)%(HEAD)%(then)*%(else)%(refname:short)%(end) %09 %(creatordate)' refs/remotes/ --sort=authorname DESC

Copying files from server to local computer using SSH

It depends on what your local OS is.

If your local OS is Unix-like, then try:

scp username@remoteHost:/remote/dir/file.txt /local/dir/

If your local OS is Windows ,then you should use pscp.exe utility. For example, below command will download file.txt from remote to D: disk of local machine.

pscp.exe username@remoteHost:/remote/dir/file.txt d:\

It seems your Local OS is Unix, so try the former one.


For those who don't know what pscp.exe is and don't know where it is, you can always go to putty official website to download it. And then open a CMD prompt, go to the pscp.exe directory where you put it. Then execute the command as provided above

Uncompress tar.gz file

Try this:

tar -zxvf file.tar.gz

Setting Custom ActionBar Title from Fragment

I am getting a very simple solution to set ActionBar Title in either fragment or any activity without any headache.

Just modify the xml where is defined Toolbar as below :

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimaryDark"
            app:popupTheme="@style/AppTheme.PopupOverlay" >

            <TextView
                style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                android:id="@+id/toolbar_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                />
            </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout> 

1) If you want to set the actionbar in a fragment then :

Toolbar toolbar = findViewById(R.id.toolbar);
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);

For using it from anywhere, you can define a method in the activity

public void setActionBarTitle(String title) {
        toolbarTitle.setText(title);
    }

To call this method in activity, simply call it.

setActionBarTitle("Your Title")

To call this method from fragment of the activity, simply call it.

((MyActivity)getActivity()).setActionBarTitle("Your Title");

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

CSS3 Fade Effect

The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..

E.g.

a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}

How do I install the ext-curl extension with PHP 7?

If you are using PHP7.1 ( try php -version to find your PHP version)

sudo apt-get install php7.1-curl

then restart apache

sudo service apache2 restart

What is the best way to determine a session variable is null or empty in C#?

That is pretty much how you do it. However, there is a shorter syntax you can use.

sSession = (string)Session["variable"] ?? "set this";

This is saying if the session variables is null, set sSession to "set this"

C# Example of AES256 encryption using System.Security.Cryptography.Aes

public class AesCryptoService
{
    private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
    private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");


    public static string EncryptStringToBytes_Aes(string plainText)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;


        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        
        return Convert.ToBase64String(encrypted);
    }


    
    public static string DecryptStringFromBytes_Aes(string Text)
    {
        if (Text == null || Text.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;
        byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;


            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
    }
}

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

How to send a correct authorization header for basic authentication

PHP - curl:

$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...

PHP - POST in WordPress:

$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode("$username:$password")
  )
));
...

How can I use UserDefaults in Swift?

I would say Anbu's answer perfectly fine but I had to add guard while fetching preferences to make my program doesn't fail

Here is the updated code snip in Swift 5

Storing data in UserDefaults

@IBAction func savePreferenceData(_ sender: Any) {
        print("Storing data..")
        UserDefaults.standard.set("RDC", forKey: "UserName") //String
        UserDefaults.standard.set("TestPass", forKey: "Passowrd")  //String
        UserDefaults.standard.set(21, forKey: "Age")  //Integer

    }

Fetching data from UserDefaults

    @IBAction func fetchPreferenceData(_ sender: Any) {
        print("Fetching data..")

        //added guard
        guard let uName = UserDefaults.standard.string(forKey: "UserName") else { return }
        print("User Name is :"+uName)
        print(UserDefaults.standard.integer(forKey: "Age"))
    }

Toolbar overlapping below status bar

None of the answers worked for me, but this is what finally worked after i set android:fitSystemWindows on the root view(I set these in styles v21):

<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:windowTranslucentStatus">false</item>

Make sure you don't have the following line as AS puts it by default:

<item name="android:statusBarColor">@android:color/transparent</item>

How do I remove duplicate items from an array in Perl?

You can do something like this as demonstrated in perlfaq4:

sub uniq {
    my %seen;
    grep !$seen{$_}++, @_;
}

my @array = qw(one two three two three);
my @filtered = uniq(@array);

print "@filtered\n";

Outputs:

one two three

If you want to use a module, try the uniq function from List::MoreUtils

I want to declare an empty array in java and then I want do update it but the code is not working

You are creating an array of zero length (no slots to put anything in)

 int array[]={/*nothing in here = array with no elements*/};

and then trying to assign values to array elements (which you don't have, because there are no slots)

array[i] = number; //array[i] = element i in the array of length 0

You need to define a larger array to fit your needs

 int array[] = new int[4]; //Create an array with 4 elements [0],[1],[2] and [3] each containing an int value

Installing Bower on Ubuntu

Ubuntu 16.04 and later

Bower is a package manager primarily for (but not limited to) front-end web development. In Ubuntu 16.04 and later Bower package manager can be quickly and easily installed from the Ubuntu Software app. Open Ubuntu Software, search for "bower" and click the Install button to install it. In all currently supported versions of Ubuntu open the terminal and type:

sudo snap install bower --classic

enter image description here

jQuery: keyPress Backspace won't fire?

I came across this myself. I used .on so it looks a bit different but I did this:

 $('#element').on('keypress', function() {
   //code to be executed
 }).on('keydown', function(e) {
   if (e.keyCode==8)
     $('element').trigger('keypress');
 });

Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery

  $(this).bind("keydown", function (event) {
        // Allow: backspace, delete
        if (event.keyCode == 46 || event.keyCode == 8) 
        {
            var tempField = $(this).attr('name');
            var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
            $('#' + hiddenID).val('');
            $(this).val('')
            return;
        }  // Allow: tab, escape, and enter
        else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
        // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else 
        {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) &&       (event.keyCode < 96 || event.keyCode > 105)) 
            {
                event.preventDefault();
            }
        }
    });

Why is conversion from string constant to 'char*' valid in C but invalid in C++

Up through C++03, your first example was valid, but used a deprecated implicit conversion--a string literal should be treated as being of type char const *, since you can't modify its contents (without causing undefined behavior).

As of C++11, the implicit conversion that had been deprecated was officially removed, so code that depends on it (like your first example) should no longer compile.

You've noted one way to allow the code to compile: although the implicit conversion has been removed, an explicit conversion still works, so you can add a cast. I would not, however, consider this "fixing" the code.

Truly fixing the code requires changing the type of the pointer to the correct type:

char const *p = "abc"; // valid and safe in either C or C++.

As to why it was allowed in C++ (and still is in C): simply because there's a lot of existing code that depends on that implicit conversion, and breaking that code (at least without some official warning) apparently seemed to the standard committees like a bad idea.

How do I change screen orientation in the Android emulator?

My virtual device could not be rotated. Go to the device list, click settings and change the predefined resolution.

Open a URL without using a browser from a batch file

You can use this command:

start /min iexplore http://www.google.com

With the use of /min, it will hit on the URL without opening in the browser.

How to limit file upload type file size in PHP?

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

Look into the docs for move_uploaded_file() (it's called move not store) for more.

Javascript getElementsByName.value not working

You have mentioned Wrong id

alert(document.getElementById("name").value);

if you want to use name attribute then

alert(document.getElementsByName("username")[0].value);

Updates:

input type="text" id="name" name="username"  

id is different from name

How to customize <input type="file">?

In webkit you can try this out...

input[type="file"]::-webkit-file-upload-button{
   /* style goes here */
}

Get current controller in view

Just use:

ViewContext.Controller.GetType().Name

This will give you the whole Controller's Name

Print JSON parsed object?

Most debugger consoles support displaying objects directly. Just use

console.log(obj);

Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.

Extracting text from HTML file using Python

in a simple way

import re

html_text = open('html_file.html').read()
text_filtered = re.sub(r'<(.*?)>', '', html_text)

this code finds all parts of the html_text started with '<' and ending with '>' and replace all found by an empty string

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

How to align texts inside of an input?

Without CSS: Use the STYLE property of text input

STYLE="text-align: right;"

Push local Git repo to new remote including all branches and tags

Here is another take on the same thing which worked better for the situation I was in. It solves the problem where you have more than one remote, would like to clone all branches in remote source to remote destination but without having to check them all out beforehand.

(The problem I had with Daniel's solution was that it would refuse to checkout a tracking branch from the source remote if I had previously checked it out already, ie, it would not update my local branch before the push)

git push destination +refs/remotes/source/*:refs/heads/*

Note: If you are not using direct CLI, you must escape the asterisks:

git push destination +refs/remotes/source/\*:refs/heads/\*

this will push all branches in remote source to a head branch in destination, possibly doing a non-fast-forward push. You still have to push tags separately.

Are HTTP headers case-sensitive?

the Headers word are not case sensitive, but on the right like the Content-Type, is good practice to write it this way, because its case sensitve. like my example below

headers = headers.set('Content-Type'

Rails 4: List of available datatypes

It is important to know not only the types but the mapping of these types to the database types, too:

enter image description here

enter image description here


Source added - Agile Web Development with Rails 4

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

If you are using Spring Security ver >= 3.2, you can use the @AuthenticationPrincipal annotation:

@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(@AuthenticationPrincipal CustomUser currentUser, HttpServletRequest request) {
    String currentUsername = currentUser.getUsername();
    // ...
}

Here, CustomUser is a custom object that implements UserDetails that is returned by a custom UserDetailsService.

More information can be found in the @AuthenticationPrincipal chapter of the Spring Security reference docs.

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

for i in *.xls ; do 
  [[ -f "$i" ]] || continue
  xls2csv "$i" "${i%.xls}.csv"
done

The first line in the do checks if the "matching" file really exists, because in case nothing matches in your for, the do will be executed with "*.xls" as $i. This could be horrible for your xls2csv.

WebAPI to Return XML

If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage and use the below code to return the XML.

public HttpResponseMessage Authenticate()
{
  //process the request 
  .........

  string XML="<note><body>Message content</body></note>";
  return new HttpResponseMessage() 
  { 
    Content = new StringContent(XML, Encoding.UTF8, "application/xml") 
  };
}

This is the quickest way to always return XML from Web API.

converting Java bitmap to byte array

In order to avoid OutOfMemory error for bigger files, I would solve the task by splitting a bitmap into several parts and merging their parts' bytes.

private byte[] getBitmapBytes(Bitmap bitmap)
{
    int chunkNumbers = 10;
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    byte[] imageBytes = new byte[bitmapSize];
    int rows, cols;
    int chunkHeight, chunkWidth;
    rows = cols = (int) Math.sqrt(chunkNumbers);
    chunkHeight = bitmap.getHeight() / rows;
    chunkWidth = bitmap.getWidth() / cols;

    int yCoord = 0;
    int bitmapsSizes = 0;

    for (int x = 0; x < rows; x++)
    {
        int xCoord = 0;
        for (int y = 0; y < cols; y++)
        {
            Bitmap bitmapChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight);
            byte[] bitmapArray = getBytesFromBitmapChunk(bitmapChunk);
            System.arraycopy(bitmapArray, 0, imageBytes, bitmapsSizes, bitmapArray.length);
            bitmapsSizes = bitmapsSizes + bitmapArray.length;
            xCoord += chunkWidth;

            bitmapChunk.recycle();
            bitmapChunk = null;
        }
        yCoord += chunkHeight;
    }

    return imageBytes;
}


private byte[] getBytesFromBitmapChunk(Bitmap bitmap)
{
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapSize);
    bitmap.copyPixelsToBuffer(byteBuffer);
    byteBuffer.rewind();
    return byteBuffer.array();
}

How to identify numpy types in python?

That actually depends on what you're looking for.

  • If you want to test whether a sequence is actually a ndarray, a isinstance(..., np.ndarray) is probably the easiest. Make sure you don't reload numpy in the background as the module may be different, but otherwise, you should be OK. MaskedArrays, matrix, recarray are all subclasses of ndarray, so you should be set.
  • If you want to test whether a scalar is a numpy scalar, things get a bit more complicated. You could check whether it has a shape and a dtype attribute. You can compare its dtype to the basic dtypes, whose list you can find in np.core.numerictypes.genericTypeRank. Note that the elements of this list are strings, so you'd have to do a tested.dtype is np.dtype(an_element_of_the_list)...

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Remove the legend on a matplotlib figure

I made a legend by adding it to the figure, not to an axis (matplotlib 2.2.2). To remove it, I set the legends attribute of the figure to an empty list:

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.plot(range(10), range(10, 20), label='line 1')
ax2.plot(range(10), range(30, 20, -1), label='line 2')

fig.legend()

fig.legends = []

plt.show()

How to transfer paid android apps from one google account to another google account

You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.

There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).

How to check a Long for null in java

As mentioned already primitives can not be set to the Object type null.

What I do in such cases is just to use -1 or Long.MIN_VALUE.

Python3 project remove __pycache__ folders and .pyc files

macOS & Linux

BSD's find implementation on macOS is different from GNU find - this is compatible with both BSD and GNU find. Start with a globbing implementation, using -name and the -o for or - Put this function in your .bashrc file:

pyclean () {
    find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
}

Then cd to the directory you want to recursively clean, and type pyclean.

GNU find-only

This is a GNU find, only (i.e. Linux) solution, but I feel it's a little nicer with the regex:

pyclean () {
    find . -regex '^.*\(__pycache__\|\.py[co]\)$' -delete
}

Any platform, using Python 3

On Windows, you probably don't even have find. You do, however, probably have Python 3, which starting in 3.4 has the convenient pathlib module:

python3 -Bc "import pathlib; [p.unlink() for p in pathlib.Path('.').rglob('*.py[co]')]"
python3 -Bc "import pathlib; [p.rmdir() for p in pathlib.Path('.').rglob('__pycache__')]"

The -B flag tells Python not to write .pyc files. (See also the PYTHONDONTWRITEBYTECODE environment variable.)

The above abuses list comprehensions for looping, but when using python -c, style is rather a secondary concern. Alternatively we could abuse (for example) __import__:

python3 -Bc "for p in __import__('pathlib').Path('.').rglob('*.py[co]'): p.unlink()"
python3 -Bc "for p in __import__('pathlib').Path('.').rglob('__pycache__'): p.rmdir()"

Critique of an answer

The top answer used to say:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

This would seem to be less efficient because it uses three processes. find takes a regular expression, so we don't need a separate invocation of grep. Similarly, it has -delete, so we don't need a separate invocation of rm —and contrary to a comment here, it will delete non-empty directories so long as they get emptied by virtue of the regular expression match.

From the xargs man page:

find /tmp -depth -name core -type f -delete

Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process).

MySQL load NULL values from CSV data

MySQL manual says:

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

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

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

How do I make a LinearLayout scrollable?

You cannot make a LinearLayout scrollable because it is not a scrollable container.

Only scrollable containers such as ScrollView, HorizontalScrollView, ListView, GridView, ExpandableListView can be made scrollable.

I suggest you place your LinearLayout inside a ScrollView which will by default show vertical scrollbars if there is enough content to scroll.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView ...>

    <LinearLayout ...>

        ...
        ...

    </LinearLayout>

</ScrollView>

Note : ScrollView takes only one view as its child. So better that child view be a Linear Layout

Why do I have to "git push --set-upstream origin <branch>"?

A basically full command is like git push <remote> <local_ref>:<remote_ref>. If you run just git push, git does not know what to do exactly unless you have made some config that helps git to make a decision. In a git repo, we can setup multiple remotes. Also we can push a local ref to any remote ref. The full command is the most straightforward way to make a push. If you want to type fewer words, you have to config first, like --set-upstream.

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

I am not sure I understand what you want, but based on what I understood

the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")

worked for me, see the picture

enter image description here

I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

How do you share constants in NodeJS modules?

I recommend doing it with webpack (assumes you're using webpack).

Defining constants is as simple as setting the webpack config file:

var webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.DefinePlugin({
            'APP_ENV': '"dev"',
            'process.env': {
                'NODE_ENV': '"development"'
            }
        })
    ],    
};

This way you define them outside your source, and they will be available in all your files.

jquery loop on Json data using $.each

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
    alert(data[i].PageName);
});

$.each(data, function(i, item) {
    alert(item.PageName);
});

these two options work well, unless you have something like:

var data.result = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data.result, function(i, item) {
    alert(data.result[i].PageName);
});

EDIT:

try with this and describes what the result

$.get('/Cms/GetPages/123', function(data) {
  alert(data);
});

FOR EDIT 3:

this corrects the problem, but not the idea to use "eval", you should see how are the response in '/Cms/GetPages/123'.

$.get('/Cms/GetPages/123', function(data) {
  $.each(eval(data.replace(/[\r\n]/, "")), function(i, item) {
   alert(item.PageName);
  });
});

How do I ignore all files in a folder with a Git repository in Sourcetree?

After beating my head on this for at least an hour, I offer this answer to try to expand on the comments some others have made. To ignore a folder/directory, do the following: if you don't have a .gitignore file in the root of your project (that name exactly ".gitignore"), create a dummy text file in the folder you want to exclude. Inside of Source Tree, right click on it and select Ignore. You'll get a popup that looks like this.

enter image description here

Select "Everything underneath" and select the folder you want to ignore from the drop-down list. This will create a .gitignore file in your root directory and put the folder specification in it.

If you do have a .gitignore folder already in your root folder, you could follow the same approach above, or you can just edit the .gitignore file and add the folder you want to exclude. It's just a text file. Note that it uses forward slashes in path names rather than backslashes, as we Windows users are accustomed to. I tried creating a .gitignore text file by hand in Windows Explorer, but it didn't let me create a file without a name (i.e. with only the extension).

Note that adding the .gitignore and the file specification will have no effect on files that are already being tracked. If you're already tracking these, you'll have to stop tracking them. (Right-click on the folder or file and select Stop Tracking.) You'll then see them change from having a green/clean or amber/changed icon to a red/removed icon. On your next commit the files will be removed from the repository and thereafter appear with a blue/ignored icon. Another contributor asked why Ignore was disabled for particular files and I believe it was because he was trying to ignore a file that was already being tracked. You can only ignore a file that has a blue question mark icon.

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method

You would use object spread:

let merged = {...obj1, ...obj2};

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

/** There's no limit to the number of objects you can merge.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

Here is also the MDN documentation for this syntax. If you're using babel you'll need the babel-plugin-transform-object-rest-spread plugin for it to work.

ECMAScript 2015 (ES6) Standard Method

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(see MDN JavaScript Reference)


Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

Example function:

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

How to set the font size in Emacs?

Press Shift and the first mouse button. You can change the font size in the following way: This website has more detail.

How to convert any Object to String?

I am try to convert Object type variable into string using this line of code

try this to convert object value to string:

Java Code

 Object dataobject=value;
    //convert object into String  
     String convert= String.valueOf(dataobject);

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

How to remove the arrow from a select element in Firefox

The appearance property from CSS3 does not allow none value. Take a look at the W3C reference. So, what you is trying to do isn't valid (indeed Chrome shouldn't accept too).

Then unfortunatelly we really don't have any cross-browser solution to hide that arrow using pure CSS. As pointed, you will need JavaScript.

I suggest you to consider using selectBox jQuery plugin. It's very lightweight and nicely done.

RegEx match open tags except XHTML self-contained tags

<?php
$selfClosing = explode(',', 'area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed');

$html = '
<p><a href="#">foo</a></p>
<hr/>
<br/>
<div>name</div>';

$dom = new DOMDocument();
$dom->loadHTML($html);
$els = $dom->getElementsByTagName('*');
foreach ( $els as $el ) {
    $nodeName = strtolower($el->nodeName);
    if ( !in_array( $nodeName, $selfClosing ) ) {
        var_dump( $nodeName );
    }
}

Output:

string(4) "html"
string(4) "body"
string(1) "p"
string(1) "a"
string(3) "div"

Basically just define the element node names that are self closing, load the whole html string into a DOM library, grab all elements, loop through and filter out ones which aren't self closing and operate on them.

I'm sure you already know by now that you shouldn't use regex for this purpose.

How can I style even and odd elements?

but it's not working in IE. recommend using :nth-child(2n+1) :nth-child(2n+2)

_x000D_
_x000D_
li {_x000D_
    color: black;_x000D_
}_x000D_
li:nth-child(odd) {_x000D_
    color: #777;_x000D_
}_x000D_
li:nth-child(even) {_x000D_
    color: blue;_x000D_
}
_x000D_
<ul>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

iOS 7 - Status bar overlaps the view

This is all that is needed to remove the status bar. enter image description here

How to grep and replace

This works best for me on OS X:

grep -r -l 'searchtext' . | sort | uniq | xargs perl -e "s/matchtext/replacetext/" -pi

Source: http://www.praj.com.au/post/23691181208/grep-replace-text-string-in-files

How can I remove the string "\n" from within a Ruby string?

If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip method.

"    hello    ".strip   #=> "hello"   
"\tgoodbye\r\n".strip   #=> "goodbye"

as mentioned here.

edit The original title for this question was different. My answer is for the original question.

Complex CSS selector for parent of active child

I had the same problem with Drupal. Given the limitations of CSS, the way to get this working is to add the "active" class to the parent elements when the menu HTML is generated. There's a good discussion of this at http://drupal.org/node/219804, the upshot of which is that this functionality has been rolled in to version 6.x-2.x of the nicemenus module. As this is still in development, I've backported the patch to 6.x-1.3 at http://drupal.org/node/465738 so that I can continue to use the production-ready version of the module.

How to rename uploaded file before saving it into a directory?

The move_uploaded_file will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file

How to insert TIMESTAMP into my MySQL table?

$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIMESTAMP(), '$comments')";

You can use this Query. CURRENT_TIMESTAMP

Remember to use the parenthesis CURRENT_TIMESTAMP()