Programs & Examples On #Mv

mv is the Unix command to rename or move a file or directory.

Is there a way to make mv create the directory to be moved to if it doesn't exist?

The following shell script, perhaps?

#!/bin/sh
if [[ -e $1 ]]
then
  if [[ ! -d $2 ]]
  then
    mkdir --parents $2
  fi
fi
mv $1 $2

That's the basic part. You might want to add in a bit to check for arguments, and you may want the behavior to change if the destination exists, or the source directory exists, or doesn't exist (i.e. don't overwrite something that doesn't exist).

Is it possible to move/rename files in Git and maintain their history?

First create a standalone commit with just a rename.

Then any eventual changes to the file content put in the separate commit.

How to move or copy files listed by 'find' command in unix?

If you're using GNU find,

find . -mtime 1 -exec cp -t ~/test/ {} +

This works as well as piping the output into xargs while avoiding the pitfalls of doing so (it handles embedded spaces and newlines without having to use find ... -print0 | xargs -0 ...).

How to rename with prefix/suffix?

I know there is great answers here but I found no reference to handle filename extensions when adding suffix.

I needed to add '_en' suffix to all wav files in a folder before the file extension.

The magic is here: %.*

for filename in *.wav; do mv $filename ${filename%.*}_en.wav; done;

If you need to handle different file extensions, check this answer. A bit less intuitive.

Get the last non-empty cell in a column in Google Sheets

for a row:

=ARRAYFORMULA(INDIRECT("A"&MAX(IF(A:A<>"", ROW(A:A), ))))

for a column:

=ARRAYFORMULA(INDIRECT(ADDRESS(1, MAX(IF(1:1<>"", COLUMN(1:1), )), 4)))

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

I too got the similar problem and I did like below..
Rt click the project, navigate to Run As --> click 6 Maven Clean and your build will be success..

Maven Clean

Build Success

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

I experienced the same problem and following solution solved this problem. You should try the following solution.

sudo mkdir -p /data/db
sudo chown -R 'username' /data/db

Update multiple columns in SQL

I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.

First, get the result of table2.

enter image description here

Next, unpivot it.

enter image description here

Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB

--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')

DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(    
    colName VARCHAR(255),
    val VARCHAR(255)
)

INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
    val
    FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id

SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot

SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + ''' 
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL

PRINT @TSQL result:

enter image description here

Remove trailing comma from comma-separated string

To remove the ", " part which is immediately followed by end of string, you can do:

str = str.replaceAll(", $", "");

This handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case.

Example code:

String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // prints "kushalhs, mayurvm, narendrabz"

NOTE: Since there has been some comments and suggested edits about the ", $" part: The expression should match the trailing part that you want to remove.

  • If your input looks like "a,b,c,", use ",$".
  • If your input looks like "a, b, c, ", use ", $".
  • If your input looks like "a , b , c , ", use " , $".

I think you get the point.

How do I remove objects from a JavaScript associative array?

Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.

To remove a property from an object in JavaScript you use the delete operator:

const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false

Note that when delete is applied to an index property of an Array, you will create a sparsely populated array (ie. an array with a missing index).

When working with instances of Array, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice or Array#pop.

Note that the delete operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o, then o will subsequently be garbage collected in the normal way.

Using the delete operator can affect JavaScript engines' ability to optimise code.

How to get the selected value from RadioButtonList?

string radioListValue = RadioButtonList.Text;

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

pip broke. how to fix DistributionNotFound error?

The root of the problem are often outdated scripts in the bin (Linux) or Scripts (Windows) subdirectory. I'll explain this using problem I encountered myself as an example.

I had virtualenv version 1.10 installed in my user site-packages (the fact it's in user site-packages not sytem site-packages is irrelevant here)

pdobrogost@host:~$ which virtualenv
/home/users/pdobrogost/.local/bin/virtualenv
pdobrogost@host:~$ virtualenv --version
1.10

After I upgraded it to version 1.11 I got the following error:

pdobrogost@host:~$ virtualenv --version  
Traceback (most recent call last):   
  File "/home/users/pdobrogost/.local/bin/virtualenv", line 5, in <module>
    from pkg_resources import load_entry_point   
File "build/bdist.linux-x86_64/egg/pkg_resources.py", line 2701, in <module>
    return self.__dep_map   
File "build/bdist.linux-x86_64/egg/pkg_resources.py", line 572, in resolve
    if insert: 
pkg_resources.DistributionNotFound: virtualenv==1.10

File /home/users/pdobrogost/.local/bin/virtualenv mentioned in the error message looked like this:

#!/opt/python/2.7.5/bin/python2.7
# EASY-INSTALL-ENTRY-SCRIPT: 'virtualenv==1.10','console_scripts','virtualenv'
__requires__ = 'virtualenv==1.10'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('virtualenv==1.10', 'console_scripts', 'virtualenv')()
    ) 

There, we see that virtualenv script was not updated and still requires previously installed version 1.10 of virtualenv.
Now, reinstalling virtualenv like this

pdobrogost@host:~$ pip install --user --upgrade virtualenv
Downloading/unpacking virtualenv from https://pypi.python.org/packages/py27/v/virtualenv/virtualenv-1.11.1-py27-none-any.whl#md5=265770b61de41d34d2e9fdfddcdf034c
  Using download cache from /home/users/pdobrogost/.pip_download_cache/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fpy27%2Fv%2Fvirtualenv%2Fvirtualenv-1.11.1-py27-none-any.whl
Installing collected packages: virtualenv
Successfully installed virtualenv
Cleaning up...

does not help (neither pip install --user --upgrade --force-reinstall virtualenv) because script /home/users/pdobrogost/.local/bin/virtualenv is left unchanged.

The only way I could fix this was by manually removing virtualenv* scripts from /home/users/pdobrogost/.local/bin/ folder and installing virtualenv again. After this, newly generated scripts refer to the proper version of the package:

pdobrogost@host:~$ virtualenv --version
1.11

Create a txt file using batch file in a specific folder

This code written above worked for me as well. Although, you can use the code I am writing here:

@echo off

@echo>"d:\testing\dblank.txt

If you want to write some text to dblank.txt then add the following line in the end of your code

@echo Writing text to dblank.txt> dblank.txt

How to correctly dismiss a DialogFragment?

Kotlin Version of Terel answer

(fragmentManager.findFragmentByTag(TAG) as? DialogFragment)?.dismiss()

"The page you are requesting cannot be served because of the extension configuration." error message

Use aspnet_regiis.exe to register version of .NET framework you are using.

This is a common issue and happens when IIS is installed after VS or .NET framework.

Note - for Windows 8/10 users, see the other answer by JohnOpincar below. And also the comment/tip from Kevin Brydon.

Save PL/pgSQL output from PostgreSQL to a CSV file

psql can do this for you:

edd@ron:~$ psql -d beancounter -t -A -F"," \
                -c "select date, symbol, day_close " \
                   "from stockprices where symbol like 'I%' " \
                   "and date >= '2009-10-02'"
2009-10-02,IBM,119.02
2009-10-02,IEF,92.77
2009-10-02,IEV,37.05
2009-10-02,IJH,66.18
2009-10-02,IJR,50.33
2009-10-02,ILF,42.24
2009-10-02,INTC,18.97
2009-10-02,IP,21.39
edd@ron:~$

See man psql for help on the options used here.

Month name as a string

Getting a standalone month name is surprisingly difficult to perform "right" in Java. (At least as of this writing. I'm currently using Java 8).

The problem is that in some languages, including Russian and Czech, the standalone version of the month name is different from the "formatting" version. Also, it appears that no single Java API will just give you the "best" string. The majority of answers posted here so far only offer the formatting version. Pasted below is a working solution for getting the standalone version of a single month name, or getting an array with all of them.

I hope this saves someone else some time!

/**
 * getStandaloneMonthName, This returns a standalone month name for the specified month, in the
 * specified locale. In some languages, including Russian and Czech, the standalone version of
 * the month name is different from the version of the month name you would use as part of a
 * full date. (Different from the formatting version).
 *
 * This tries to get the standalone version first. If no mapping is found for a standalone
 * version (Presumably because the supplied language has no standalone version), then this will
 * return the formatting version of the month name.
 */
private static String getStandaloneMonthName(Month month, Locale locale, boolean capitalize) {
    // Attempt to get the standalone version of the month name.
    String monthName = month.getDisplayName(TextStyle.FULL_STANDALONE, locale);
    String monthNumber = "" + month.getValue();
    // If no mapping was found, then get the formatting version of the month name.
    if (monthName.equals(monthNumber)) {
        DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
        monthName = dateSymbols.getMonths()[month.getValue()];
    }
    // If needed, capitalize the month name.
    if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
        monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
    }
    return monthName;
}

/**
 * getStandaloneMonthNames, This returns an array with the standalone version of the full month
 * names.
 */
private static String[] getStandaloneMonthNames(Locale locale, boolean capitalize) {
    Month[] monthEnums = Month.values();
    ArrayList<String> monthNamesArrayList = new ArrayList<>();
    for (Month monthEnum : monthEnums) {
        monthNamesArrayList.add(getStandaloneMonthName(monthEnum, locale, capitalize));
    }
    // Convert the arraylist to a string array, and return the array.
    String[] monthNames = monthNamesArrayList.toArray(new String[]{});
    return monthNames;
}

What is the difference between dim and set in vba

There's no reason to use set unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea to dim (dimension) ALL variables however:

Examples of simple data types would be integer, long, boolean, string. These are just data types and do not have their own methods and properties.

Dim i as Integer
i = 5

Dim myWord as String
myWord = "Whatever I want"

An example of an object would be a Range, a Worksheet, or a Workbook. These have their own methods and properties.

Dim myRange as Range
Set myRange = Sheet1.Range("A1")

If you try to use the last line without Set, VB will throw an error. Now that you have an object declared you can access its properties and methods.

myString = myRange.Value

Make Frequency Histogram for Factor Variables

Data as factor can be used as input to the plot function.

An answer to a similar question has been given here: https://stat.ethz.ch/pipermail/r-help/2010-December/261873.html

 x=sample(c("Richard", "Minnie", "Albert", "Helen", "Joe", "Kingston"),  
 50, replace=T)
 x=as.factor(x)
 plot(x)

getch and arrow codes

    void input_from_key_board(int &ri, int &ci)
{
    char ch = 'x';
    if (_kbhit())
    {
        ch = _getch();
        if (ch == -32)
        {
            ch = _getch();
            switch (ch)
            {
            case 72: { ri--; break; }
            case 80: { ri++; break; }
            case 77: { ci++; break; }
            case 75: { ci--; break; }

            }
        }
        else if (ch == '\r'){ gotoRowCol(ri++, ci -= ci); }
        else if (ch == '\t'){ gotoRowCol(ri, ci += 5); }
        else if (ch == 27) { system("ipconfig"); }
        else if (ch == 8){ cout << " "; gotoRowCol(ri, --ci); if (ci <= 0)gotoRowCol(ri--, ci); }
        else { cout << ch; gotoRowCol(ri, ci++); }
        gotoRowCol(ri, ci);
    }
}

What's the easiest way to install a missing Perl module?

Otto made a good suggestion. This works for Debian too, as well as any other Debian derivative. The missing piece is what to do when apt-cache search doesn't find something.

$ sudo apt-get install dh-make-perl build-essential apt-file
$ sudo apt-file update

Then whenever you have a random module you wish to install:

$ cd ~/some/path
$ dh-make-perl --build --cpan Some::Random::Module
$ sudo dpkg -i libsome-random-module-perl-0.01-1_i386.deb

This will give you a deb package that you can install to get Some::Random::Module. One of the big benefits here is man pages and sample scripts in addition to the module itself will be placed in your distro's location of choice. If the distro ever comes out with an official package for a newer version of Some::Random::Module, it will automatically be installed when you apt-get upgrade.

diff to output only the file names

You can also use rsync

rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out

How to remove empty cells in UITableView?

Swift 3 syntax:

tableView.tableFooterView = UIView(frame: .zero)

Swift syntax: < 2.0

tableView.tableFooterView = UIView(frame: CGRect.zeroRect)

Swift 2.0 syntax:

tableView.tableFooterView = UIView(frame: CGRect.zero)

Change image in HTML page every few seconds

Best way to swap images with javascript with left vertical clickable thumbnails

SCRIPT FILE: function swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

How do I get the picture size with PIL?

Note that PIL will not apply the EXIF rotation information (at least up to v7.1.1; used in many jpgs). A quick fix to accomodate this:

def get_image_dims(file_path):
    from PIL import Image as pilim
    im = pilim.open(file_path)
    # returns (w,h) after rotation-correction
    return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]

Is there a difference between /\s/g and /\s+/g?

\s means "one space", and \s+ means "one or more spaces".

But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.

How to get milliseconds from LocalDateTime in Java 8

Date and time as String to Long (millis):

String dateTimeString = "2020-12-12T14:34:18.000Z";

DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);

LocalDateTime localDateTime = LocalDateTime
        .parse(dateTimeString, formatter);

Long dateTimeMillis = localDateTime
        .atZone(ZoneId.systemDefault())
        .toInstant()
        .toEpochMilli();

Python unittest passing arguments

If you want to use steffens21's approach with unittest.TestLoader, you can modify the original test loader (see unittest.py):

import unittest
from unittest import suite

class TestLoaderWithKwargs(unittest.TestLoader):
    """A test loader which allows to parse keyword arguments to the
       test case class."""
    def loadTestsFromTestCase(self, testCaseClass, **kwargs):
        """Return a suite of all tests cases contained in 
           testCaseClass."""
        if issubclass(testCaseClass, suite.TestSuite):
            raise TypeError("Test cases should not be derived from "\
                            "TestSuite. Maybe you meant to derive from"\ 
                            " TestCase?")
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']

        # Modification here: parse keyword arguments to testCaseClass.
        test_cases = []
        for test_case_name in testCaseNames:
            test_cases.append(testCaseClass(test_case_name, **kwargs))
        loaded_suite = self.suiteClass(test_cases)

        return loaded_suite 

# call your test
loader = TestLoaderWithKwargs()
suite = loader.loadTestsFromTestCase(MyTest, extraArg=extraArg)
unittest.TextTestRunner(verbosity=2).run(suite)

Reading *.wav files in Python

If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do NumPy block-by-block processing using efficient and transparent block management by means of generators. Other pythonic niceties are context manager for files, metadata as properties... and if you want the whole file interface, because you are developing a quick prototype and you don't care about efficency, the whole file interface is still there.

A simple example of processing would be:

import sys
from wavefile import WaveReader, WaveWriter

with WaveReader(sys.argv[1]) as r :
    with WaveWriter(
            'output.wav',
            channels=r.channels,
            samplerate=r.samplerate,
            ) as w :

        # Just to set the metadata
        w.metadata.title = r.metadata.title + " II"
        w.metadata.artist = r.metadata.artist

        # This is the prodessing loop
        for data in r.read_iter(size=512) :
            data[1] *= .8     # lower volume on the second channel
            w.write(data)

The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.

How to access the first property of a Javascript object?

I don't recommend you to use Object.keys since its not supported in old IE versions. But if you really need that, you could use the code above to guarantee the back compatibility:

if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
    hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
    dontEnums = [
      'toString',
      'toLocaleString',
      'valueOf',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'constructor'
    ],
    dontEnumsLength = dontEnums.length;

return function (obj) {
  if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

  var result = [];

  for (var prop in obj) {
    if (hasOwnProperty.call(obj, prop)) result.push(prop);
  }

  if (hasDontEnumBug) {
    for (var i=0; i < dontEnumsLength; i++) {
      if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
    }
  }
  return result;
}})()};

Feature Firefox (Gecko)4 (2.0) Chrome 5 Internet Explorer 9 Opera 12 Safari 5

More info: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys

But if you only need the first one, we could arrange a shorter solution like:

var data = {"key1":"123","key2":"456"};
var first = {};
for(key in data){
    if(data.hasOwnProperty(key)){
        first.key = key;
        first.content =  data[key];
        break;
    }
}
console.log(first); // {key:"key",content:"123"}

How to update values in a specific row in a Python Pandas DataFrame?

I needed to update and add suffix to few rows of the dataframe on conditional basis based on the another column's value of the same dataframe -

df with column Feature and Entity and need to update Entity based on specific feature type

df2= df1 df.loc[df.Feature == 'dnb', 'Entity'] = 'duns_' + df.loc[df.Feature == 'dnb','Entity']

java : non-static variable cannot be referenced from a static context Error

This is an interesting question, i just want to give another angle by adding a little more info.You can understand why an exception is thrown if you see how static methods operate. These methods can manipulate either static data, local data or data that is sent to it as a parameter.why? because static method can be accessed by any object, from anywhere. So, there can be security issues posed or there can be leaks of information if it can use instance variables.Hence the compiler has to throw such a case out of consideration.

Disable resizing of a Windows Forms form

There is far more efficient answer: just put the following instructions in the Form_Load:

Me.MinimumSize = New Size(Width, Height)
Me.MaximumSize = Me.MinimumSize

How to strip comma in Python string

You want to replace it, not strip it:

s = s.replace(',', '')

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Using Proxies:

var a = new Proxy({ i: 0 }, {
    get: (target, name) => name === Symbol.toPrimitive ? () => ++target.i : target[name],
});
console.log(a == 1 && a == 2 && a == 3);

Proxies basically pretend to be a target object (the first parameter), but intercept operations on the target object (in this case the "get property" operation) so that there is an opportunity to do something other than the default object behavior. In this case the "get property" action is called on a when == coerces its type in order to compare it to each number. This happens:

  1. We create a target object, { i: 0 }, where the i property is our counter
  2. We create a Proxy for the target object and assign it to a
  3. For each a == comparison, a's type is coerced to a primitive value
  4. This type coercion results in calling a[Symbol.toPrimitive]() internally
  5. The Proxy intercepts getting the a[Symbol.toPrimitive] function using the "get handler"
  6. The Proxy's "get handler" checks that the property being gotten is Symbol.toPrimitive, in which case it increments and then returns the counter from the target object: ++target.i. If a different property is being retrieved, we just fall back to returning the default property value, target[name]

So:

var a = ...; // a.valueOf == target.i == 0
a == 1 && // a == ++target.i == 1
a == 2 && // a == ++target.i == 2
a == 3    // a == ++target.i == 3

As with most of the other answers, this only works with a loose equality check (==), because strict equality checks (===) do not do type coercion that the Proxy can intercept.

<script> tag vs <script type = 'text/javascript'> tag

You only need <script></script> Tag that's it. <script type="text/javascript"></script> is not a valid HTML tag, so for best SEO practice use <script></script>

How to check if a python module exists without importing it

Python 2, without relying ImportError

Until the current answer is updated, here is the way for Python 2

import pkgutil
import importlib

if pkgutil.find_loader(mod) is not None:
    return importlib.import_module(mod)
return None

Why another answer?

A lot of answers make use of catching an ImportError. The problem with that is, that we cannot know what throws the ImportError.

If you import your existant module and there happens to be an ImportError in your module (e.g. typo on line 1), the result will be that your module does not exist. It will take you quite the amount of backtracking to figure out that your module exists and the ImportError is caught and makes things fail silently.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.

Model:

public class MyViewModel
{
    [PlaceHolder("Enter title here")]
    public string Title { get; set; }
}

Html helper extension:

   public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
    var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var metadata = modelMetadata;

    var viewData = new
    {
        HtmlAttributes = new
            {
                @class = htmlClass,
                placeholder = metadata.Watermark,
            }
    };
    return htmlHelper.EditorFor(expression, viewData);

}

A corresponding view:

@Html.BsEditorFor(x => x.Title)

How can I submit a POST form using the <a href="..."> tag?

There really seems no way for fooling the <a href= .. into a POST method. However, given that you have access to CSS of a page, this can be substituted by using a form instead.

Unfortunately, the obvious way of just styling the button in CSS as an anchor tag, is not cross-browser compatible, since different browsers treat <button value= ... differently.

Incorrect:

<form action='actbusy.php' method='post'>
  <button type='submit' name='parameter' value='One'>Two</button>
</form>

The above example will be showing 'Two' and transmit 'parameter:One' in FireFox, while it will show 'One' and transmit also 'parameter:One' in IE8.

The way around is to use hidden input field(s) for delivering data and the button just for submitting it.

<form action='actbusy.php' method='post'>
   <input class=hidden name='parameter' value='blaah'>
   <button type='submit' name='delete' value='Delete'>Delete</button>
</form>

Note, that this method has a side effect that besides 'parameter:blaah' it will also deliver 'delete:Delete' as surplus parameters in POST.

You want to keep for a button the value attribute and button label between tags both the same ('Delete' on this case), since (as stated above) some browsers will display one and some display another as a button label.

Determine Whether Integer Is Between Two Other Integers?

if number >= 10000 and number <= 30000:
    print ("you have to pay 5% taxes")

Function in JavaScript that can be called only once

Talking about static variables, this is a little bit like closure variant:

var once = function() {
    if(once.done) return;
    console.log('Doing this once!');
    once.done = true;
};

once(); once(); 

You could then reset a function if you wish:

once.done = false;

SELECT INTO a table variable in T-SQL

OK, Now with enough effort i am able to insert into @table using the below :

INSERT @TempWithheldTable SELECT
a.SuspendedReason, a.SuspendedNotes, a.SuspendedBy , a.ReasonCode FROM OPENROWSET( BULK 'C:\DataBases\WithHeld.csv', FORMATFILE = N'C:\DataBases\Format.txt',
ERRORFILE=N'C:\Temp\MovieLensRatings.txt' ) AS a;

The main thing here is selecting columns to insert .

How to access the contents of a vector from a pointer to the vector in C++?

You can access the iterator methods directly:

std::vector<int> *intVec;
std::vector<int>::iterator it;

for( it = intVec->begin(); it != intVec->end(); ++it )
{
}

If you want the array-access operator, you'd have to de-reference the pointer. For example:

std::vector<int> *intVec;

int val = (*intVec)[0];

How do I count unique visitors to my site?

Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.

In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.

Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!


Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).

How do I build an import library (.lib) AND a DLL in Visual C++?

OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.

#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif

Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:

BARNABY_API int add(){
}

This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.

Saving image to file

You could try to save the image using this approach

SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
   int width = Convert.ToInt32(drawImage.Width); 
   int height = Convert.ToInt32(drawImage.Height); 
   Bitmap bmp = new Bitmap(width,height);        
   drawImage.DrawToBitmap(bmp, new Rectangle(0, 0, width, height);
   bmp.Save(dialog.FileName, ImageFormat.Jpeg);
}

How to avoid the "divide by zero" error in SQL?

You can also do this at the beginning of the query:

SET ARITHABORT OFF 
SET ANSI_WARNINGS OFF

So if you have something like 100/0 it will return NULL. I've only done this for simple queries, so I don't know how it will affect longer/complex ones.

adb shell command to make Android package uninstall dialog appear

In my case, I do an adb shell pm list packages to see first what are the packages/apps installed in my Android device or emulator, then upon locating the desired package/app, I do an adb shell pm uninstall -k com.package.name.

How do I position a div relative to the mouse pointer using jQuery?

<script type="text/javascript" language="JavaScript">

  var cX = 0;
  var cY = 0;
  var rX = 0;
  var rY = 0;

  function UpdateCursorPosition(e) {
    cX = e.pageX;
    cY = e.pageY;
  }

  function UpdateCursorPositionDocAll(e) {
    cX = event.clientX;
    cY = event.clientY;
  }
  if (document.all) {
    document.onmousemove = UpdateCursorPositionDocAll;
  } else {
    document.onmousemove = UpdateCursorPosition;
  }

  function AssignPosition(d) {
    if (self.pageYOffset) {
      rX = self.pageXOffset;
      rY = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      rX = document.documentElement.scrollLeft;
      rY = document.documentElement.scrollTop;
    } else if (document.body) {
      rX = document.body.scrollLeft;
      rY = document.body.scrollTop;
    }
    if (document.all) {
      cX += rX;
      cY += rY;
    }
    d.style.left = (cX + 10) + "px";
    d.style.top = (cY + 10) + "px";
  }

  function HideContent(d) {
    if (d.length < 1) {
      return;
    }
    document.getElementById(d).style.display = "none";
  }

  function ShowContent(d) {
    if (d.length < 1) {
      return;
    }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    dd.style.display = "block";
  }

  function ReverseContentDisplay(d) {
    if (d.length < 1) {
      return;
    }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    if (dd.style.display == "none") {
      dd.style.display = "block";
    } else {
      dd.style.display = "none";
    }
  }
  //-->
</script>


<a onmouseover="ShowContent('uniquename3'); return true;" onmouseout="HideContent('uniquename3'); return true;" href="javascript:ShowContent('uniquename3')">
[show on mouseover, hide on mouseout]
</a>
<div id="uniquename3" style="display:none;
position:absolute;
border-style: solid;
background-color: white;
padding: 5px;">
  Content goes here.
</div>

Google Play Services Library update and missing symbol @integer/google_play_services_version

Fixed by adding Google Play Services to my Module:app gradle build file. Documentation also says to update version when you update GMS.

dependencies {

compile 'com.google.android.gms:play-services:9.6.1'

} 

How to merge lists into a list of tuples?

Youre looking for the builtin function zip.

Why does the order in which libraries are linked sometimes cause errors in GCC?

Link order certainly does matter, at least on some platforms. I have seen crashes for applications linked with libraries in wrong order (where wrong means A linked before B but B depends on A).

Adding an onclicklistener to listview (android)

Try this:

    list.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3)
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

What's the difference between a single precision and double precision floating point operation?

All have explained in great detail and nothing I could add further. Though I would like to explain it in Layman's Terms or plain ENGLISH

1.9 is less precise than 1.99
1.99 is less precise than 1.999
1.999 is less precise than 1.9999

.....

A variable, able to store or represent "1.9" provides less precision than the one able to hold or represent 1.9999. These Fraction can amount to a huge difference in large calculations.

OnClick in Excel VBA

This has worked for me.....

Private Sub Worksheet_Change(ByVal Target As Range)

    If Mid(Target.Address, 3, 1) = "$" And Mid(Target.Address, 2, 1) < "E" Then
       ' The logic in the if condition will filter for a specific cell or block of cells
       Application.ScreenUpdating = False
       'MsgBox "You just changed " & Target.Address

       'all conditions are true .... DO THE FUNCTION NEEDED 
       Application.ScreenUpdating = True
    End If
    ' if clicked cell is not in the range then do nothing (if condttion is not run)  
End Sub

NOTE: this function in actual use recalculated a pivot table if a user added a item in a data range of A4 to D500. The there were protected and unprotected sections in the sheet so the actual check for the click is if the column is less that "E" The logic can get as complex as you want to include or exclude any number of areas

block1  = row > 3 and row < 5 and column column >"b" and < "d" 
block2  = row > 7 and row < 12 and column column >"b" and < "d" 
block3  = row > 10 and row < 15 and column column >"e" and < "g"

If block1 or block2 or block 3 then
  do function .....
end if  

Get user's current location

You may want to take a look at GeoIP Country Whois Locator found at PHPClasses.

How to convert a color integer to a hex String in Android?

With this method Integer.toHexString, you can have an Unknown color exception for some colors when using Color.parseColor.

And with this method String.format("#%06X", (0xFFFFFF & intColor)), you'll lose alpha value.

So I recommend this method:

public static String ColorToHex(int color) {
        int alpha = android.graphics.Color.alpha(color);
        int blue = android.graphics.Color.blue(color);
        int green = android.graphics.Color.green(color);
        int red = android.graphics.Color.red(color);

        String alphaHex = To00Hex(alpha);
        String blueHex = To00Hex(blue);
        String greenHex = To00Hex(green);
        String redHex = To00Hex(red);

        // hexBinary value: aabbggrr
        StringBuilder str = new StringBuilder("#");
        str.append(alphaHex);
        str.append(blueHex);
        str.append(greenHex);
        str.append(redHex );

        return str.toString();
    }

    private static String To00Hex(int value) {
        String hex = "00".concat(Integer.toHexString(value));
        return hex.substring(hex.length()-2, hex.length());
    }

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object

Is it possible to get the index you're sorting over in Underscore.js?

Index is actually available like;

_.sortBy([1, 4, 2, 66, 444, 9], function(num, index){  });

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

How to play ringtone/alarm sound in Android

This works fine:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
MediaPlayer thePlayer = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

try {
    thePlayer.setVolume((float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)),
                        (float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)));
} catch (Exception e) {
    e.printStackTrace();
}

thePlayer.start();

CSS3 Spin Animation

HTML with font-awesome glyphicon.

<span class="fa fa-spinner spin"></span>

CSS

@-moz-keyframes spin {
    to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
    to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
    to {transform:rotate(360deg);}
}

.spin {
    animation: spin 1000ms linear infinite;
}

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

In etc/my.cnf try changing the max_allowed _packet and net_buffer_length to

max_allowed_packet=100000000
net_buffer_length=1000000 

if this is not working then try changing to

max_allowed_packet=100M
net_buffer_length=100K 

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Maven Run Project

No need to add new plugin in pom.xml. Just run this command

mvn org.codehaus.mojo:exec-maven-plugin:1.5.0:java -Dexec.mainClass="com.example.Main" | grep -Ev '(^\[|Download\w+:)' 

See the maven exec plugin for more usage.

Install Visual Studio 2013 on Windows 7

The minimum requirements are based on the Express edition you're attempting to install:

Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8

It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.

The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"

Source

Intersection and union of ArrayLists in Java

Here is a way how you can do an intersection with streams (remember that you have to use java 8 for streams):

List<foo> fooList1 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
List<foo> fooList2 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
fooList1.stream().filter(f -> fooList2.contains(f)).collect(Collectors.toList());

An example for lists with different types. If you have a realtion between foo and bar and you can get a bar-object from foo than you can modify your stream:

List<foo> fooList = new ArrayList<>(Arrays.asList(new foo(), new foo()));
List<bar> barList = new ArrayList<>(Arrays.asList(new bar(), new bar()));

fooList.stream().filter(f -> barList.contains(f.getBar()).collect(Collectors.toList());

Sort a List of objects by multiple fields

If you know in advance which fields to use to make the comparison, then other people gave right answers.
What you may be interested in is to sort your collection in case you don't know at compile-time which criteria to apply. Imagine you have a program dealing with cities:



    protected Set<City> cities;
    (...)
    Field temperatureField = City.class.getDeclaredField("temperature");
    Field numberOfInhabitantsField = City.class.getDeclaredField("numberOfInhabitants");
    Field rainfallField = City.class.getDeclaredField("rainfall");
    program.showCitiesSortBy(temperatureField, numberOfInhabitantsField, rainfallField);
    (...)
    public void showCitiesSortBy(Field... fields) {
        List<City> sortedCities = new ArrayList<City>(cities);
        Collections.sort(sortedCities, new City.CityMultiComparator(fields));
        for (City city : sortedCities) {
            System.out.println(city.toString());
        }
    }

where you can replace hard-coded field names by field names deduced from a user request in your program.

In this example, City.CityMultiComparator<City> is a static nested class of class City implementing Comparator:



    public static class CityMultiComparator implements Comparator<City> {
        protected List<Field> fields;

        public CityMultiComparator(Field... orderedFields) {
            fields = new ArrayList<Field>();
            for (Field field : orderedFields) {
                fields.add(field);
            }
        }

        @Override
        public int compare(City cityA, City cityB) {
            Integer score = 0;
            Boolean continueComparison = true;
            Iterator itFields = fields.iterator();

            while (itFields.hasNext() && continueComparison) {
                Field field = itFields.next();
                Integer currentScore = 0;
                if (field.getName().equalsIgnoreCase("temperature")) {
                    currentScore = cityA.getTemperature().compareTo(cityB.getTemperature());
                } else if (field.getName().equalsIgnoreCase("numberOfInhabitants")) {
                    currentScore = cityA.getNumberOfInhabitants().compareTo(cityB.getNumberOfInhabitants());
                } else if (field.getName().equalsIgnoreCase("rainfall")) {
                    currentScore = cityA.getRainfall().compareTo(cityB.getRainfall());
                }
                if (currentScore != 0) {
                    continueComparison = false;
                }
                score = currentScore;
            }

            return score;
        }
    }


You may want to add an extra layer of precision, to specify, for each field, whether sorting should be ascendant or descendant. I guess a solution is to replace Field objects by objects of a class you could call SortedField, containing a Field object, plus another field meaning ascendant or descendant.

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

What's the best strategy for unit-testing database-driven applications?

I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.

I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).

How do I disable a jquery-ui draggable?

In the case of a dialog, it has a property called draggable, set it to false.

$("#yourDialog").dialog({
    draggable: false
});

Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

How do you change Background for a Button MouseOver in WPF?

For change button style

1st: define resource styles

<Window.Resources>

    <Style x:Key="OvergroundIn" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FF16832F">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FF06731F">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>

    <Style x:Key="OvergroundOut" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FFF35E5E">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FFE34E4E">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>


</Window.Resources>

2nd define button code

                           <Border Grid.Column="2" BorderBrush="LightGray" BorderThickness="2" CornerRadius="3" Margin="2,2,2,2"  >
                                <Button Name="btnFichar" BorderThickness="0" Click="BtnFichar_Click">
                                    <Button.Content>
                                        <Grid>
                                            <TextBlock Margin="0,7,0,7" TextAlignment="Center">Fichar</TextBlock> 
                                        </Grid>
                                    </Button.Content>
                                </Button>
                            </Border>

3th code behind

    public void ShowStatus()
    {
        switch (((MainDto)this.DataContext).State)
        {
            case State.IN:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(243, 94, 94));
                this.btnFichar.Style = Resources["OvergroundIn"] as Style;
                this.btnFichar.Content = "Fichar Salida";
                break;

            case State.OUT:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(76, 106, 83));
                this.btnFichar.Style = Resources["OvergroundOut"] as Style;
                this.btnFichar.Content = "Fichar Entrada";
                break;

        }
    }

no debugging symbols found when using gdb

You should also try -ggdb instead of -g if you're compiling for Android!

PLS-00201 - identifier must be declared

When creating the TABLE under B2BOWNER, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert.

I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.

What is a superfast way to read large files line-by-line in VBA?

Be careful when using Application.Transpose with a huge number of values. If you transpose values to a column, excel will assume you are assuming you transposed them from rows.


Max Column Limit < Max Row Limit, and it will only display the first (Max Column Limit) values, and anithing after that will be "N/A"

Better naming in Tuple classes than "Item1", "Item2"

MichaelMocko Answered is great,

but I want to add a few things which I had to figure out

(string first, string middle, string last) LookupName(long id)

above Line will give you compile-time error if you are using .net framework < 4.7

So if you have a project that is using .net framework < 4.7 and still you want to use ValueTuple than workAround would be installing this NuGet package

Update:

Example of returning Named tuple from a method and using it

public static (string extension, string fileName) GetFile()
{
    return ("png", "test");
}

Using it

var (extension, fileName) = GetFile();

Console.WriteLine(extension);
Console.WriteLine(fileName);

Execute Stored Procedure from a Function

Here is another possible workaround:

if exists (select * from master..sysservers where srvname = 'loopback')
    exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = @@servername
go

create function testit()
    returns int
as
begin
    declare @res int;
    select @res=count(*) from openquery(loopback, 'exec sp_who');
    return @res
end
go

select dbo.testit()

It's not so scary as xp_cmdshell but also has too many implications for practical use.

Plot inline or a separate window using Matplotlib in Spyder IDE

Magic commands such as

%matplotlib qt  

work in the iPython console and Notebook, but do not work within a script.

In that case, after importing:

from IPython import get_ipython

use:

get_ipython().run_line_magic('matplotlib', 'inline')

for inline plotting of the following code, and

get_ipython().run_line_magic('matplotlib', 'qt')

for plotting in an external window.

Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.

Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.

Update Git submodule to latest commit on origin

If you don't know the host branch, make this:

git submodule foreach git pull origin $(git rev-parse --abbrev-ref HEAD)

It will get a branch of the main Git repository and then for each submodule will make a pull of the same branch.

How to add multiple classes to a ReactJS Component?

When I have many varying classes, I have found the following to be useful.

The filter removes any of the null values and the join puts all the remaining values into a space separated string.

const buttonClasses = [
    "Button", 
    disabled ? "disabled" : null,
    active ? "active" : null
].filter((class) => class).join(" ")

<button className={buttonClasses} onClick={onClick} disabled={disabled ? disabled : false}>

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

I know you already accepted the other answer, but if you want to do this as a DataFrame, just use groupBy and agg. Assuming you had a DF already created (with columns named "col1", "col2", etc) you could do:

myDF.groupBy($"col1", $"col3", $"col4").agg($"col1", max($"col2"), $"col3", $"col4")

Note that in this case, I chose the Max of col2, but you could do avg, min, etc.

What's NSLocalizedString equivalent in Swift?

By using this way its possible to create a different implementation for different types (i.e. Int or custom classes like CurrencyUnit, ...). Its also possible to scan for this method invoke using the genstrings utility. Simply add the routine flag to the command

genstrings MyCoolApp/Views/SomeView.swift -s localize -o .

extension:

import UIKit

extension String {
    public static func localize(key: String, comment: String) -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

usage:

String.localize("foo.bar", comment: "Foo Bar Comment :)")

Stopword removal with NLTK

@alvas's answer does the job but it can be done way faster. Assuming that you have documents: a list of strings.

from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation 

for doc in documents:
    list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2 times faster, which is significant if you need to operate through many documents.

For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.

P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()

and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] inside of a loop.

Get first n characters of a string

This is what i do

    function cutat($num, $tt){
        if (mb_strlen($tt)>$num){
            $tt=mb_substr($tt,0,$num-2).'...';
        }
        return $tt;
    }

where $num stands for number of chars, and $tt the string for manipulation.

Concatenating Files And Insert New Line In Between Files

If it were me doing it I'd use sed:

sed -e '$s/$/\n/' -s *.txt > finalfile.txt

In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.

If your version of sed doesn't have -s (process input files separately) you can do it all as a loop though:

for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt

How to set a selected option of a dropdown list control using angular JS

It can be usefull. Bindings dose not always work.

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products">
</select>

For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
   $http.get('/product/list')
     .then(function (response) {
       $scope.products = response.data;

       if (productId) {
           console.log("" + $("#product option").length);//for clarity                       
           $timeout(function () {
               console.log("" + $("#product option").length);//for clarity
               $('#product').val('number:'+productId);
               //$scope.issue.productId = productId;//not work at all
           }, 200);
       }
   });
}

JavaScript, Node.js: is Array.forEach asynchronous?

If you need an asynchronous-friendly version of Array.forEach and similar, they're available in the Node.js 'async' module: http://github.com/caolan/async ...as a bonus this module also works in the browser.

async.each(openFiles, saveFile, function(err){
    // if any of the saves produced an error, err would equal that error
});

Difference between matches() and find() in Java Regex

matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.

Using routes in Express-js

You could also organise them into modules. So it would be something like.

./
controllers
    index.js
    indexController.js
app.js

and then in the indexController.js of the controllers export your controllers.

//indexController.js
module.exports = function(){
//do some set up

var self = {
     indexAction : function (req,res){
       //do your thing
}
return self;
};

then in index.js of controllers dir

exports.indexController = require("./indexController");

and finally in app.js

var controllers = require("./controllers");

app.get("/",controllers.indexController().indexAction);

I think this approach allows for clearer seperation and also you can configure your controllers by passing perhaps a db connection in.

Why is this jQuery click function not working?

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

i.e.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

CSS center display inline block?

You don't need to use "display: table". The reason your margin: 0 auto centering attempt doesn't work is because you didn't specify a width.

This will work just fine:

.wrap {
    background: #aaa;
    margin: 0 auto;
    width: some width in pixels since it's the container;
}

You don't need to specify display: block since that div will be block by default. You can also probably lose the overflow: hidden.

Convert float to double without losing precision

Floats, by nature, are imprecise and always have neat rounding "issues". If precision is important then you might consider refactoring your application to use Decimal or BigDecimal.

Yes, floats are computationally faster than decimals because of the on processor support. However, do you want fast or accurate?

How to find char in string and get all the indexes?

Lev's answer is the one I'd use, however here's something based on your original code:

def find(str, ch):
    for i, ltr in enumerate(str):
        if ltr == ch:
            yield i

>>> list(find("ooottat", "o"))
[0, 1, 2]

How to know installed Oracle Client is 32 bit or 64 bit?

For Unix

grep "ARCHITECTURE" $ORACLE_HOME/inventory/ContentsXML/oraclehomeproperties.xml

And the output is:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/> 

For Windows

findstr "ARCHITECTURE" %ORACLE_HOME%\inventory\ContentsXML\oraclehomeproperties.xml

And the output can be:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/>

Find out who is locking a file on a network share

PsFile does work on remote machines. If my login account already has access to the remote share, I can just enter:

psfile \\remote-share

(replace "remote-share" with the name of your file server) and it will list every opened document on that share, along with who has it open, and the file ID if I want to force the file closed. For me, this is a really long list, but it can be narrowed down by entering part of a path:

psfile \\remote-share I:\\Human_Resources

This is kind of tricky, since in my case this remote share is mounted as Z: on my local machine, but psfile identifies paths as they are defined on the remote file server, which in my case is I: (yours will be different). I just had to comb through the results of my first psfile run to see some of the paths it returned and then run it again with a partial path to narrow down the results.

Optionally, PsFile will let you specify credentials for the remote share if you need to supply them for access.

Lastly, a little known tip: if someone clicks on a file in Windows Explorer and cuts or copies the file with the intent to paste it somewhere else, that act also places a lock on the file.

sorting a vector of structs

Use a comparison function:

bool compareByLength(const data &a, const data &b)
{
    return a.word.size() < b.word.size();
}

and then use std::sort in the header #include <algorithm>:

std::sort(info.begin(), info.end(), compareByLength);

Send FormData and String Data Together Through JQuery AJAX?

For multiple files in ajax try this

        var url = "your_url";
        var data = $('#form').serialize();
        var form_data = new FormData(); 
        //get the length of file inputs   
        var length = $('input[type="file"]').length; 

        for(var i = 0;i<length;i++){
           file_data = $('input[type="file"]')[i].files;

            form_data.append("file_"+i, file_data[0]);
        }

            // for other data
            form_data.append("data",data);


        $.ajax({
                url: url,
                type: "POST",
                data: form_data,
                cache: false,
                contentType: false, //important
                processData: false, //important
                success: function (data) {
                  //do something
                }
        })

In php

        parse_str($_POST['data'], $_POST); 
        for($i=0;$i<count($_FILES);$i++){
              if(isset($_FILES['file_'.$i])){
                   $file = $_FILES['file_'.$i];
                   $file_name = $file['name'];
                   $file_type = $file ['type'];
                   $file_size = $file ['size'];
                   $file_path = $file ['tmp_name'];
              }
        }

Functions that return a function

Create a variable:

var thing1 = undefined;

Declare a Function:

function something1 () {
    return "Hi there, I'm number 1!";
}

Alert the value of thing1 (our first variable):

alert(thing1); // Outputs: "undefined".

Now, if we wanted thing1 to be a reference to the function something1, meaning it would be the same thing as our created function, we would do:

thing1 = something1;

However, if we wanted the return value of the function then we must assign it the return value of the executed function. You execute the function by using parenthesis:

thing1 = something1(); // Value of thing1: "Hi there, I'm number 1!" 

Change the value in app.config file dynamically

This code works for me:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    config.AppSettings.Settings["test"].Value = "blah";       
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");

Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.

How to convert date to string and to date again?

For converting date to string check this thread

Convert java.util.Date to String

And for converting string to date try this,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StringToDate
{
    public static void main(String[] args) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        String strDate = "14/03/2003 08:05:10";     
        System.out.println("Date - " + sdf.parse(strDate));
    }
}

How to set locale in DatePipe in Angular 2?

If you use TranslateService from @ngx-translate/core, below is a version without creating a new pipe which works with switching dynamically on runtime (tested on Angular 7). Using DatePipe's locale parameter (docs):

First, declare the locales you use in your app, e.g. in app.component.ts:

import localeIt from '@angular/common/locales/it';
import localeEnGb from '@angular/common/locales/en-GB';
.
.
.
ngOnInit() {
    registerLocaleData(localeIt, 'it-IT');
    registerLocaleData(localeEnGb, 'en-GB');
}

Then, use your pipe dynamically:

myComponent.component.html

<span>{{ dueDate | date: 'shortDate' : '' : translateService.currentLang }}</span>

myComponent.component.ts

 constructor(public translateService: TranslateService) { ... }

extra qualification error in C++

Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::.

How to split a string of space separated numbers into integers?

Other answers already show that you can use split() to get the values into a list. If you were asking about Python's arrays, here is one solution:

import array
s = '42 0'
a = array.array('i')
for n in s.split():
    a.append(int(n))

Edit: A more concise solution:

import array
s = '42 0'
a = array.array('i', (int(t) for t in s.split()))

ALTER TABLE DROP COLUMN failed because one or more objects access this column

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name> drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

What is a "callback" in C and how are they implemented?

There is no "callback" in C - not more than any other generic programming concept.

They're implemented using function pointers. Here's an example:

void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
    for (size_t i=0; i<arraySize; i++)
        array[i] = getNextValue();
}

int getNextRandomValue(void)
{
    return rand();
}

int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
    ...
}

Here, the populate_array function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback getNextRandomValue, which returns a random-ish value, and passed a pointer to it to populate_array. populate_array will call our callback function 10 times and assign the returned values to the elements in the given array.

How to perform a for-each loop over all the files under a specified path?

The for-loop will iterate over each (space separated) entry on the provided string.

You do not actually execute the find command, but provide it is as string (which gets iterated by the for-loop). Instead of the double quotes use either backticks or $():

for line in $(find . -iname '*.txt'); do 
     echo "$line"
     ls -l "$line"
done

Furthermore, if your file paths/names contains spaces this method fails (since the for-loop iterates over space separated entries). Instead it is better to use the method described in dogbanes answer.


To clarify your error:

As said, for line in "find . -iname '*.txt'"; iterates over all space separated entries, which are:

  • find
  • .
  • -iname
  • '*.txt' (I think...)

The first two do not result in an error (besides the undesired behavior), but the third is problematic as it executes:

ls -l -iname

A lot of (bash) commands can combine single character options, so -iname is the same as -i -n -a -m -e. And voila: your invalid option -- 'e' error!

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783

Automatically resize images with browser size using CSS

This may be too simplistic of an answer (I am still new here), but what I have done in the past to remedy this situation is figured out the percentage of the screen I would like the image to take up. For example, there is one webpage I am working on where the logo must take up 30% of the screen size to look best. I played around and finally tried this code and it has worked for me thus far:

img {
width:30%;
height:auto;
}

That being said, this will change all of your images to be 30% of the screen size at all times. To get around this issue, simply make this a class and apply it to the image that you desire to be at 30% directly. Here is an example of the code I wrote to accomplish this on the aforementioned site:

the CSS portion:

.logo {
position:absolute;
right:25%;
top:0px;
width:30%;
height:auto;
}

the HTML portion:

<img src="logo_001_002.png" class="logo">

Alternatively, you could place ever image you hope to automatically resize into a div of its own and use the class tag option on each div (creating now class tags whenever needed), but I feel like that would cause a lot of extra work eventually. But, if the site calls for it: the site calls for it.

Hopefully this helps. Have a great day!

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

How to unmount a busy device

Niche Answer:

If you have a zfs pool on that device, at least when it's a file-based pool, lsof will not show the usage. But you can simply run

sudo zpool export mypoo

and then unmount.

div inside php echo

You can also do this,

<?php 
if ( ($cart->count_product) > 0) { 
  $print .= "<div class='my_class'>"
  $print .= $cart->count_product; 
  $print .= "</div>"
} else { 
   $print = ''; 
} 
echo  $print;
?>

Changing the color of an hr element

I like the answers setting border-top, but they are somehow still a little off in Chrome...
BUT if I set border-top: 1px solid black; and border-bottom: 0px; I end up with a truly single line (that also works fine with higher thickness).

Choose File Dialog

Adding to the mix: the OI File Manager has a public api registered at openintents.org

http://www.openintents.org/filemanager

http://www.openintents.org/action/org-openintents-action-pick-file/

How to vertically align text inside a flexbox?

It's depend on your li height just call one more thing line height

_x000D_
_x000D_
* {
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100%;
}

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  align-self: center;
  background: silver;
  width: 100%;
  height:50px;line-height:50px;
}
_x000D_
<ul>
  <li>This is the text</li>
</ul>
_x000D_
_x000D_
_x000D_

Android Studio Run/Debug configuration error: Module not specified

in my case, when I added Fragment I git this error.

When I opened THe app build.gradle I saw id("kotlin-android") this plugin in plugins.

just remove it!

What Java FTP client library should I use?

Yes, EnterpriseDT's edtFTPj is stable (first released in 2000), has all the features you might need, and is open source as well.

It's used in a bunch of open source projects (as well as in many commercial projects), and is acknowledged to be one of the fastest client libraries around.

As another poster noted, if you do wish to upgrade to SFTP and/or FTPS, it is a simple upgrade path with very few code changes required.

No provider for HttpClient

I was facing the same problem, then in my app.module.ts I updated the file this way,

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

and in the same file (app.module.ts) in my @NgModule imports[]array I wrote this way,

HttpModule,
HttpClientModule

Uploading files to file server using webclient class

namespace FileUpload
{
public partial class Form1 : Form
{
    string fileName = "";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        string path = "";
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Attach customer proposal document";
        fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
        fDialog.InitialDirectory = @"C:\";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = System.IO.Path.GetFileName(fDialog.FileName);
            path = Path.GetDirectoryName(fDialog.FileName);
            textBox1.Text = path + "\\" + fileName;

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            WebClient client = new WebClient();

            NetworkCredential nc = new NetworkCredential("erandika1986", "123");

            Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);

            client.Credentials = nc;
            byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
            MessageBox.Show(arrReturn.ToString());

        }
        catch (Exception ex1)
        {
            MessageBox.Show(ex1.Message);
        }
    }
}
}

cast or convert a float to nvarchar?

Do not use floats to store fixed-point, accuracy-required data. This example shows how to convert a float to NVARCHAR(50) properly, while also showing why it is a bad idea to use floats for precision data.

create table #f ([Column_Name] float)
insert #f select 9072351234
insert #f select 907235123400000000000

select
    cast([Column_Name] as nvarchar(50)),
    --cast([Column_Name] as int), Arithmetic overflow
    --cast([Column_Name] as bigint), Arithmetic overflow
    CAST(LTRIM(STR([Column_Name],50)) AS NVARCHAR(50))
from #f

Output

9.07235e+009    9072351234
9.07235e+020    907235123400000010000

You may notice that the 2nd output ends with '10000' even though the data we tried to store in the table ends with '00000'. It is because float datatype has a fixed number of significant figures supported, which doesn't extend that far.

Should I use 'border: none' or 'border: 0'?

Both are valid. It's your choice.

I prefer border:0 because it's shorter; I find that easier to read. You may find none more legible. We live in a world of very capable CSS post-processors so I'd recommend you use whatever you prefer and then run it through a "compressor". There's no holy war worth fighting here but Webpack?LESS?PostCSS?PurgeCSS is a good 2020 stack.

That all said, if you're hand-writing all your production CSS, I maintain —despite the grumbling in the comments— it does not hurt to be bandwidth conscious. Using border:0 will save an infinitesimal amount of bandwidth on its own, but if you make every byte count, you will make your website faster.


The CSS2 specs are here. These are extended in CSS3 but not in any way relevant to this.

'border'
    Value:      [ <border-width> || <border-style> || <'border-top-color'> ] | inherit
    Initial:    see individual properties
    Applies to:     all elements
    Inherited:      no
    Percentages:    N/A
    Media:      visual
    Computed value:     see individual properties 

You can use any combination of width, style and colour.
Here, 0 sets the width, none the style. They have the same rendering result: nothing is shown.

MySQL - count total number of rows in php

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  echo "number of rows: ",$rowcount;
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

it is best way (I think) to get the number of special row in mysql with php.

Java Embedded Databases Comparison

Most things have been said already, but I can just add that I've used HSQL, Derby and Berkely DB in a few of my pet projects and they all worked just fine. So I don't think it really matters much to be honest. One thing worth mentioning is that HSQL saves itself as a text file with SQL statements which is quite good. Makes it really easy for when you are developing to do tests and setup data quickly. Can also do quick edits if needed. Guess you could easily transfer all that to any database if you ever need to change as well :)

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

Look here for the answer by TheMattster. I implemented it and it worked like a charm. In a nutshell, his solution suggests to add the COM dll as a resource to the project (so now it compiles into the project's dll), and upon the first run write it to a file (i.e. the dll file I wanted there in the first place).

The following is taken from his answer.

Step 1) Add the DLL as a resource (below as "Resources.DllFile"). To do this open project properties, select the resources tab, select "add existing file" and add the DLL as a resource.

Step 2) Add the name of the DLL as a string resource (below as "Resources.DllName").

Step 3) Add this code to your main form-load:

if (!File.Exists(Properties.Resources.DllName))
{
    var outStream = new StreamWriter(Properties.Resources.DllName, false);
    var binStream = new BinaryWriter(outStream.BaseStream);
    binStream.Write(Properties.Resources.DllFile);
    binStream.Close();
}

My problem was that not only I had to use the COM dll in my project, I also had to deploy it with my app using ClickOnce, and without being able to add reference to it in my project the above solution is practically the only one that worked.

How to control the line spacing in UILabel

In Swift and as a function, inspired by DarkDust

// Usage: setTextWithLineSpacing(myEpicUILabel,text:"Hello",lineSpacing:20)
func setTextWithLineSpacing(label:UILabel,text:String,lineSpacing:CGFloat)
{
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = lineSpacing

    let attrString = NSMutableAttributedString(string: text)
    attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

    label.attributedText = attrString
}

How to convert an array of strings to an array of floats in numpy?

If you have (or create) a single string, you can use np.fromstring:

import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )

Note, x = ','.join(x) transforms the x array to string '1.1, 2.2, 3.2'. If you read a line from a txt file, each line will be already a string.

Find the location of a character in string

You can use gregexpr

 gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")


[[1]]
[1]  4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE

or perhaps str_locate_all from package stringr which is a wrapper for gregexpr stringi::stri_locate_all (as of stringr version 1.0)

library(stringr)
str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired")

[[1]]
     start end
[1,]     4   4
[2,]    24  24

note that you could simply use stringi

library(stringi)
stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)

Another option in base R would be something like

lapply(strsplit(x, ''), function(x) which(x == '2'))

should work (given a character vector x)

Android WSDL/SOAP service client

Icesoap, which I found yesterday, looks promising. It worked on a basic test, but it lacks more examples.

How to get current url in view in asp.net core 1.0

If you're looking to also get the port number out of the request you'll need to access it through the Request.Host property for AspNet Core.

The Request.Host property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"), then calling Request.Host will give you the host domain and the port number like so: "example.com:8080".

If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host or Request.Host.Port).

Node JS Promise.all and forEach

It's pretty straightforward with some simple rules:

  • Whenever you create a promise in a then, return it - any promise you don't return will not be waited for outside.
  • Whenever you create multiple promises, .all them - that way it waits for all the promises and no error from any of them are silenced.
  • Whenever you nest thens, you can typically return in the middle - then chains are usually at most 1 level deep.
  • Whenever you perform IO, it should be with a promise - either it should be in a promise or it should use a promise to signal its completion.

And some tips:

  • Mapping is better done with .map than with for/push - if you're mapping values with a function, map lets you concisely express the notion of applying actions one by one and aggregating the results.
  • Concurrency is better than sequential execution if it's free - it's better to execute things concurrently and wait for them Promise.all than to execute things one after the other - each waiting before the next.

Ok, so let's get started:

var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
    return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns

var actions = items.map(fn); // run the function over all items

// we now have a promises array and we want to wait for it

var results = Promise.all(actions); // pass array of promises

results.then(data => // or just .then(console.log)
    console.log(data) // [2, 4, 6, 8, 10]
);

// we can nest this of course, as I said, `then` chains:

var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
    data => Promise.all(data.map(fn))
).then(function(data){
    // the next `then` is executed after the promise has returned from the previous
    // `then` fulfilled, in this case it's an aggregate promise because of 
    // the `.all` 
    return Promise.all(data.map(fn));
}).then(function(data){
    // just for good measure
    return Promise.all(data.map(fn));
});

// now to get the results:

res2.then(function(data){
    console.log(data); // [16, 32, 48, 64, 80]
});

React.createElement: type is invalid -- expected a string

Array of components

A common way to get this error is using an array of components, with a positional index used to select the component to render from the array. I saw a code like this many times:

const checkoutSteps = [Address, Shipment, Payment]

export const Checkout = ({step}) => {

  const ToRender = checkoutSteps[step]

  return (
    <ToRender />
  )
}

This is not necessary bad code, but if you call it with a wrong index (eg -1, or 3 in this case), the ToRender component will be undefined, throwing the React.createElement: type is invalid... error:

<Checkout step={0} /> // <Address />
<Checkout step={1} /> // <Shipment />
<Checkout step={2} /> // <Payment />
<Checkout step={3} /> // undefined
<Checkout step={-1} /> // undefined

A rational solution

You should protect yourself and your collegues from this hard-to-debug code using a more explicit approach, avoiding magic numbers and using PropTypes:

const checkoutSteps = {
  address: Address,
  shipment Shipment,
  payment: Payment
}

const propTypes = {
  step: PropTypes.oneOf(['address', 'shipment', 'payment']),
}

/* TIP: easier to maintain
const propTypes = {
  step: PropTypes.oneOf(Object.keys(checkoutSteps)),
}
*/

const Checkout = ({step}) => {

  const ToRender = checkoutSteps[step]

  return (
    <ToRender />
  )
}

Checkout.propTypes = propTypes

export default Checkout

And your code will look like this:

// OK
<Checkout step="address" /> // <Address />
<Checkout step="shipment" /> // <Shipment />
<Checkout step="payment" /> // <Payment />

// Errors
<Checkout step="wrongstep" /> // explicit error "step must be one of..."
<Checkout step={3} /> // explicit error (same as above)
<Checkout step={myWrongVar} /> // explicit error (same as above)

Benefits of this approach

  • code is more explicit, you can clearly see what you want to render
  • you don't need to remember the numbers and their hidden meaning (1 is for Address, 2 is for...)
  • errors are explicit too
  • no headache for your peers :)

Python JSON serialize a Decimal object

this can be done by adding

    elif isinstance(o, decimal.Decimal):
        yield str(o)

in \Lib\json\encoder.py:JSONEncoder._iterencode, but I was hoping for a better solution

Using curl to upload POST data with files

Here is how to correctly escape arbitrary filenames of uploaded files with bash:

#!/bin/bash
set -eu

f="$1"
f=${f//\\/\\\\}
f=${f//\"/\\\"}
f=${f//;/\\;}

curl --silent --form "uploaded=@\"$f\"" "$2"

updating table rows in postgres using subquery

If there are no performance gains using a join, then I prefer Common Table Expressions (CTEs) for readability:

WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
)
UPDATE dummy
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE dummy.address_id = subquery.address_id;

IMHO a bit more modern.

How to use adb command to push a file on device without sd card

In Mac: To push files via adb

adb push /Users/Downloads?/amazon.sdktester.json '/mnt/sdcard/amazon.sdktester.json'

ES6 modules implementation, how to load a json file

This just works on React & React Native

const data = require('./data/photos.json');

console.log('[-- typeof data --]', typeof data); // object


const fotos = data.xs.map(item => {
    return { uri: item };
});

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

JQuery get data from JSON array

You're not looping over the items. Try this instead:

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

How to use an environment variable inside a quoted string in Bash

Note that COLUMNS is:

  1. NOT an environment variable. It is an ordinary bash parameter that is set by bash itself.
  2. Set automatically upon receipt of a SIGWINCH signal.

That second point usually means that your COLUMNS variable will only be set in your interactive shell, not in a bash script.

If your script's stdin is connected to your terminal you can manually look up the width of your terminal by asking your terminal:

tput cols

And to use this in your SVN command:

svn diff "$@" --diff-cmd /usr/bin/diff -x "-y -w -p -W $(tput cols)"

(Note: you should quote "$@" and stay away from eval ;-))

PHP function use variable from outside

Alternatively, you can bring variables in from the outside scope by using closures with the use keyword.

$myVar = "foo";
$myFunction = function($arg1, $arg2) use ($myVar)
{
 return $arg1 . $myVar . $arg2;
};

Android sqlite how to check if a record exists

Raw queries are more vulnerable to SQL Injection. I will suggest using query() method instead.

public boolean Exists(String searchItem) {

    String[] columns = { COLUMN_NAME };
    String selection = COLUMN_NAME + " =?";
    String[] selectionArgs = { searchItem };
    String limit = "1";

    Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
    boolean exists = (cursor.getCount() > 0);
    cursor.close();
    return exists;
}

Source: here

Make: how to continue after a command fails?

Return successfully by blocking rm's returncode behind a pipe with the true command, which always returns 0 (success)

rm file | true

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

IE 8: background-size fix

As posted by 'Dan' in a similar thread, there is a possible fix if you're not using a sprite:

How do I make background-size work in IE?

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

However, this scales the entire image to fit in the allocated area. So if your using a sprite, this may cause issues.

Caution
The filter has a flaw, any links inside the allocated area are no longer clickable.

Adding a Method to an Existing Object Instance

Since this question asked for non-Python versions, here's JavaScript:

a.methodname = function () { console.log("Yay, a new method!") }

"Faceted Project Problem (Java Version Mismatch)" error message

In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.

Thanks & Regards Vengat Maran

What is the order of precedence for CSS?

The order in which the classes appear in the html element does not matter, what counts is the order in which the blocks appear in the style sheet.

In your case .smallbox-paysummary is defined after .smallbox hence the 10px precedence.

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

you can use skimage.img_as_ubyte(yourdata) it will make you numpy array ranges from 0->255

from skimage import img_as_ubyte

img = img_as_ubyte(data)
cv2.imshow("Window", img)

Object Dump JavaScript

Just use:

console.dir(object);

you will get a nice clickable object representation. Works in Chrome and Firefox

Errors: Data path ".builders['app-shell']" should have required property 'class'

On my side it was package

@angular-devkit/build-angular

and

@angular-devkit/build-ng-packagr

was not the same version, Updating build-ng-packagr to same version as build-angular fixed my problem.

How to pass multiple parameters in a querystring

This can be done by using:

Response.Redirect("http://localhost/YourControllerName/ActionMethodName?querystring1=querystringvalue1&querystring2=querystringvalue2&querystring3=querystringvalue3");

Pull all images from a specified directory and then display them

You can also use glob for this:

$dirname = "media/images/iconized/";
$images = glob($dirname."*.png");

foreach($images as $image) {
    echo '<img src="'.$image.'" /><br />';
}

What's the difference between UTF-8 and UTF-8 without BOM?

There are at least three problems with putting a BOM in UTF-8 encoded files.

  1. Files that hold no text are no longer empty because they always contain the BOM.
  2. Files that hold text that is within the ASCII subset of UTF-8 is no longer themselves ASCII because the BOM is not ASCII, which makes some existing tools break down, and it can be impossible for users to replace such legacy tools.
  3. It is not possible to concatenate several files together because each file now has a BOM at the beginning.

And, as others have mentioned, it is neither sufficient nor necessary to have a BOM to detect that something is UTF-8:

  • It is not sufficient because an arbitrary byte sequence can happen to start with the exact sequence that constitutes the BOM.
  • It is not necessary because you can just read the bytes as if they were UTF-8; if that succeeds, it is, by definition, valid UTF-8.

calculate the mean for each column of a matrix in R

Another way is to use purrr package

# example data like what is said above

@A Handcart And Mohair

set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))


library(purrr)
means <- map_dbl(m, mean)

> means
#  X1   X2   X3   X4 
#47.0 64.4 44.8 67.8 

How can I configure Logback to log different levels for a logger to different destinations?

This is the configuration that I use, which works fine, it is based on XML + JaninoEventEvaluator (requires the Janino library to be added to Classpath)

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%date | [%-5level] in [%file:%line] - %msg %n</pattern>
    </encoder>
    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
        <evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
            <expression>
                level &lt;= INFO
            </expression>
        </evaluator>
        <OnMismatch>DENY</OnMismatch>
        <OnMatch>NEUTRAL</OnMatch>
    </filter>
</appender>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
    <target>System.err</target>
    <encoder>
        <pattern>%date | [%-5level] in [%file:%line] - %msg %n</pattern>
    </encoder>
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>WARN</level>
    </filter>
</appender>

<root level="DEBUG">
    <appender-ref ref="STDOUT" />
    <appender-ref ref="STDERR" />
</root>
</configuration>  

How to fix nginx throws 400 bad request headers on any header testing tools?

normally, Maxim Donnie's method can find the reason. But I encountered one 400 bad request will not log to err_log. I found the reason with the help with tcpdump

What is the scope of variables in JavaScript?

Here's an example:

<script>

var globalVariable = 7; //==window.globalVariable

function aGlobal( param ) { //==window.aGlobal(); 
                            //param is only accessible in this function
  var scopedToFunction = {
    //can't be accessed outside of this function

    nested : 3 //accessible by: scopedToFunction.nested
  };

  anotherGlobal = {
    //global because there's no `var`
  }; 

}

</script>

You'll want to investigate closures, and how to use them to make private members.

How to remove error about glyphicons-halflings-regular.woff2 not found

For me, the problem was twofold: First, the version of IIS I was dealing with didn't know about the .woff2 MIME type, only about .woff. I fixed that using IIS Manager at the server level, not at the web app level, so the setting wouldn't get overridden with each new app deployment. (Under IIS Manager, I went to MIME types, and added the missing .woff2, then updated .woff.)

Second, and more importantly, I was bundling bootstrap.css along with some other files as "~/bundles/css/site". Meanwhile, my font files were in "~/fonts". bootstrap.css looks for the glyphicon fonts in "../fonts", which translated to "~/bundles/fonts" -- wrong path.

In other words, my bundle path was one directory too deep. I renamed it to "~/bundles/siteCss", and updated all the references to it that I found in my project. Now bootstrap looked in "~/fonts" for the glyphicon files, which worked. Problem solved.

Before I fixed the second problem above, none of the glyphicon font files were loading. The symptom was that all instances of glyphicon glyphs in the project just showed an empty box. However, this symptom only occurred in the deployed versions of the web app, not on my dev machine. I'm still not sure why that was the case.

How to calculate sum of a formula field in crystal Reports?

You Can simply Right Click Formula Fields- > new Give it a name like TotalCount then Right this code:

if(isnull(sum(count({YOURCOLUMN})))) then
0
else
(sum(count({YOURCOLUMN})))

and Save then Drag and drop TotalCount this field in header/footer. After you open the "count" bracket you can drop your column there from the above section.See the example in the Pictureenter image description here

libxml install error using pip

Using Windows 7 with Cygwin, I came across:

Compile failed: command 'gcc' failed with exit status 1
cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInitZsgdMQ.c -o tmp/xmlXPathInitZsgdMQ.o
*********************************************************************************
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
*********************************************************************************
error: command 'gcc' failed with exit status 1

I fixed it by installing mingw64-x86_64-libxslt

Regex for parsing directory and filename

What about this?

[/]{0,1}([^/]+[/])*([^/]*)

Deterministic :

((/)|())([^/]+/)*([^/]*)

Strict :

^[/]{0,1}([^/]+[/])*([^/]*)$
^((/)|())([^/]+/)*([^/]*)$

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

This error is due to if there is white spaces where your repo is copied. E.g. my project is copied in below location c://projects/My rest project then you can see the white spaces there, if you change your repo path to below, it should work c://projects/myrestproject

How do you kill a Thread in Java?

Generally you don't..

You ask it to interrupt whatever it is doing using Thread.interrupt() (javadoc link)

A good explanation of why is in the javadoc here (java technote link)

How to make div fixed after you scroll to that div?

Adding on to @Alexandre Aimbiré's answer - sometimes you may need to specify z-index:1 to have the element always on top while scrolling. Like this:

position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;

keycode and charcode

It is a conditional statement.

If browser supprts e.keyCode then take e.keyCode else e.charCode.

It is similar to

var code = event.keyCode || event.charCode

event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

event.charCode: Returns the Unicode value of a character key pressed during a keypress event.

How does the "position: sticky;" property work?

It's TRUE that the overflow needs to be removed or set to initial to make position: sticky works on the child element. I used Material Design in my Angular app and found out that some Material components changed the overflow value. The fix for my scenario is

mat-sidenav-container, mat-sidenav-content {
  overflow: initial;
}

String field value length in mongoDB

Queries with $where and $expr are slow if there are too many documents.

Using $regex is much faster than $where, $expr.

db.usercollection.find({ 
  "name": /^[\s\S]{40,}$/, // name.length >= 40
})

or 

db.usercollection.find({ 
  "name": { "$regex": "^[\s\S]{40,}$" }, // name.length >= 40
})

This query is the same meaning with

db.usercollection.find({ 
  "$where": "this.name && this.name.length >= 40",
})

or

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gte": [ { "$strLenCP": "$name" }, 40 ] } 
})

I tested each queries for my collection.

# find
$where: 10529.359ms
$expr: 5305.801ms
$regex: 2516.124ms

# count
$where: 10872.006ms
$expr: 2630.155ms
$regex: 158.066ms

How can one run multiple versions of PHP 5.x on a development LAMP server?

One way to do this is to have your main version of php set up with mod_php and run all of the others through fast cgi on different ports (i.e. 81, 82, 83 etc). This won't guarantee totally consistent behavior though.

Eclipse returns error message "Java was started but returned exit code = 1"

I received this error out of the blue. Eclipse stopped working even though I made no config changes and did not install any new jdk's.

Here was my eclipse.ini file :

--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:/Program Files (x86)/Java/jre7/bin/javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx1024m

To get Eclipse to start successfully I removed

    -vmargs
    -Dosgi.requiredJavaVersion=1.6
    -vm 
C:/Program Files (x86)/Java/jre7/bin/javaw.exe

So here is my updated file :

--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-Xms40m
-Xmx1024m

I have no idea why removing osgi.requiredJavaVersion=1.6 fixed this as my jvm version is 1.6. From the doc http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html

osgi.requiredJavaVersion
The minimum java version that is required to launch Eclipse. The default value is "1.4.1".

I think my java version was set correctly. Anyway Eclipse starts and runs for me now......

R: Plotting a 3D surface from x, y, z

You can use the function outer() to generate it.

Have a look at the demo for the function persp(), which is a base graphics function to draw perspective plots for surfaces.

Here is their first example:

x <- seq(-10, 10, length.out = 50)  
y <- x  
rotsinc <- function(x,y) {
    sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }  
    10 * sinc( sqrt(x^2+y^2) )  
}

z <- outer(x, y, rotsinc)  
persp(x, y, z)

The same applies to surface3d():

require(rgl)  
surface3d(x, y, z)

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

Using LINQ to group a list of objects

The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID

 var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                                  .Select(group => new { GroupID = group.Key, Customers = group.ToList() })
                                                  .ToList();

What does IFormatProvider do?

In adition to Ian Boyd's answer:

Also CultureInfo implements this interface and can be used in your case. So you could parse a French date string for example; you could use

var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);

BeautifulSoup: extract text from anchor tag

This will help:

from bs4 import BeautifulSoup

data = '''<div class="image">
        <a href="http://www.example.com/eg1">Content1<img  
        src="http://image.example.com/img1.jpg" /></a>
        </div>
        <div class="image">
        <a href="http://www.example.com/eg2">Content2<img  
        src="http://image.example.com/img2.jpg" /> </a>
        </div>'''

soup = BeautifulSoup(data)

for div in soup.findAll('div', attrs={'class':'image'}):
    print(div.find('a')['href'])
    print(div.find('a').contents[0])
    print(div.find('img')['src'])

If you are looking into Amazon products then you should be using the official API. There is at least one Python package that will ease your scraping issues and keep your activity within the terms of use.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

For an assembly project (ProjectName -> Build Dependencies -> Build Customizations -> masm (selected)), setting Generate Preprocessed Source Listing to True caused the problem for me too, clearing the setting fixed it. VS2013 here.

concatenate char array in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *name = "hello";

int main(void) {
  char *ext = ".txt";
  int len   = strlen(name) + strlen(ext) + 1;
  char *n2  = malloc(len);
  char *n2a = malloc(len);

  if (n2 == NULL || n2a == NULL)
    abort();

  strlcpy(n2, name, len);
  strlcat(n2, ext, len);
  printf("%s\n", n2);

  /* or for conforming C99 ...  */
  strncpy(n2a, name, len);
  strncat(n2a, ext, len - strlen(n2a));
  printf("%s\n", n2a);

  return 0; // this exits, otherwise free n2 && n2a
}

What is the difference between a pandas Series and a single-column DataFrame?

Quoting the Pandas docs

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.

So, the Series is the data structure for a single column of a DataFrame, not only conceptually, but literally, i.e. the data in a DataFrame is actually stored in memory as a collection of Series.

Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.

They both have extremely similar APIs, but you'll find that DataFrame methods always cater to the possibility that you have more than one column. And, of course, you can always add another Series (or equivalent object) to a DataFrame, while adding a Series to another Series involves creating a DataFrame.

What's the difference between StaticResource and DynamicResource in WPF?

  1. StaticResource uses first value. DynamicResource uses last value.
  2. DynamicResource can be used for nested styling, StaticResource cannot.

Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type Grid}">
        <Style.Resources>
            <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
                <Setter Property="Background" Value="Pink"/>
            </Style>
        </Style.Resources>
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
        <Setter Property="Background" Value="LightGreen"/>
    </Style>
</ResourceDictionary>

In view:

<Window x:Class="WpfStyleDemo.ConflictingStyleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ConflictingStyleWindow" Height="100" Width="100">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/ConflictingStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button Style="{DynamicResource ConflictButton}" Content="Test"/>
    </Grid>
</Window>

StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.

StaticResource StaticResource

DynamicResource DynamicResource

Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.

StaticResource will throw an error when the root-level style (LightGreen) is removed.

angular2: how to copy object into another object

Solution

Angular2 developed on the ground of modern technologies like TypeScript and ES6.

So you can just do let copy = Object.assign({}, myObject).

Object assign - nice examples.

For nested objects : let copy = JSON.parse(JSON.stringify(myObject))

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

It's because you can't resolve the host name Maybe DNS problems, host is unreachable...

try to use IP address instead of host name... ping this host name... nslookup it...

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

First must be Alphabet and then dot not allowed in target string. below is code.

        string input = "A_aaA";

        // B
        // The regular expression we use to match
        Regex r1 = new Regex("^[A-Za-z][^.]*$"); //[\t\0x0020] tab and spaces.

        // C
        // Match the input and write results
        Match match = r1.Match(input);
        if (match.Success)
        {
            Console.WriteLine("Valid: {0}", match.Value);

        }
        else
        {
            Console.WriteLine("Not Match");
        }


        Console.ReadLine();

How to disable SSL certificate checking with Spring RestTemplate?

Disabling certificate checking is the wrong solution, and radically insecure.

The correct solution is to import the self-signed certificate into your truststore. An even more correct solution is to get the certificate signed by a CA.

If this is 'only for testing' it is still necessary to test the production configuration. Testing something else isn't a test at all, it's just a waste of time.

non static method cannot be referenced from a static context

You're trying to invoke an instance method on the class it self.

You should do:

    Random rand = new Random();
    int a = 0 ; 
    while (!done) { 
        int a = rand.nextInt(10) ; 
    ....

Instead

As I told you here stackoverflow.com/questions/2694470/whats-wrong...

Can I use an HTML input type "date" to collect only a year?

You can do the following:

  1. Generate an Array of the years I'll be accepting,
  2. Use a select box.
  3. Use each item from your Array as an 'option' tag.

Example using PHP (you can do this in any language of your choice):

Server:

<?php $years = range(1900, strftime("%Y", time())); ?>

HTML

<select>
  <option>Select Year</option>
  <?php foreach($years as $year) : ?>
    <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
  <?php endforeach; ?>
</select>

As an added benefit, this works has a browser compatibility of a 100% ;-)

Replace new lines with a comma delimiter with Notepad++?

Here's what worked for me with a similar list of strings in Notepad++ without any macros or anything else:

  1. Click Edit -> Blank Operations -> EOL to space [All the items should now be in a single line separated by a 'space']

  2. Select any 'space' and do a Replace All (by ',')

Opacity of div's background without affecting contained element in IE 8?

The opacity style affects the whole element and everything within it. The correct answer to this is to use an rgba background colour instead.

The CSS is fairly simple:

.myelement {
    background: rgba(200, 54, 54, 0.5);
}

...where the first three numbers are the red, green and blue values for your background colour, and the fourth is the 'alpha' channel value, which works the same way as the opacity value.

See this page for more info: http://css-tricks.com/rgba-browser-support/

The down-side, is that this doesn't work in IE8 or lower. The page I linked above also lists a few other browsers it doesn't work in, but they're all very old by now; all browsers in current use except IE6/7/8 will work with rgba colours.

The good news is that you can force IE to work with this as well, using a hack called CSS3Pie. CSS3Pie adds a number of modern CSS3 features to older versions of IE, including rgba background colours.

To use CSS3Pie for backgrounds, you need to add a specific -pie-background declaration to your CSS, as well as the PIE behavior style, so your stylesheet would end up looking like this:

.myelement {
    background: rgba(200, 54, 54, 0.5);
    -pie-background:  rgba(200, 54, 54, 0.5);
    behavior: url(PIE.htc);
}

Hope that helps.

[EDIT]

For what it's worth, as others have mentioned, you can use IE's filter style, with the gradient keyword. The CSS3Pie solution does actually use this same technique behind the scenes, but removes the need for you to mess around directly with IE's filters, so your stylesheets are much cleaner. (it also adds a whole bunch of other nice features too, but that's not relevant to this discussion)

How to Store Historical Data

Just wanted to add an option that I started using because I use Azure SQL and the multiple table thing was way too cumbersome for me. I added an insert/update/delete trigger on my table and then converted the before/after change to json using the "FOR JSON AUTO" feature.

 SET @beforeJson = (SELECT * FROM DELETED FOR JSON AUTO)
SET @afterJson = (SELECT * FROM INSERTED FOR JSON AUTO)

That returns a JSON representation fo the record before/after the change. I then store those values in a history table with a timestamp of when the change occurred (I also store the ID for current record of concern). Using the serialization process, I can control how data is backfilled in the case of changes to schema.

I learned about this from this link here

intelliJ IDEA 13 error: please select Android SDK

Delete all android SDKs from Intellij and add them again.

To do this open project structure, in SDK pane, delete all android SDK, click OK. open project structure and add them again.

HTML span align center not working?

Please use the following style. margin:auto normally used to center align the content. display:table is needed for span element

<span style="margin:auto; display:table; border:1px solid red;">
    This is some text in a div element!
</span>

How to implement class constructor in Visual Basic?

A class with a field:

Public Class MyStudent
   Public StudentId As Integer

The constructor:

    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

What is the difference between :focus and :active?

Using "focus" will give keyboard users the same effect that mouse users get when they hover with a mouse. "Active" is needed to get the same effect in Internet Explorer.

The reality is, these states do not work as they should for all users. Not using all three selectors creates accessibility issues for many keyboard-only users who are physically unable to use a mouse. I invite you to take the #nomouse challenge (nomouse dot org).

Save bitmap to location

Create a video thumbnail for a video. It may return null if the video is corrupted or the format is not supported.

private void makeVideoPreview() {
    Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(videoAbsolutePath, MediaStore.Images.Thumbnails.MINI_KIND);
    saveImage(thumbnail);
}

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

What is the advantage of using REST instead of non-REST HTTP?

  • Give every “resource” an ID
  • Link things together
  • Use standard methods
  • Resources with multiple representations
  • Communicate statelessly

It is possible to do everything just with POST and GET? Yes, is it the best approach? No, why? because we have standards methods. If you think again, it would be possible to do everything using just GET.. so why should we even bother do use POST? Because of the standards!

For example, today thinking about a MVC model, you can limit your application to respond just to specific kinds of verbs like POST, GET, PUT and DELETE. Even if under the hood everything is emulated to POST and GET, don't make sense to have different verbs for different actions?

Getting and removing the first character of a string

There is also str_sub from the stringr package

x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"

How can I center text (horizontally and vertically) inside a div block?

Common techniques as of 2014:


  • Approach 1 - transform translateX/translateY:

    Example Here / Full Screen Example

    In supported browsers (most of them), you can use top: 50%/left: 50% in combination with translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.

    .container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
    }
    

  • Approach 2 - Flexbox method:

    Example Here / Full Screen Example

    In supported browsers, set the display of the targeted element to flex and use align-items: center for vertical centering and justify-content: center for horizontal centering. Just don't forget to add vendor prefixes for additional browser support (see example).

    html, body, .container {
        height: 100%;
    }
    .container {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    

  • Approach 3 - table-cell/vertical-align: middle:

    Example Here / Full Screen Example

    In some cases, you will need to ensure that the html/body element's height is set to 100%.

    For vertical alignment, set the parent element's width/height to 100% and add display: table. Then for the child element, change the display to table-cell and add vertical-align: middle.

    For horizontal centering, you could either add text-align: center to center the text and any other inline children elements. Alternatively, you could use margin: 0 auto assuming the element is block level.

    html, body {
        height: 100%;
    }
    .parent {
        width: 100%;
        height: 100%;
        display: table;
        text-align: center;
    }
    .parent > .child {
        display: table-cell;
        vertical-align: middle;
    }
    

  • Approach 4 - Absolutely positioned 50% from the top with displacement:

    Example Here / Full Screen Example

    This approach assumes that the text has a known height - in this instance, 18px. Just absolutely position the element 50% from the top, relative to the parent element. Use a negative margin-top value that is half of the element's known height, in this case - -9px.

    html, body, .container {
        height: 100%;
    }
    .container {
        position: relative;
        text-align: center;
    }
    .container > p {
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        margin-top: -9px;
    }
    

  • Approach 5 - The line-height method (Least flexible - not suggested):

    Example Here

    In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a line-height value on the child element equal to the fixed height of the parent element.

    Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this.

    .parent {
        height: 200px;
        width: 400px;
        text-align: center;
    }
    .parent > .child {
        line-height: 200px;
    }
    

Methods 4 and 5 aren't the most reliable. Go with one of the first 3.

What's the u prefix in a Python string?

All strings meant for humans should use u"".

I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u"" syntax. The "" syntax is for byte arrays, only.

Before the bashing begins, let me explain. Most Python programs start out with using "" for strings. But then they need to support documentation off the Internet, so they start using "".decode and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of "" for strings. In this case, Unicode does act like a virus and will wreak havoc.

But, if you follow my rule, you won't have this infection (because you will already be infected).

phpMyAdmin - The MySQL Extension is Missing

Just check your php.ini file, In this file Semicolon(;) used for comment if you see then remove semicolon ;.

;extension=mysql.dll

Now your extension is enable but you need to restart appache

extension=mysql.dll