Programs & Examples On #Func

Func is a family of delegate types in the .Net framework.

Func vs. Action vs. Predicate

Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

var result = someCollection.Select( x => new { x.Name, x.Address });

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

button1.Click += (sender, e) => { /* Do Some Work */ }

Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

var filteredResults = 
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

"undefined" function declared in another file?

Please read "How to Write Go Code".

Use go build or go install within the package directory, or supply an import path for the package. Do not use file arguments for build or install.

While you can use file arguments for go run, you should build a package instead, usually with go run ., though you should almost always use go install, or go build.

Click outside menu to close in jquery

what about this?

    $(this).mouseleave(function(){  
        var thisUI = $(this);
        $('html').click(function(){
                thisUI.hide();
            $('html').unbind('click');
         });
     });

Make <body> fill entire screen?

I had to apply 100% to both html and body.

Deleting multiple columns based on column names in Pandas

The below worked for me:

for col in df:
    if 'Unnamed' in col:
        #del df[col]
        print col
        try:
            df.drop(col, axis=1, inplace=True)
        except Exception:
            pass

How to use AND in IF Statement

If there are no typos in the question, you got the conditions wrong:

You said this:

IF cells (i,"A") contains the text 'Miami'

...but your code says:

If Cells(i, "A") <> "Miami"

--> <> means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.

I guess you want this instead:

If Cells(i, "A") like "*Miami*"

EDIT:

Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).

Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.

Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA" line?
Or is the If Cells(i, "A") like "*Miami*" stuff already False?
If yes, try checking just one cell and see if that works.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Acked Unseen sample

Hi guys! Just some observations from what I just found in my capture:

On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client

Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC

  • In the capture example above, frame 67795 sends an ACK for 10384

  • Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194

  • Frame 67800 sends an ACK for 23524
  • 10384+13194 = 23578
  • 23578 – 23524 = 54
  • 54 is in fact length of the Ethernet / IP / TCP headers (14 for Ethernt, 20 for IP, 20 for TCP)
  • So in fact, the frame 67796 does represent a large TCP packets (13194 bytes) which operating system tried to put on the wore
    • NIC driver will fragment it into smaller 1500 bytes pieces in order to transmit over the network
    • But Wireshark running on my PC fails to understand it is a valid packet and parse it. I believe Wireshark running on 2012 Windows server reads these captures correctly
  • So after all, these “Bogus IP length” and “ACKed segment that wasn't captured” alerts were in fact false positives in my case

C++ IDE for Macs

It's not really an IDE per se, but I really like TextMate, and with the C++ bundle that ships with it, it can do a lot of the things you'd find in an IDE (without all the bloat!).

How to .gitignore all files/folder in a folder, but not the folder itself?

Put this .gitignore into the folder, then git add .gitignore.

*
*/
!.gitignore

The * line tells git to ignore all files in the folder, but !.gitignore tells git to still include the .gitignore file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore it needs.

Edit: May be obvious but also add */ to the .gitignore to also ignore subfolders.

How to change RGB color to HSV?

Have you considered simply using System.Drawing namespace? For example:

System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);
float hue = color.GetHue();
float saturation = color.GetSaturation();
float lightness = color.GetBrightness();

Note that it's not exactly what you've asked for (see differences between HSL and HSV and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably easy to add.

Addressing localhost from a VirtualBox virtual machine

Googling turned this up: http://data.agaric.com/localhost-from-virtualbox-xp-install-ubuntu

It suggests using IP: http://10.0.2.2, and it worked for me.

So, I edited the hosts file, C:\windows\system32\drivers\etc\hosts, and added this entry:

10.0.2.2   outer

If you're testing on IE8, remember to put http:// in the address bar. Just putting the ip directly will not work.

For example:

http://10.0.2.2:3000/

DateTime2 vs DateTime in SQL Server

I just stumbled across one more advantage for DATETIME2: it avoids a bug in the Python adodbapi module, which blows up if a standard library datetime value is passed which has non-zero microseconds for a DATETIME column but works fine if the column is defined as DATETIME2.

How do I initialize the base (super) class?

Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object and are what you are using, and invoke their base class through super(), e.g.

class X(object):
  def __init__(self, x):
    pass

  def doit(self, bar):
    pass

class Y(X):
  def __init__(self):
    super(Y, self).__init__(123)

  def doit(self, foo):
    return super(Y, self).doit(foo)

Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.

For completeness sake, old-style classes call base methods explicitly using the base class, i.e.

def doit(self, foo):
  return X.doit(self, foo)

But since you shouldn't be using old-style anymore, I wouldn't care about this too much.

Python 3 only knows about new-style classes (no matter if you derive from object or not).

CSS media query to target iPad and iPad only?

Well quite same question and there is also an answer =)

http://css-tricks.com/forums/discussion/12708/target-ipad-ipad-only./p1

@media only screen and (device-width: 768px) ...
@media only screen and (max-device-width: 1024px) ...

I can not test it currently so please test it =)

Also found some more:

http://perishablepress.com/press/2010/10/20/target-iphone-and-ipad-with-css3-media-queries/

Or you check the navigator with some javascript and generate / add a css file with javascript

Drop rows containing empty cells from a pandas DataFrame

There's a situation where the cell has white space, you can't see it, use

df['col'].replace('  ', np.nan, inplace=True)

to replace white space as NaN, then

df= df.dropna(subset=['col'])

Regex: Check if string contains at least one digit

Another possible solution, in case you're looking for all the words in a given string, which contain a number

Pattern

\w*\d{1,}\w*
  • \w* - Matches 0 or more instances of [A-Za-z0-9_]
  • \d{1,} - Matches 1 or more instances of a number
  • \w* - Matches 0 or more instances of [A-Za-z0-9_]

The whole point in \w* is to allow not having a character in the beginning or at the end of a word. This enables capturing the first and last words in the text.

If the goal here is to only get the numbers without the words, you can omit both \w*.

Given the string

Hello world 1 4m very happy to be here, my name is W1lly W0nk4

Matches

1 4m W1lly W0nk4

Check this example in regexr - https://regexr.com/5ff7q

How to delete duplicates on a MySQL table?

DELETE T2
FROM   table_name T1
JOIN   same_table_name T2 ON (T1.title = T2.title AND T1.ID <> T2.ID)

Android: How do bluetooth UUIDs work?

In Bluetooth, all objects are identified by UUIDs. These include services, characteristics and many other things. Bluetooth maintains a database of assigned numbers for standard objects, and assigns sub-ranges for vendors (that have paid enough for a reservation). You can view this list here:

https://www.bluetooth.com/specifications/assigned-numbers/

If you are implementing a standard service (e.g. a serial port, keyboard, headset, etc.) then you should use that service's standard UUID - that will allow you to be interoperable with devices that you didn't develop.

If you are implementing a custom service, then you should generate unique UUIDs, in order to make sure incompatible third-party devices don't try to use your service thinking it is something else. The easiest way is to generate random ones and then hard-code the result in your application (and use the same UUIDs in the devices that will connect to your service, of course).

How to Call VBA Function from Excel Cells?

A Function will not work, nor is it necessary:

Sub OpenWorkbook()
    Dim r1 As Range, r2 As Range, o As Workbook
    Set r1 = ThisWorkbook.Sheets("Sheet1").Range("A1")
    Set o = Workbooks.Open(Filename:="C:\TestFolder\ABC.xlsx")
    Set r2 = ActiveWorkbook.Sheets("Sheet1").Range("B2")
    [r1] = [r2]
    o.Close
End Sub

How to delete SQLite database from Android programmatically

Once you have your Context and know the name of the database, use:

context.deleteDatabase(DATABASE_NAME);

When this line gets run, the database should be deleted.

Pytorch reshape tensor dimension

Use torch.unsqueeze(input, dim, out=None)

>>> import torch
>>> a = torch.Tensor([1,2,3,4,5])
>>> a

 1
 2
 3
 4
 5
[torch.FloatTensor of size 5]

>>> a = a.unsqueeze(0)
>>> a

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

Git: Create a branch from unstaged/uncommitted changes on master

If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.

enter image description here

background-image: url("images/plaid.jpg") no-repeat; wont show up

Try this:

body
{ 
    background:url("images/plaid.jpg") no-repeat fixed center;
}

jsfiddle example: http://jsfiddle.net/Q9Zfa/

compare differences between two tables in mysql

Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....

Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"

SELECT ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

So you need to add the extra "where in" clause:

WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)


Also:

For ease of reading if you want to indicate the table names you can use the following:

SELECT tbl, ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

Android Studio rendering problems

Change your android version on your designer preview into your current version depend on your Manifest. rendering problem caused your designer preview used higher API level than your current android API level.

Adjust with your current API Level

Adjust with your current API Level. If the API level isn't in the list, you'll need to install it via the SDK Manager.

IE8 support for CSS Media Query

The best solution I've found is Respond.js especially if your main concern is making sure your responsive design works in IE8. It's pretty lightweight at 1kb when min/gzipped and you can make sure only IE8 clients load it:

<!--[if lt IE 9]>
<script src="respond.min.js"></script>
<![endif]-->

It's also the recommended method if you're using bootstrap: http://getbootstrap.com/getting-started/#support-ie8-ie9

How to disable JavaScript in Chrome Developer Tools?

  • Go to options (Windows: three vertical dots in the top right) -> Settings, or hit F1.
  • In the General section you find "disable JavaScript"

The gear icon is no longer part of developer tools. Since Chome 30.0 it is not even possible to bring it back (In Google Chrome Developer Tools, the toolbar icons disappeared. What gives?)

How can I change the Java Runtime Version on Windows (7)?

I use to work on UNIX-like machines, but recently I have had to do some work with Java on a Windows 7 machine. I have had that problem and this is the I've solved it. It has worked right for me so I hope it can be used for whoever who may have this problem in the future.

These steps are exposed considering a default Java installation on drive C. You should change what it is necessary in case your installation is not a default one.

Change Java default VM on Windows 7

Suppose we have installed Java 8 but for whatever reason we want to keep with Java 7.

1- Start a cmd as administrator

2- Go to C:\ProgramData\Oracle\Java

3- Rename the current directory javapath to javapath_<version_it_refers_to>. E.g.: rename javapath javapath_1.8

4- Create a javapath_<version_you_want_by_default> directory. E.g.: mkdir javapath_1.7

5- cd into it and create the following links:

cd javapath_1.7
mklink java.exe "C:\Program Files\Java\jre7\bin\java.exe"
mklink javaw.exe "C:\Program Files\Java\jre7\bin\javaw.exe"
mklink javaws.exe "C:\Program Files\Java\jre7\bin\javaws.exe"

6- cd out and create a directory link javapath pointing to the desired javapath. E.g.: mklink /D javapath javapath_1.7

7- Open the register and change the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\CurrentVersion to have the value 1.7

At this point if you execute java -version you should see that you are using java version 1.7:

java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

8- Finally it is a good idea to create the environment variable JAVA_HOME. To do that I create a directory link named CurrentVersion in C:\Program Files\Java pointing to the Java version I'm interested in. E.g.:

cd C:\Program Files\Java\
mklink /D CurrentVersion .\jdk1.7.0_71

9- And once this is done:

  • Right click My Computer and select Properties.
  • On the Advanced tab, select Environment Variables, and then edit/create JAVA_HOME to point to where the JDK software is located, in that case, C:\Program Files\Java\CurrentVersion

IntelliJ how to zoom in / out

Update: This answer is old. Intellij has since added actions to adjust font size. Check out Wilker's answer for assigning the new actions to keymaps.

Try Ctrl+Mouse Wheel which can be enabled under File > Settings... > Editor > General : Change font size (Zoom) with Ctrl+Mouse Wheel

nginx showing blank PHP pages

replace

include fastcgi_params;

with

include fastcgi.conf;

and remove fastcgi_param SCRIPT_FILENAME ... in nginx.conf

How can you print a variable name in python?

With eager evaluation, variables essentially turn into their values any time you look at them (to paraphrase). That said, Python does have built-in namespaces. For example, locals() will return a dictionary mapping a function's variables' names to their values, and globals() does the same for a module. Thus:

for name, value in globals().items():
    if value is unknown_variable:
        ... do something with name

Note that you don't need to import anything to be able to access locals() and globals().

Also, if there are multiple aliases for a value, iterating through a namespace only finds the first one.

Error: «Could not load type MvcApplication»

[Extracted from question]

If you are getting this error: "Could not load type MvcApplication", look at the Output path of your project and make sure it is set to 'bin\'. The problem is that the AspNetCompiler cannot find the files if they are not in the default location.

Another side effect of changing the output folder is that you will not be able to debug your code and it comes up with a message saying that the Assembly info cannot be found.

Alter MySQL table to add comments on columns

As per the documentation you can add comments only at the time of creating table. So it is must to have table definition. One way to automate it using the script to read the definition and update your comments.

Reference:

http://cornempire.net/2010/04/15/add-comments-to-column-mysql/

http://bugs.mysql.com/bug.php?id=64439

Add php variable inside echo statement as href link address?

This worked much better in my case.

HTML in PHP: <a href=".$link_address.">Link</a>

Console app arguments, how arguments are passed to Main method

Every managed exe has a an entry point which can be seen when if you load your code to ILDASM. The Entry Point is specified in the CLR headed and would look something like this.

enter image description here

Checking for Undefined In React

You can check undefined object using below code.

ReactObject === 'undefined'

Get Enum from Description attribute

Should be pretty straightforward, its just the reverse of your previous method;

public static int GetEnumFromDescription(string description, Type enumType)
{
    foreach (var field in enumType.GetFields())
    {
        DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
        if(attribute == null)
            continue;
        if(attribute.Description == description)
        {
            return (int) field.GetValue(null);
        }
    }
    return 0;
}

Usage:

Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

Pause Console in C++ program

Late response, but I think it will help others.

Part of imitating system("pause") is imitating what it asks the user to do: "Press any key to continue . . . " So, we need something that does not wait for simply a return as std::cin.get() would do. Even getch() has its problems when used twice (the second time call has been noticed to skip pausing generally if it's immediately paused again afterwards on the same key press). I think it has to do with the input buffer. System("pause") is usually not recommended, but we still need something to imitate what users might already expect. I prefer getch() because it doesn't echo to the screen, and it works dynamically.

The solution is to do the following using a do-while loop:

void Console::pause()
{ 
    int ch = 0;

    std::cout << "\nPress any key to continue . . . ";

    do {
        ch = getch();
    } while (ch != 0);

    std::cout << std::endl;
} 

Now it waits for the user to press any key. If it's used twice, it waits for the user again instead of skipping.

Can I embed a custom font in an iPhone application?

I have been trying out the various suggestions on this page on iOS 3.1.2 and these are my conclusions:

Simply using [UIFont fontWithName:size:] with the fonts in the Resources directory will not work, even if the FOND name is set using FontForge.

[UIFont fontWithName:size:] will work if the fonts are loaded first using GSFontAddFromFile. But GSFontAddFromFile is not part of iOS 3.1.2 so it has to be dynamically loaded as described by @rpetrich.

Count cells that contain any text

You can pass "<>" (including the quotes) as the parameter for criteria. This basically says, as long as its not empty/blank, count it. I believe this is what you want.

=COUNTIF(A1:A10, "<>") 

Otherwise you can use CountA as Scott suggests

How to fix corrupted git repository?

As an alternative to CodeGnome's last option, if only the local repo is corrupted, and you know the url to the remote, you can use this to re-set your .git to match the remote (replacing ${url} with the remote url):

mv -v .git .git_old &&            # remove old git
git init &&                       # initialise new repo
git remote add origin "${url}" && # link to old repo
git fetch &&                      # get old history
git reset origin/master --mixed   # force update to old history

This leaves your working tree intact, and only affects git's bookkeeping.
I also recently made a bash script for this very purpose (Appendix A), which wraps a bit of safety around this operation.

Note:

If your repo has submodules, this process will mess them up somehow, and the only solution I've found so far is deleting them and then using git submodule update --init (or re-cloning the repo, but that seems too drastic).

Appendix A - Full script

#!/bin/bash

# Author: Zoey Llewellyn "Zobean" Hewll
#
# Usage: fix-git [REMOTE-URL]
#   Must be run from the root directory of the repository.
#   If a remote is not supplied, it will be read from .git/config
# 
# For when you have a corrupted local repo, but a trusted remote.
# This script replaces all your history with that of the remote.
# If there is a .git, it is backed up as .git_old, removing the last backup.
# This does not affect your working tree.
#
# This does not currently work with submodules!
# This will abort if a suspected submodule is found.
# You will have to delete them first
# and re-clone them after (with `git submodule update --init`)
#
# Error codes:
# 1: If a url is not supplied, and one cannot be read from .git/config
# 4: If the url cannot be reached
# 5: If a git submodule is detected


if [[ "$(find -name .git -not -path ./.git | wc -l)" -gt 0 ]] ;
then
    echo "It looks like this repo uses submodules" >&2
    echo "You will need to remove them before this script can safely execute" >&2
    echo "Then use \`git submodule update --init\` to re-clone them" >&2
    exit 5
fi

if [[ $# -ge 1 ]] ;
then
    url="$1"
else
    if ! url="$(git config --local --get remote.origin.url)" ;
    then
        echo "Unable to find remote 'origin': missing in '.git/config'" >&2
        exit 1
    fi
fi
url_base="$(echo "${url}" | sed -E 's;^([^/]*://)?([^/]*)(/.*)?$;\2;')"
echo "Attempting to access ${url_base} before continuing"
if ! wget -p "${url_base}" -O /dev/null -q --dns-timeout=5 --connect-timeout=5 ;
then
    echo "Unable to reach ${url_base}: Aborting before any damage is done" >&2
    exit 4
fi

echo
echo "This operation will replace the local repo with the remote at:"
echo "${url}"
echo
echo "This will completely rewrite history,"
echo "but will leave your working tree intact"
echo -n "Are you sure? (y/N): "

read confirm
if ! [ -t 0 ] ; # i'm open in a pipe
then
    # print the piped input
    echo "${confirm}"
fi
if echo "${confirm}"|grep -Eq "[Yy]+[EeSs]*" ; # it looks like a yes
then
    if [[ -e .git ]] ;
    then
        # remove old backup
        rm -vrf .git_old | tail -n 1 &&
        # backup .git iff it exists
        mv -v .git .git_old
    fi &&
    git init &&
    git remote add origin "${url}" &&
    git config --local --get remote.origin.url | sed 's/^/Added remote origin at /' &&
    git fetch &&
    git reset origin/master --mixed
else
    echo "Aborting without doing anything"
fi

Counting number of occurrences in column?

A simpler approach to this

At the beginning of column B, type

=UNIQUE(A:A)

Then in column C, use

=COUNTIF(A:A, B1)

and copy them in all row column C.

Edit: If that doesn't work for you, try using semicolon instead of comma:

=COUNTIF(A:A; B1)

Version vs build in Xcode

(Just leaving this here for my own reference.) This will show version and build for the "version" and "build" fields you see in an Xcode target:

- (NSString*) version {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

In Swift

func version() -> String {
    let dictionary = NSBundle.mainBundle().infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as? String
    let build = dictionary["CFBundleVersion"] as? String
    return "\(version) build \(build)"
}

Change value of input and submit form in JavaScript

This might help you.

Your HTML

<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>

Your Script

    <script>
        function save(){
            $('#myinput').val('1');
            $('#form').submit();
        }
    </script>

How can I force clients to refresh JavaScript files?

Below worked for me:

<head>
<meta charset="UTF-8">
<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
</head>

Check if value is zero or not null in python

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

sorting and paging with gridview asp.net

I found a much easier way, which allows you to still use the built in sorting/paging of the standard gridview...

create 2 labels. set them to be visible = false. I called mine lblSort1 and lblSortDirection1

then code 2 simple events... the page sorting, which writes to the text of the invisible labels, and the page index changing, which uses them...

Private Sub gridview_Sorting(sender As Object, e As GridViewSortEventArgs) Handles gridview.Sorting
lblSort1.Text = e.SortExpression
lblSortDirection1.Text = e.SortDirection
End Sub

Private Sub gridview_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles gridview.PageIndexChanging
    gridview.Sort(lblSort1.Text, CInt(lblSortDirection1.Text))
End Sub

this is a little sloppier than using global variables, but I've found with asp especially that global vars are, well, unreliable...

Difference between 2 dates in seconds

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

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

Play audio from a stream using C#

Edit: Answer updated to reflect changes in recent versions of NAudio

It's possible using the NAudio open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the MP3Frame and AcmMp3FrameDecompressor classes in NAudio to decompress streamed MP3 on the fly.

I have posted an article on my blog explaining how to play back an MP3 stream using NAudio. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a BufferedWaveProvider. Another thread then plays back using the BufferedWaveProvider as an input.

How do I create a slug in Django?

You can look at the docs for the SlugField to get to know more about it in more descriptive way.

Does Go have "if x in" construct similar to Python?

Just had similar question and decided to try out some of the suggestions in this thread.

I've benchmarked best and worst case scenarios of 3 types of lookup:

  • using a map
  • using a list
  • using a switch statement

here's the function code:

func belongsToMap(lookup string) bool {
list := map[string]bool{
    "900898296857": true,
    "900898302052": true,
    "900898296492": true,
    "900898296850": true,
    "900898296703": true,
    "900898296633": true,
    "900898296613": true,
    "900898296615": true,
    "900898296620": true,
    "900898296636": true,
}
if _, ok := list[lookup]; ok {
    return true
} else {
    return false
}
}


func belongsToList(lookup string) bool {
list := []string{
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636",
}
for _, val := range list {
    if val == lookup {
        return true
    }
}
return false
}

func belongsToSwitch(lookup string) bool {
switch lookup {
case
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636":
    return true
}
return false
}

best case scenarios pick the first item in lists, worst case ones use nonexistant value.

here are the results:

BenchmarkBelongsToMapWorstCase-4 2000000 787 ns/op BenchmarkBelongsToSwitchWorstCase-4 2000000000 0.35 ns/op BenchmarkBelongsToListWorstCase-4 100000000 14.7 ns/op BenchmarkBelongsToMapBestCase-4 2000000 683 ns/op BenchmarkBelongsToSwitchBestCase-4 100000000 10.6 ns/op BenchmarkBelongsToListBestCase-4 100000000 10.4 ns/op

Switch wins all the way, worst case is surpassingly quicker than best case. Maps are the worst and list is closer to switch.

So the moral is: If you have a static, reasonably small list, switch statement is the way to go.

How can I access an internal class from an external assembly?

Reflection.

using System.Reflection;

Vendor vendor = new Vendor();
object tag = vendor.Tag;

Type tagt = tag.GetType();
FieldInfo field = tagt.GetField("test");

string value = field.GetValue(tag);

Use the power wisely. Don't forget error checking. :)

How can I create an editable combo box in HTML/Javascript?

try doing this

<div style="position: absolute;top: 32px; left: 430px;" id="outerFilterDiv">
<input name="filterTextField" type="text" id="filterTextField" tabindex="2"  style="width: 140px;
    position: absolute; top: 1px; left: 1px; z-index: 2;border:none;" />
        <div style="position: absolute;" id="filterDropdownDiv">
<select name="filterDropDown" id="filterDropDown" tabindex="1000"
    onchange="DropDownTextToBox(this,'filterTextField');" style="position: absolute;
    top: 0px; left: 0px; z-index: 1; width: 165px;">
    <option value="-1" selected="selected" disabled="disabled">-- Select Column Name --</option>
</select>

please look at following example fiddle

Get the list of stored procedures created and / or modified on a particular date?

For SQL Server 2012:

SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%' 
ORDER BY modify_date desc

How large is a DWORD with 32- and 64-bit code?

It is defined as:

typedef unsigned long       DWORD;

However, according to the MSDN:

On 32-bit platforms, long is synonymous with int.

Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:

typdef unsigned _int64 DWORD64;

Hope that helps.

How do I toggle an element's class in pure JavaScript?

Here is a code for IE >= 9 by using split(" ") on the className :

function toggleClass(element, className) {
    var arrayClass = element.className.split(" ");
    var index = arrayClass.indexOf(className);

    if (index === -1) {
        if (element.className !== "") {
            element.className += ' '
        }
        element.className += className;
    } else {
        arrayClass.splice(index, 1);
        element.className = "";
        for (var i = 0; i < arrayClass.length; i++) {
            element.className += arrayClass[i];
            if (i < arrayClass.length - 1) {
                element.className += " ";
            }
        }
    }
}

How do I check the operating system in Python?

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.system function uses uname internally.

How to set width and height dynamically using jQuery

As @Misha Moroshko has already posted himself, this works:

$("#mainTable").css("width", 100);
$("#mainTable").css("height", 200);

There's some advantage to this technique over @Nick Craver's accepted answer - you can also specifiy different units:

$("#mainTable").css("width", "100%");

So @Nick Craver's method might actually be the wrong choice for some users. From the jquery API (http://api.jquery.com/width/):

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

Python slice first and last element in list

These are all interesting but what if you have a version number and you don't know the size of any one segment in string from and you want to drop the last segment. Something like 20.0.1.300 and I want to end up with 20.0.1 without the 300 on the end. I have this so far:

str('20.0.1.300'.split('.')[:3])

which returns in list form as:

['20', '0', '1']

How do I get it back to into a single string separated by periods

20.0.1

Read a file in Node.js

Use path.join(__dirname, '/start.html');

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (!err) {
        console.log('received data: ' + data);
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    } else {
        console.log(err);
    }
});

Thanks to dc5.

What does "var" mean in C#?

It declares a type based on what is assigned to it in the initialisation.

A simple example is that the code:

var i = 53;

Will examine the type of 53, and essentially rewrite this as:

int i = 53;

Note that while we can have:

long i = 53;

This won't happen with var. Though it can with:

var i = 53l; // i is now a long

Similarly:

var i = null; // not allowed as type can't be inferred.
var j = (string) null; // allowed as the expression (string) null has both type and value.

This can be a minor convenience with complicated types. It is more important with anonymous types:

var i = from x in SomeSource where x.Name.Length > 3 select new {x.ID, x.Name};
foreach(var j in i)
  Console.WriteLine(j.ID.ToString() + ":" + j.Name);

Here there is no other way of defining i and j than using var as there is no name for the types that they hold.

How do I make a transparent canvas in html5?

Canvases are transparent by default.

Try setting a page background image, and then put a canvas over it. If nothing is drawn on the canvas, you can fully see the page background.

Think of a canvas as like painting on a glass plate.

How to sort in-place using the merge sort algorithm?

There is a relatively simple implementation of in-place merge sort using Kronrod's original technique but with simpler implementation. A pictorial example that illustrates this technique can be found here: http://www.logiccoder.com/TheSortProblem/BestMergeInfo.htm.

There are also links to more detailed theoretical analysis by the same author associated with this link.

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

What is the best way to search the Long datatype within an Oracle database?

You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.

Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Private properties in JavaScript ES6 classes

Coming very late to this party but I hit the OP question in a search so... Yes, you can have private properties by wrapping the class declaration in a closure

There is an example of how I have private methods in this codepen. In the snippet below, the Subscribable class has two 'private' functions process and processCallbacks. Any properties can be added in this manner and they are kept private through the use of the closure. IMO Privacy is a rare need if concerns are well separated and Javascript does not need to become bloated by adding more syntax when a closure neatly does the job.

const Subscribable = (function(){

  const process = (self, eventName, args) => {
    self.processing.set(eventName, setTimeout(() => processCallbacks(self, eventName, args)))};

  const processCallbacks = (self, eventName, args) => {
    if (self.callingBack.get(eventName).length > 0){
      const [nextCallback, ...callingBack] = self.callingBack.get(eventName);
      self.callingBack.set(eventName, callingBack);
      process(self, eventName, args);
      nextCallback(...args)}
    else {
      delete self.processing.delete(eventName)}};

  return class {
    constructor(){
      this.callingBack = new Map();
      this.processing = new Map();
      this.toCallbacks = new Map()}

    subscribe(eventName, callback){
      const callbacks = this.unsubscribe(eventName, callback);
      this.toCallbacks.set(eventName,  [...callbacks, callback]);
      return () => this.unsubscribe(eventName, callback)}  // callable to unsubscribe for convenience

    unsubscribe(eventName, callback){
      let callbacks = this.toCallbacks.get(eventName) || [];
      callbacks = callbacks.filter(subscribedCallback => subscribedCallback !== callback);
      if (callbacks.length > 0) {
        this.toCallbacks.set(eventName, callbacks)}
      else {
        this.toCallbacks.delete(eventName)}
      return callbacks}

    emit(eventName, ...args){
      this.callingBack.set(eventName, this.toCallbacks.get(eventName) || []);
      if (!this.processing.has(eventName)){
        process(this, eventName, args)}}}})();

I like this approach because it separates concerns nicely and keeps things truly private. The only downside is the need to use 'self' (or something similar) to refer to 'this' in the private content.

Python division

In Python 2.7, the / operator is an integer division if inputs are integers:

>>>20/15
1

>>>20.0/15.0
1.33333333333

>>>20.0/15
1.33333333333

In Python 3.3, the / operator is a float division even if the inputs are integer.

>>> 20/15
1.33333333333

>>>20.0/15
1.33333333333

For integer division in Python 3, we will use the // operator.

The // operator is an integer division operator in both Python 2.7 and Python 3.3.

In Python 2.7 and Python 3.3:

>>>20//15
1

Now, see the comparison

>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b

For the above program, the output will be False in Python 2.7 and True in Python 3.3.

In Python 2.7 a = 1.75 and b = 1.

In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

How to add a class to body tag?

You can extract that part of the URL using a simple regular expression:

var url = location.href;
var className = url.match(/\w+\/(\w+)_/)[1];
$('body').addClass(className);

How do I load a PHP file into a variable?

If you want to load the file without running it through the webserver, the following should work.

$string = eval(file_get_contents("file.php"));

This will load then evaluate the file contents. The PHP file will need to be fully formed with <?php and ?> tags for eval to evaluate it.

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

SET JAVA_HOME=C:\Program Files\Java\jdk1.8.0

worked fine for me.

Note - Don't put double quotes over the path as mentioned above. Otherwise when you run

mvn -version

it will give following error

Files\java\jdk1.8.0_201\jre""=="" was unexpected at this time.

Rotate camera in Three.js with mouse

Take a look at THREE.PointerLockControls

How to test if a double is zero?

Numeric primitives in class scope are initialized to zero when not explicitly initialized.

Numeric primitives in local scope (variables in methods) must be explicitly initialized.

If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

if(value != 0)
    //divide by value is safe when value is not exactly zero.

Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

public boolean isZero(double value, double threshold){
    return value >= -threshold && value <= threshold;
}

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

Converting std::__cxx11::string to std::string

When I had similar issue it's happened because my lib was build using clang++, and it's linked to libstdc++.so by default on my system. While app binary was build using clang and linked with -lc++ option.

Easiest way to check dependencies is to perform ldd libName.so

To fix it you should use the same library on in app and library.

  • Easiest way. Build library using clang++ and compile app using clang++. Without extra linking options on both steps. Default stdlib will be used.

  • Build library with -stdlib=c++ and compile app with -lc++. In this case both library and app will use libc++.so.

  • Build library without extra options and link binary to -lstdc++. In this case both library and app will use libstdc++.so.

How disable / remove android activity label and label bar?

you can try this

 ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

Make: how to continue after a command fails?

Put an -f option in your rm command.

rm -f .lambda .lambda_t .activity .activity_t_lambda

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

As others pointed out, this message is coming from your shell prompt. The problem is that in a freshly created repository HEAD (.git/HEAD) points to a ref that doesn't exist yet.

% git init test
Initialized empty shared Git repository in /Users/jhelwig/tmp/test/.git/
% cd test
% cat .git/HEAD
ref: refs/heads/master
% ls -l .git/refs/heads
total 0
% git rev-parse HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

It looks like rev-parse is being used without sufficient error checking before-hand. After the first commit has been created .git/refs/heads looks a bit different and git rev-parse HEAD will no longer fail.

% ls -l .git/refs/heads
total 4
-rw------- 1 jhelwig staff 41 Oct 14 16:07 master
% git rev-parse HEAD
af0f70f8962f8b88eef679a1854991cb0f337f89

In the function that updates the Git information for the rest of my shell prompt (heavily modified version of wunjo prompt theme for ZSH), I have the following to get around this:

zgit_info_update() {
    zgit_info=()

    local gitdir=$(git rev-parse --git-dir 2>/dev/null)
    if [ $? -ne 0 ] || [ -z "$gitdir" ]; then
        return
    fi

    # More code ...
}

How to update specific key's value in an associative array in PHP?

This will work too!

foreach($data as &$value) {
  $value['transaction_date'] = date('d/m/Y', $value['transaction_date']);
}

Yay for alternatives!

In Android, how do I set margins in dp programmatically?

Best way ever:

private void setMargins (View view, int left, int top, int right, int bottom) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        p.setMargins(left, top, right, bottom);
        view.requestLayout();
    }
}

How to call method:

setMargins(mImageView, 50, 50, 50, 50);

Hope this will help you.

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

Structure padding and packing

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system) or larger. Data alignment means putting the data at a memory address equal to some multiple of the word size, which increases the system’s performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

  1. In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left empty) between memory addresses which are allocated for other structure members while memory allocation. This concept is called structure padding.
  2. Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.
  3. To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.
  4. Because of this structure padding concept in C, size of the structure is always not same as what we think.

Selecting all text in HTML text input when clicked

Use "placeholder" instead of "value" in your input field.

How to call one shell script from another shell script?

Use backticks.

$ ./script-that-consumes-argument.sh `sh script-that-produces-argument.sh`

Then fetch the output of the producer script as an argument on the consumer script.

Spring get current ApplicationContext

Another way is to inject applicationContext through servlet.

This is an example of how to inject dependencies when using Spring web services.

<servlet>
        <servlet-name>my-soap-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:my-applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>5</load-on-startup>

</servlet>

Alternate way is to add application Context in your web.xml as shown below

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/classes/my-another-applicationContext.xml
        classpath:my-second-context.xml
    </param-value>
</context-param>

Basically you are trying to tell servlet that it should look for beans defined in these context files.

Folder structure for a Node.js project

It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.

I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.

So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.

It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.

How do you do block comments in YAML?

In .gitlab-ci.yml file following works::

To comment out a block (multiline): Select the whole block section > Ctrl K C

To uncomment already commented out block (multiline): Select the whole block section > Ctrl K U

iOS change navigation bar title font and color

Anyone needs a Swift 3 version. redColor() has changed to just red.

self.navigationController?.navigationBar.titleTextAttributes =
        [NSForegroundColorAttributeName: UIColor.red,
         NSFontAttributeName: UIFont(name: "{your-font-name}", size: 21)!]

getting error while updating Composer

Your error message is pretty explicit about what is going wrong:

laravel/framework v5.2.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.

Do you have mbstring installed on your server and is it enabled?

You can install mbstring as part of the libapache2-mod-php5 package:

sudo apt-get install libapache2-mod-php5

Or standalone with:

sudo apt-get install php-mbstring

Installing it will also enable it, however you can also enable it by editing your php.ini file and remove the ; that is commenting it out if it is already installed.

If this is on your local machine, then follow the appropriate steps to install this on your environment.

Infinite Recursion with Jackson JSON and Hibernate JPA issue

The point is to place the @JsonIgnore in the setter method as follow. in my case.

Township.java

@Access(AccessType.PROPERTY)
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="townshipId", nullable=false ,insertable=false, updatable=false)
public List<Village> getVillages() {
    return villages;
}

@JsonIgnore
@Access(AccessType.PROPERTY)
public void setVillages(List<Village> villages) {
    this.villages = villages;
}

Village.java

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "townshipId", insertable=false, updatable=false)
Township township;

@Column(name = "townshipId", nullable=false)
Long townshipId;

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

A hex viewer / editor plugin for Notepad++?

According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.

Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

As for every "3rd-party" library in flavor of a JAR file which is to be used by the webapp, just copy/drop the physical JAR file in webapp's /WEB-INF/lib. It will then be available in webapp's default classpath. Also, Eclipse is smart enough to notice that. No need to hassle with buildpath. However, make sure to remove all unnecessary references you added before, else it might collide.

An alternative is to install it in the server itself by dropping the physical JAR file in server's own /lib folder. This is required when you're using server-provided JDBC connection pool data source which in turn needs the MySQL JDBC driver.

See also:

Laravel Soft Delete posts

Here is the details from laravel.com

http://laravel.com/docs/eloquent#soft-deleting

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model:

class User extends Eloquent {

    protected $softDelete = true;

}

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

$table->softDeletes();

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results.

How to add certificate chain to keystore?

I solved the problem by cat'ing all the pems together:

cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD

(keytool didn't know what to do with a PKCS7 formatted key)

I got all the pems from letsencrypt

Remove blue border from css custom-styled button in Chrome

If you want to delete same effect in input, you could add the following code as well as button.

input:focus {outline:0;}

Simplest way to throw an error/exception with a custom message in Swift 2?

In case you don't need to catch the error and you want to immediately stop the application you can use a fatalError: fatalError ("Custom message here")

How to un-commit last un-pushed git commit without losing the changes

For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.

  1. Go to Version control window (Alt + 9/Command + 9) - "Log" tab.
  2. Right-click on a commit before your last one.
  3. Reset current branch to here
  4. pick Soft (!!!)
  5. push the Reset button in the bottom of the dialog window.

Done.

This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.

Android Use Done button on Keyboard to click button

Kotlin and Numeric keyboard

If you are using the numeric keyboard you have to dismiss the keyboard, it will be like:

editText.setOnEditorActionListener { v, actionId, event ->
  if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_NEXT || action == EditorInfo.IME_ACTION_UNSPECIFIED) {
      //hide the keyboard
      val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
      imm.hideSoftInputFromWindow(windowToken, 0)
      //Take action
      editValue.clearFocus()
      return true
  } else {
      return false
  }
}

How to link an image and target a new window

To open in a new tab use:

target = "_blank"

To open in the same tab use:

target = "_self"

The data-toggle attributes in Twitter Bootstrap

Any attribute that starts with data- is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel and other attributes for purposes other than their original intended purposes (rel was often used to hold data for things like advanced tooltips).

In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).

html5doctor has a good article on the data- attribute.

Cycle 2 is another example of extensive use of the data- attribute.

How do I get the value of a textbox using jQuery?

Per Jquery docs

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

In order to retrieve the value store in the text box with id txtEmail, you can use

$("#txtEmail").val()

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

Rails formatting date

Create an initializer for it:

# config/initializers/time_formats.rb

Add something like this to it:

Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"

And then use it the following way:

post.updated_at.to_s(:custom_datetime)

?? Your have to restart rails server for this to work.

Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s

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

In ASP.NET Core you should rather use Environment Variables instead of build configuration for proper appsettings.json

  1. Right click on you project > Properties > Debug > Environment Variables

    environment variables

  2. ASP.NET Core will use the appropriate appsettings.json file:

    example of appsettings files in solution explorer

  3. Now you can use that Environment Variable like this:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
    
        Configuration = builder.Build();
    }
    

Note: If you use @Dmitry's answer, you can run into problems eg. when overriding appsettings.json values on Azure.

Configure apache to listen on port other than 80

Open httpd.conf file in your text editor. Find this line:

Listen 80

and change it

Listen 8079

After change, save it and restart apache.

tSQL - Conversion from varchar to numeric works for all but integer

SELECT
  convert(numeric(18,5),Col1), Col2
     FROM DBname.dbo.TableName
         WHERE isnumeric(isnull(Col1,1)) <> 0

Drop default constraint on a column in TSQL

This is how you would drop the constraint

ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
   DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO

With a script

-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)

set @database = 'dotnetnuke'
set @table = 'tabs'

DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
    select    @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME 
    from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
    where    constraint_catalog = @database and 
            table_name = @table
    exec    sp_executesql @sql
END

Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx

How to set character limit on the_content() and the_excerpt() in wordpress

Or even easier and without the need to create a filter: use PHP's mb_strimwidth to truncate a string to a certain width (length). Just make sure you use one of the get_ syntaxes. For example with the content:

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>

This will cut the string at 400 characters and close it with .... Just add a "read more"-link to the end by pointing to the permalink with get_permalink().

<a href="<?php the_permalink() ?>">Read more </a>

Of course you could also build the read more in the first line. Than just replace '...' with '<a href="' . get_permalink() . '">[Read more]</a>'

Select multiple columns using Entity Framework

You can select to an anonymous type, for example

var dataset2 = 
    (from recordset in entities.processlists 
    where recordset.ProcessName == processname 
    select new
    {
        serverName = recordset.ServerName,
        processId = recordset.ProcessID, 
        username = recordset.Username
    }).ToList();

Or you can create a new class that will represent your selection, for example

public class MyDataSet
{
    public string ServerName { get; set; }
    public string ProcessId { get; set; }
    public string Username { get; set; }
}

then you can for example do the following

 var dataset2 = 
    (from recordset in entities.processlists 
    where recordset.ProcessName == processname 
    select new MyDataSet
    {
        ServerName = recordset.ServerName,
        ProcessId = recordset.ProcessID, 
        Username = recordset.Username
    }).ToList();

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command line using

D:\>xcopy myfile.dat xcopytest\test\

and the target directory was properly created.

If not you can create the target dir using the mkdir command with cmd's command extensions enabled like

cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"

('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd)

use

cmd /? 
mkdir /?
xcopy /?

for further information :)

GLYPHICONS - bootstrap icon font hex value

The hex values are on the mainpage of http://glyphicons.com/ in the tooltips of the specific icon.

git reset --hard HEAD leaves untracked files behind

Remove all things except .git folder and then run git reset --hard

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

How to read numbers separated by space using scanf

It should be as simple as using a list of receiving variables:

scanf("%i %i %i", &var1, &var2, &var3);

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

Why does the Visual Studio editor show dots in blank spaces?

I had the same problem and resolved by pressing Ctrl + R , Ctrl + W.

Getting the application's directory from a WPF application

Here is another:

System.Reflection.Assembly.GetExecutingAssembly().Location

DELETE ... FROM ... WHERE ... IN

You can achieve this using exists:

DELETE
  FROM table1
 WHERE exists(
           SELECT 1
             FROM table2
            WHERE table2.stn = table1.stn
              and table2.jaar = year(table1.datum)
       )

Manually put files to Android emulator SD card

In Visual Studio 2019 (Xamarin):

  1. Click on the Device Monitor (DDMS) button.

enter image description here

  1. Go to the File Explorer tab and click the button with a phone and a right-pointing arrow on top of it.

enter image description here

writing to existing workbook using xlwt

I had the same problem. My customer ordered me Python 3.4 script that updates XLS (not XLSX) Excel files.

The 1st package xlrd was installed by "pip install" without problems in my Python home.

The 2nd one xlwt needed to say "pip install xlwt-future" to be compatible.

The 3rd one xlutils has no support for Python 3, but I adapted it a little bit and now it works at least for dummy script:

#!C:\Python343\python
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt

file_path = 'C:\Dev\Test_upd.xls'
rb = open_workbook('C:\Dev\Test.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
w_sheet.write(1, 1, 'Value')
wb.save(file_path)

I attached the file here: http://ifolder.su/43507580

Write to [email protected] if it got expired.

P.S.: Some functions are not called in the dummy example, so maybe they will need for an adaptation also. Who wants to do it, fix exceptions one-by-one with a google help. It's not a very difficult task, because the package code is small...

How to prevent long words from breaking my div?

Yeah, if it is possible, setting an absolute width and setting overflow : auto works well.

Convert to date format dd/mm/yyyy

$source    =    'your varible name';
$date    =     new DateTime($source);
$_REQUEST["date"]    =     $date->format('d-m-Y');

echo $_REQUEST["date"];

How to Bootstrap navbar static to fixed on scroll?

Here's a solution using Bootstrap's affix plugin:

HTML:

<header class="container-fluid">
    ...
</header>
<nav class="navbar navbar-default navbar-static-top" role="navigation">
    ...
</nav>

Javascript:

$('nav').affix({
      offset: {
        top: $('header').height()
      }
});

Set padding-top to your body equal to that of your nav's height so that the content overlayed by the fixed navbar is visible.

$('nav').on('affix.bs.affix', function (){
     $('body').css('margin-top', $('nav').height());
});

$('nav').on('affix-top.bs.affix', function (){
     $('body').css('margin-top', 0);
});

To get the nav to stick on top while scrolling add this bit of CSS.

CSS:

.affix
{
    top: 0;
}

How can I shrink the drawable on a button?

My DiplayScaleHelper, that works perfectly:

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ScaleDrawable;
import android.widget.Button;

public class DisplayHelper {

  public static void scaleButtonDrawables(Button btn, double fitFactor) {
        Drawable[] drawables = btn.getCompoundDrawables();

        for (int i = 0; i < drawables.length; i++) {
            if (drawables[i] != null) {
                if (drawables[i] instanceof ScaleDrawable) {
                    drawables[i].setLevel(1);
                }
                drawables[i].setBounds(0, 0, (int) (drawables[i].getIntrinsicWidth() * fitFactor),
                    (int) (drawables[i].getIntrinsicHeight() * fitFactor));
                ScaleDrawable sd = new ScaleDrawable(drawables[i], 0, drawables[i].getIntrinsicWidth(), drawables[i].getIntrinsicHeight());
                if(i == 0) {
                    btn.setCompoundDrawables(sd.getDrawable(), drawables[1], drawables[2], drawables[3]);
                } else if(i == 1) {
                    btn.setCompoundDrawables(drawables[0], sd.getDrawable(), drawables[2], drawables[3]);
                } else if(i == 2) {
                    btn.setCompoundDrawables(drawables[0], drawables[1], sd.getDrawable(), drawables[3]);
                } else {
                    btn.setCompoundDrawables(drawables[0], drawables[1], drawables[2], sd.getDrawable());
                }
            }
        }
    }
}

Is there such a thing as min-font-size and max-font-size?

Rucksack is brilliant, but you don't necessarily have to resort to build tools like Gulp or Grunt etc.

I made a demo using CSS Custom Properties (CSS Variables) to easily control the min and max font sizes.

Like so:

* {
  /* Calculation */
  --diff: calc(var(--max-size) - var(--min-size));
  --responsive: calc((var(--min-size) * 1px) + var(--diff) * ((100vw - 420px) / (1200 - 420))); /* Ranges from 421px to 1199px */
}

h1 {
  --max-size: 50;
  --min-size: 25;
  font-size: var(--responsive);
}

h2 {
  --max-size: 40;
  --min-size: 20;
  font-size: var(--responsive);
}

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

Filter array to have unique values

You can use Array.filter function to filter out elements of an array based on the return value of a callback function. The callback function runs for every element of the original array.

The logic for the callback function here is that if the indexOf value for current item is same as the index, it means the element has been encountered first time, so it can be considered unique. If not, it means the element has been encountered already, so should be discarded now.

_x000D_
_x000D_
var arr = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"];_x000D_
_x000D_
var filteredArray = arr.filter(function(item, pos){_x000D_
  return arr.indexOf(item)== pos; _x000D_
});_x000D_
_x000D_
console.log( filteredArray );
_x000D_
_x000D_
_x000D_

Caveat: As pointed out by rob in the comments, this method should be avoided with very large arrays as it runs in O(N^2).

UPDATE (16 Nov 2017)

If you can rely on ES6 features, then you can use Set object and Spread operator to create a unique array from a given array, as already specified in @Travis Heeter's answer below:

var uniqueArray = [...new Set(array)]

How to set the environmental variable LD_LIBRARY_PATH in linux

You could try adding a custom script, say myenv_vars.sh in /etc/profile.d.

cd /etc/profile.d
sudo touch myenv_vars.sh
sudo gedit myenv_vars.sh

Add this to the empty file, and save it.

export LD_LIBRARY_PATH=/usr/local/lib

Logout and login, LD_LIBRARY_PATH will have been set permanently.

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

rbenv not changing ruby version

Check that PATH contains $HOME/.rbenv/shims and $HOME/.rbenv/bin

$ env | grep PATH

Also check that you have the following in your ~/.bash_profile if using bash or ~/.zshenv if using zsh

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

NOTE: Make sure it's the last setting in your ~/.bash_profile . I ran into an issue where I installed a program that updated my .bash_profile and reset PATH.

Finally, make sure your $HOME folder doesn't have a .ruby-version file that you may have created by accident if you were to have done $ rbenv local <ruby-version> in your $HOME folder. Doing $ rbenv global <ruby-version> modifies the $HOME/.rbenv/version file, and the existence of a .ruby-version file in the $HOME folder would override the version set by $HOME/.rbenv/version.

From the docs:

Choosing the Ruby Version When you execute a shim, rbenv determines which Ruby version to use by reading it from the following sources, in this order:

The RBENV_VERSION environment variable, if specified. You can use the rbenv shell command to set this environment variable in your current shell session.

The first .ruby-version file found by searching the directory of the script you are executing and each of its parent directories until reaching the root of your filesystem.

The first .ruby-version file found by searching the current working directory and each of its parent directories until reaching the root of your filesystem. You can modify the .ruby-version file in the current working directory with the rbenv local command.

The global ~/.rbenv/version file. You can modify this file using the rbenv global command. If the global version file is not present, rbenv assumes you want to use the "system" Ruby—i.e. whatever version would be run if rbenv weren't in your path.

Animate element to auto height with jQuery

I needed this functionality for multiple read more area's on one page implementing this into a Wordpress shortcode I ran into the same problem.

Design technically all of the read more span's on the page have a fixed height. And I wanted to be able to expand them separately to an auto height with a toggle. First click: 'expand to full height of text span', second click: 'collapse back to default height of 70px'

Html

 <span class="read-more" data-base="70" data-height="null">
     /* Lots of text determining the height of this span */
 </span>
 <button data-target='read-more'>Read more</button>

CSS

span.read-more {
    position:relative;
    display:block;
    overflow:hidden;
}

So above this looks very simple the data-base attribute I need to set the fixed height needed. The data-height attribute I used to store the actual (dynamic) height of the element.

The jQuery part

jQuery(document).ready(function($){

  $.fn.clickToggle = function(func1, func2) {
      var funcs = [func1, func2];
      this.data('toggleclicked', 0);
      this.click(function() {
          var data = $(this).data();
          var tc = data.toggleclicked;
          $.proxy(funcs[tc], this)();
          data.toggleclicked = (tc + 1) % 2;
      });
      return this;
  };

    function setAttr_height(key) {
        $(key).each(function(){
            var setNormalHeight = $(this).height();
            $(this).attr('data-height', setNormalHeight);
            $(this).css('height', $(this).attr('data-base') + 'px' );
        });
    }
    setAttr_height('.read-more');

    $('[data-target]').clickToggle(function(){
        $(this).prev().animate({height: $(this).prev().attr('data-height')}, 200);
    }, function(){
        $(this).prev().animate({height: $(this).prev().attr('data-base')}, 200);
    });

});

First I've used a clickToggle function for my first and second click. The second function is more important: setAttr_height() All of the .read-more elements have their actual heights set on page load in the base-height attribute. After that the base height is set through the jquery css function.

With both of our attributes set we now can toggle between them in a smooth way. Only chang the data-base to your desired (fixed)height and switch the .read-more class for your own ID

You can all see it working in a fiddle FIDDLE

No jQuery UI needed

What resources are shared between threads?

Thread share the heap (there is a research about thread specific heap) but current implementation share the heap. (and of course the code)

What is the difference between compare() and compareTo()?

The main difference is in the use of the interfaces:

Comparable (which has compareTo()) requires the objects to be compared (in order to use a TreeMap, or to sort a list) to implement that interface. But what if the class does not implement Comparable and you can't change it because it's part of a 3rd party library? Then you have to implement a Comparator, which is a bit less convenient to use.

How to autosize and right-align GridViewColumn data in WPF?

I know that this is too late but here is my approach:

<GridViewColumn x:Name="GridHeaderLocalSize"  Width="100">      
<GridViewColumn.Header>
    <GridViewColumnHeader HorizontalContentAlignment="Right">
        <Grid Width="Auto" HorizontalAlignment="Right">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"/>
            </Grid.ColumnDefinitions>
            <TextBlock Grid.Column="0" Text="Local size" TextAlignment="Right" Padding="0,0,5,0"/>
        </Grid>
    </GridViewColumnHeader>
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Width="{Binding ElementName=GridHeaderLocalSize, Path=Width, FallbackValue=100}"  HorizontalAlignment="Right" TextAlignment="Right" Padding="0,0,5,0" Text="Text" >
        </TextBlock>
    </DataTemplate>
</GridViewColumn.CellTemplate>

The main idea is to bind the width of the cellTemplete element to the width of the ViewGridColumn. Width=100 is default width used until first resize. There isn't any code behind. Everything is in xaml.

How to position a table at the center of div horizontally & vertically

Just add margin: 0 auto; to your table. No need of adding any property to div

_x000D_
_x000D_
<div style="background-color:lightgrey">_x000D_
 <table width="80%" style="margin: 0 auto; border:1px solid;text-align:center">_x000D_
    <tr>_x000D_
      <th>Name </th>_x000D_
      <th>Country</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>John</td>_x000D_
      <td>US </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Bob</td>_x000D_
      <td>India </td>_x000D_
    </tr>_x000D_
 </table>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Note: Added background color to div to visualize the alignment of table to its center

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

How to fix the height of a <div> element?

change the div to display block

.topbar{
    display:block;
    width:100%;
    height:70px;
    background-color:#475;
    overflow:scroll;
    }

i made a jsfiddle example here please check

http://jsfiddle.net/TgPRM/

Nested jQuery.each() - continue/break

return true not work

return false working

found = false;
query = "foo";

$('.items').each(function()
{
  if($(this).text() == query)
  {
    found = true;
    return false;
  }
});

String.format() to format double in java

public class MainClass {
   public static void main(String args[]) {
    System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);

    System.out.printf("Default floating-point format: %f\n", 1234567.123);
    System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
    System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
    System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);

    System.out.printf("Line-up positive and negative values:\n");
    System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
  }
}

And print out:

3 (3) +3 00003
Default floating-point format: 1234567,123000
Floating-point with commas: 1.234.567,123000
Negative floating-point default: -1.234.567,123000
Negative floating-point option: (1.234.567,123000)

Line-up positive and negative values:
1.234.567,12
-1.234.567,12

Checking if an Android application is running in the background

Idolon's answer is error prone and much more complicated althought repeatead here check android application is in foreground or not? and here Determining the current foreground application from a background task or service

There is a much more simpler approach:

On a BaseActivity that all Activities extend:

protected static boolean isVisible = false;

 @Override
 public void onResume()
 {
     super.onResume();
     setVisible(true);
 }


 @Override
 public void onPause()
 {
     super.onPause();
     setVisible(false);
 }

Whenever you need to check if any of your application activities is in foreground just check isVisible();

To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle

What is a singleton in C#?

A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

How do you search an amazon s3 bucket?

Another option is to mirror the S3 bucket on your web server and traverse locally. The trick is that the local files are empty and only used as a skeleton. Alternatively, the local files could hold useful meta data that you normally would need to get from S3 (e.g. filesize, mimetype, author, timestamp, uuid). When you provide a URL to download the file, search locally and but provide a link to the S3 address.

Local file traversing is easy and this approach for S3 management is language agnostic. Local file traversing also avoids maintaining and querying a database of files or delays making a series of remote API calls to authenticate and get the bucket contents.

You could allow users to upload files directly to your server via FTP or HTTP and then transfer a batch of new and updated files to Amazon at off peak times by just recursing over the directories for files with any size. On the completion of a file transfer to Amazon, replace the web server file with an empty one of the same name. If a local file has any filesize then serve it directly because its awaiting batch transfer.

Changing image size in Markdown

With certain Markdown implementations (including Mou and Marked 2 (only macOS)) you can append =WIDTHxHEIGHT after the URL of the graphic file to resize the image. Do not forget the space before the =.

![](./pic/pic1_50.png =100x20)

You can skip the HEIGHT

![](./pic/pic1s.png =250x)

What is the best way to connect and use a sqlite database from C#

if you have any problem with the library you can use Microsoft.Data.Sqlite;

 public static DataTable GetData(string connectionString, string query)
        {
            DataTable dt = new DataTable();
            Microsoft.Data.Sqlite.SqliteConnection connection;
            Microsoft.Data.Sqlite.SqliteCommand command;

            connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
            try
            {
                connection.Open();
                command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
                dt.Load(command.ExecuteReader());
                connection.Close();
            }
            catch
            {
            }

            return dt;
        }

you can add NuGet Package Microsoft.Data.Sqlite

How can I convert a Word document to PDF?

unoconv, it's a python tool worked in UNIX. While I use Java to invoke the shell in UNIX, it works perfect for me. My source code : UnoconvTool.java. Both JODConverter and unoconv are said to use open office/libre office.

docx4j/docxreport, POI, PDFBox are good but they are missing some formats in conversion.

How to Rotate a UIImage 90 degrees?

I had trouble with ll of the above, including the approved answer. I converted Hardy's category back into a method since all i wanted was to rotate an image. Here's the code and usage:

- (UIImage *)imageRotatedByDegrees:(UIImage*)oldImage deg:(CGFloat)degrees{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,oldImage.size.width, oldImage.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(degrees * M_PI / 180);
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();

// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

//   // Rotate the image context
CGContextRotateCTM(bitmap, (degrees * M_PI / 180));

// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-oldImage.size.width / 2, -oldImage.size.height / 2, oldImage.size.width, oldImage.size.height), [oldImage CGImage]);

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

And the usage:

UIImage *image2 = [self imageRotatedByDegrees:image deg:90];

Thanks Hardy!

How can I change the color of my prompt in zsh (different from normal text)?

Try my favorite: put in

~/.zshrc

this line:

PROMPT='%F{240}%n%F{red}@%F{green}%m:%F{141}%d$ %F{reset}'

don't forget

source ~/.zshrc

to test the changes

you can change the colors/color codes, of course :-)

Google Maps API Multiple Markers with Infowindows

function setMarkers(map,locations){

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

 var loan = locations[i][0];
 var lat = locations[i][1];
 var long = locations[i][2];
 var add =  locations[i][3];

 latlngset = new google.maps.LatLng(lat, long);

 var marker = new google.maps.Marker({  
          map: map, title: loan , position: latlngset  
 });
 map.setCenter(marker.getPosition());


 marker.content = "<h3>Loan Number: " + loan +  '</h3>' + "Address: " + add;


 google.maps.events.addListener(marker,'click', function(map,marker){
          map.infowindow.setContent(marker.content);
          map.infowindow.open(map,marker);

 });

 }
}

Then move var infowindow = new google.maps.InfoWindow() to the initialize() function:

function initialize() {

    var myOptions = {
      center: new google.maps.LatLng(33.890542, 151.274856),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    var map = new google.maps.Map(document.getElementById("default"),
        myOptions);
    map.infowindow = new google.maps.InfoWindow();

    setMarkers(map,locations)

  }

Convert Java Array to Iterable

First of all, I can only agree that Arrays.asList(T...) is clearly the best solution for Wrapper types or arrays with non-primtive datatypes. This method calls a constructor of a simple private static AbstractList implementation in the Arrays class which basically saves the given array reference as field and simulates a list by overriding the needed methods.

If you can choose between a primtive type or a Wrapper type for your array, I would use the Wrapper type for such situations but of course, it's not always useful or required. There would be only two possibilities you can do:

1) You can create a class with a static method for each primitive datatype array (boolean, byte, short, int, long, char, float, double returning an Iterable<WrapperType>. These methods would use anonymous classes of Iterator (besides Iterable) which are allowed to contain the reference of the comprising method's argument (for example an int[]) as field in order to implement the methods.

-> This approach is performant and saves you memory (except for the memory of the newly created methods, even though, using Arrays.asList() would take memory in the same way)

2) Since arrays don't have methods (as to be read on the side you linked) they can't provide an Iterator instance either. If you really are too lazy to write new classes, you must use an instance of an already existing class that implements Iterable because there is no other way around than instantiating Iterable or a subtype.
The ONLY way to create an existing Collection derivative implementing Iterable is to use a loop (except you use anonymous classes as described above) or you instantiate an Iterable implementing class whose constructor allows a primtive type array (because Object[] doesn't allow arrays with primitive type elements) but as far as I know, the Java API doesn't feature a class like that.

The reason for the loop can be explained easily:
for each Collection you need Objects and primtive datatypes aren't objects. Objects are much bigger than primitive types so that they require additional data which must be generated for each element of the primitive type array. That means if two ways of three (using Arrays.asList(T...) or using an existing Collection) require an aggregate of objects, you need to create for each primitive value of your int[] array the wrapper object. The third way would use the array as is and use it in an anonymous class as I think it's preferable due to fast performance.

There is also a third strategy using an Object as argument for the method where you want to use the array or Iterable and it would require type checks to figure out which type the argument has, however I wouldn't recommend it at all as you usually need to consider that the Object hasn't always the required type and that you need seperate code for certain cases.

In conclusion, it's the fault of Java's problematic Generic Type system which doesn't allow to use primitive types as generic type which would save a lot of code by using simply Arrays.asList(T...). So you need to program for each primitive type array, you need, such a method (which basically makes no difference to the memory used by a C++ program which would create for each used type argument a seperate method.

jQuery: get data attribute

You could use the .attr() function:

$(this).attr('data-fullText')

or if you lowercase the attribute name:

data-fulltext="This is a span element"

then you could use the .data() function:

$(this).data('fulltext')

The .data() function expects and works only with lowercase attribute names.

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

How do I get the old value of a changed cell in Excel VBA?

I had to do it too. I found the solution from "Chris R" really good, but thought it could be more compatible in not adding any references. Chris, you talked about using Collection. So here is another solution using Collection. And it's not that slow, in my case. Also, with this solution, in adding the event "_SelectionChange", it's always working (no need of workbook_open).

Dim OldValues As New Collection

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'Copy old values
    Set OldValues = Nothing
    Dim c As Range
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    On Local Error Resume Next  ' To avoid error if the old value of the cell address you're looking for has not been copied
    Dim c As Range
    For Each c In Target
        Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value was " & OldValues(c.Address)
    Next c
    'Copy old values (in case you made any changes in previous lines of code)
    Set OldValues = Nothing
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Well I got this Issue too in my few websites and all i need to do is customize the content fetler for HTML entites. before that more i delete them more i got, so just change you html fiter or parsing function for the page and it worked. Its mainly due to HTML editors in most of CMSs. the way they store parse the data caused this issue (In My case). May this would Help in your case too

Apply CSS to jQuery Dialog Buttons

I’m reposting my answer to a similar question because no-one seems to have given it here and it’s much cleaner and neater:

Use the alternative buttons property syntax:

$dialogDiv.dialog({
    autoOpen: false,
    modal: true,
    width: 600,
    resizable: false,
    buttons: [
        {
            text: "Cancel",
            "class": 'cancelButtonClass',
            click: function() {
                // Cancel code here
            }
        },
        {
            text: "Save",
            "class": 'saveButtonClass',
            click: function() {
                // Save code here
            }
        }
    ],
    close: function() {
        // Close code here (incidentally, same as Cancel code)
    }
});

What is the size limit of a post request?

One of the best solutions for this, you do not use multiple or more than 1,000 input fields. You can concatenate multiple inputs with any special character, for ex. @.

See this:

<input type='text' name='hs1' id='hs1'>
<input type='text' name='hs2' id='hs2'>
<input type='text' name='hs3' id='hs3'>
<input type='text' name='hs4' id='hs4'>
<input type='text' name='hs5' id='hs5'>

<input type='hidden' name='hd' id='hd'>

Using any script (JavaScript or JScript),

document.getElementById("hd").value = document.getElementById("hs1").value+"@"+document.getElementById("hs2").value+"@"+document.getElementById("hs3").value+"@"+document.getElementById("hs4").value+"@"+document.getElementById("hs5").value

With this, you will bypass the max_input_vars issue. If you increase max_input_vars in the php.ini file, that is harmful to the server because it uses more server cache memory, and this can sometimes crash the server.

How to generate a random integer number from within a range

Wouldn't you just do:

srand(time(NULL));
int r = ( rand() % 6 ) + 1;

% is the modulus operator. Essentially it will just divide by 6 and return the remainder... from 0 - 5

The request was aborted: Could not create SSL/TLS secure channel

If you don't want to, can't easily, or can't quickly patch your code, instead, you can force TLS 1.2 usage by your .NET code in the framework.

This isn't my app, but it helped hotfix our older .NET 4.5 app (running on Server 2008r2) to work again with Paypal Payflow Gateway. They must have started forcing connections over to TLS 1.2 on the payflow gateway callbacks between 6/25/18 and 7/8/18.

Details: https://github.com/TheLevelUp/pos-tls-patcher Download: https://github.com/TheLevelUp/pos-tls-patcher/releases

toggle show/hide div with button?

Here's a plain Javascript way of doing toggle:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">

In Android EditText, how to force writing uppercase?

Even better... one liner in Kotlin...

// gets your previous attributes in XML, plus adds AllCaps filter    
<your_edit_text>.setFilters(<your_edit_text>.getFilters() + InputFilter.AllCaps())

Done!

Adding maven nexus repo to my pom.xml

From Maven - Settings Reference

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                  http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <servers>
    <server>
      <id>server001</id>
      <username>my_login</username>
      <password>my_password</password>
      <privateKey>${user.home}/.ssh/id_dsa</privateKey>
      <passphrase>some_passphrase</passphrase>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
      <configuration></configuration>
    </server>
  </servers>
  ...
</settings>

id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.

username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.

privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.

filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.

Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.

All you should need is the id, username and password

The id and URL should be defined in your pom.xml like this:

<repositories>
    ...
    <repository>
        <id>acme-nexus-releases</id>
        <name>acme nexus</name>
        <url>https://nexus.acme.net/content/repositories/releases</url>
    </repository>
    ...
</repositories>

If you need a username and password to your server, you should encrypt it. Maven Password Encryption

How to validate an email address using a regular expression?

If you want to improve on a regex that has been working reasonably well over several years, then the answer depends on what exactly you want to achieve - what kinds of email addresses have been failing. Fine-tuning email regexes is very difficult, and I have yet to see a perfect solution.

  • If your application involves something very technical in nature (or something internal to organizations), then maybe you need to support IP addresses instead of domain names, or comments in the "local" part of the email address.
  • If your application is multinational, I would consider focusing on Unicode/UTF8 support.

The leading answer to your question currently links to a "fully RFC-822–compliant regex". However, in spite of the complexity of that regex and its presumed attention to detail in RFC rules, it completely fails when it comes to Unicode support.

The regex that I've written for most of my apps focuses on Unicode support, as well as reasonably good overall adherence to RFC standards:

/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFFu20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\.!#$%&'*+-/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\-\.\d]+)((\.([a-zA-Z\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF]){2,63})+)$/i

I'll avoid copy-pasting complete answers, so I'll just link this to a similar answer I provided here: How to validate a unicode email?

There is also a live demo available for the regex above at: http://jsfiddle.net/aossikine/qCLVH/3/

Permission is only granted to system app

In Eclipse:

Window -> Preferences -> Android -> Lint Error Checking.

In the list find an entry with ID = ProtectedPermission. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.

In Android Studio:

File -> Settings -> Editor -> Inspections

Under Android Lint, locate Using system app permission. Either uncheck the checkbox or choose a Severity lower than Error.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

I followed the below steps and it worked for me.

Step1: Edit eclipse.ini by adding javaw.exe path and remove --launcher.appendVmargs line. Below shows the original and edited file

Orginal eclipse.ini openFile --launcher.appendVmargs -vmargs -Dosgi.requiredJavaVersion=1.8

After editing eclipse.ini: openFile -vm C:/ProgramFiles/Java/javapath/javaw.exe -vmargs -Dosgi.requiredJavaVersion=1.8

Step2: Copied the org.eclipse.equinox.launcher_1.5.700.v20200207-2156.jar to eclipse installation folder . You can find the .jar location in eclipse.ini eg : C:\Users\Username.p2\pool\plugins

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

How to check if a user is logged in (how to properly use user.is_authenticated)?

Update for Django 1.10+:

is_authenticated is now an attribute in Django 1.10.

The method was removed in Django 2.0.

For Django 1.9 and older:

is_authenticated is a function. You should call it like

if request.user.is_authenticated():
    # do something if the user is authenticated

As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:

{% if user.is_authenticated %}

However, in Python code, it is indeed a method in the User class.

How do I get the application exit code from a Windows command line?

At one point I needed to accurately push log events from Cygwin to the Windows Event log. I wanted the messages in WEVL to be custom, have the correct exit code, details, priorities, message, etc. So I created a little Bash script to take care of this. Here it is on GitHub, logit.sh.

Some excerpts:

usage: logit.sh [-h] [-p] [-i=n] [-s] <description>
example: logit.sh -p error -i 501 -s myscript.sh "failed to run the mount command"

Here is the temporary file contents part:

LGT_TEMP_FILE="$(mktemp --suffix .cmd)"
cat<<EOF>$LGT_TEMP_FILE
    @echo off
    set LGT_EXITCODE="$LGT_ID"
    exit /b %LGT_ID%
EOF
unix2dos "$LGT_TEMP_FILE"

Here is a function to to create events in WEVL:

__create_event () {
    local cmd="eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D "
    if [[ "$1" == *';'* ]]; then
        local IFS=';'
        for i in "$1"; do
            $cmd "$i" &>/dev/null
        done
    else
        $cmd "$LGT_DESC" &>/dev/null
    fi
}

Executing the batch script and calling on __create_event:

cmd /c "$(cygpath -wa "$LGT_TEMP_FILE")"
__create_event

How to get CPU temperature?

I know this post is old, but just wanted to add a comment if somebody should be looking at this post and trying to find a solution for this problem.

You can indeed read the CPU temperature very easily in C# by using a WMI approach.

To get a Celsius value, I have created a wrapper that converts the value returned by WMI and wraps it into an easy to use object.

Please remember to add a reference to the System.Management.dll in Visual Studio.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace RCoding.Common.Diagnostics.SystemInfo
{
    public class Temperature
    {
        public double CurrentValue { get; set; }
        public string InstanceName { get; set; }
        public static List<Temperature> Temperatures
        {
            get
            {
                List<Temperature> result = new List<Temperature>();
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");
                foreach (ManagementObject obj in searcher.Get())
                {
                    Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString());
                    temp = (temp - 2732) / 10.0;
                    result.Add(new Temperature { CurrentValue = temp, InstanceName = obj["InstanceName"].ToString() });
                }
                return result;

            }
        }
    }
}

Update 25.06.2010:

(Just saw that a link was posted to the same kind of solution above... Anyway, I will leave this piece of code if somebody should want to use it :-) )

How do I find out if first character of a string is a number?

Character.isDigit(string.charAt(0))

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Or the slower regex solutions:

s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")

If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.

How to create unique keys for React elements?

Do not use this return `${ pre }_${ new Date().getTime()}`;. It's better to have the array index instead of that because, even though it's not ideal, that way you will at least get some consistency among the list components, with the new Date function you will get constant inconsistency. That means every new iteration of the function will lead to a new truly unique key.

The unique key doesn't mean that it needs to be globally unique, it means that it needs to be unique in the context of the component, so it doesn't run useless re-renders all the time. You won't feel the problem associated with new Date initially, but you will feel it, for example, if you need to get back to the already rendered list and React starts getting all confused because it doesn't know which component changed and which didn't, resulting in memory leaks, because, you guessed it, according to your Date key, every component changed.

Now to my answer. Let's say you are rendering a list of YouTube videos. Use the video id (arqTu9Ay4Ig) as a unique ID. That way, if that ID doesn't change, the component will stay the same, but if it does, React will recognize that it's a new Video and change it accordingly.

It doesn't have to be that strict, the little more relaxed variant is to use the title, like Erez Hochman already pointed out, or a combination of the attributes of the component (title plus category), so you can tell React to check if they have changed or not.

edited some unimportant stuff

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

Assign command output to variable in batch file

This is work for me

@FOR /f "delims=" %i in ('reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion') DO set var=%i
echo %var%

What are all possible pos tags of NLTK?

['LS', 'TO', 'VBN', "''", 'WP', 'UH', 'VBG', 'JJ', 'VBZ', '--', 'VBP', 'NN', 'DT', 'PRP', ':', 'WP$', 'NNPS', 'PRP$', 'WDT', '(', ')', '.', ',', '``', '$', 'RB', 'RBR', 'RBS', 'VBD', 'IN', 'FW', 'RP', 'JJR', 'JJS', 'PDT', 'MD', 'VB', 'WRB', 'NNP', 'EX', 'NNS', 'SYM', 'CC', 'CD', 'POS']

Based on Doug Shore's method but make it more copy-paste friendly

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

Git pull - Please move or remove them before you can merge

If there are too many files to delete, which is actually a case for me. You can also try the following solution:

1) fetch

2) merge with a strategy. For instance this one works for me:

git.exe merge --strategy=ours master

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

If you want to migrate the repo including the wiki and all issues and milestones, you can use node-gitlab-2-github and GitLab to GitHub migration

Get root view from current activity

Another Kotlin Extension solution

If your activity's view is declared in xml (ex activity_root.xml), open the xml and assign an id to the root view:

android:id="@+id/root_activity"

Now in your class, import the view using:

import kotlinx.android.synthetic.main.activity_root.root_activity

You can now use root_activity as the view.

jQuery - Disable Form Fields

<script type="text/javascript" src="jquery.js"></script>          
<script type="text/javascript">
  $(document).ready(function() {
      $("#suburb").blur(function() {
          if ($(this).val() != '')
              $("#post_code").attr("disabled", "disabled");
          else
              $("#post_code").removeAttr("disabled");
      });

      $("#post_code").blur(function() {
          if ($(this).val() != '')
              $("#suburb").attr("disabled", "disabled");
          else
              $("#suburb").removeAttr("disabled");
      });
  });
</script>

You'll also need to add a value attribute to the first option under your select element:

<option value=""></option>

How the single threaded non blocking IO model works in Node.js

Node.js is based on the event loop programming model. The event loop runs in single thread and repeatedly waits for events and then runs any event handlers subscribed to those events. Events can be for example

  • timer wait is complete
  • next chunk of data is ready to be written to this file
  • theres a fresh new HTTP request coming our way

All of this runs in single thread and no JavaScript code is ever executed in parallel. As long as these event handlers are small and wait for yet more events themselves everything works out nicely. This allows multiple request to be handled concurrently by a single Node.js process.

(There's a little bit magic under the hood as where the events originate. Some of it involve low level worker threads running in parallel.)

In this SQL case, there's a lot of things (events) happening between making the database query and getting its results in the callback. During that time the event loop keeps pumping life into the application and advancing other requests one tiny event at a time. Therefore multiple requests are being served concurrently.

event loop high level view

According to: "Event loop from 10,000ft - core concept behind Node.js".

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

Transfer data between databases with PostgreSQL

I just had to do this exact thing so I figured I'd post the recipe here. This assumes that both databases are on the same server.

First, copy the table from the old db to the new db (because apparently you can't move data between databases). At the commandline:

pg_dump -U postgres -t <old_table> <old_database> | psql -U postgres -d <new_database>

# Just adding extra space here so scrollbar doesn't hide the command

Next, grant permissions of the copied table to the user of the new database. Log into psql:

psql -U postgres -d <new_database>

ALTER TABLE <old_table> OWNER TO <new_user>;

\q

Finally, copy data from the old table to the new table. Log in as the new user and then:

INSERT INTO <new_table> (field1, field2, field3) 
SELECT field1, field2, field3 from <old_table>;

Done!

Pass Arraylist as argument to function

The answer is already posted but note that this will pass the ArrayList by reference. So if you make any changes to the list in the function it will be affected to the original list also.

<access-modfier> <returnType> AnalyseArray(ArrayList<Integer> list)
{
//analyse the list
//return value
}

call it like this:

x=AnalyseArray(list);

or pass a copy of ArrayList:

x=AnalyseArray(list.clone());

pandas unique values multiple columns

for those of us that love all things pandas, apply, and of course lambda functions:

df['Col3'] = df[['Col1', 'Col2']].apply(lambda x: ''.join(x), axis=1)

Code formatting shortcuts in Android Studio for Operation Systems

You can use the following shortcut for code formatting: Ctrl+Alt+L

How to use execvp()

In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

in my case i have saved a json file with a space like this

google-services .json

and the right one is

google-services.json

and also take care you do not put (_) instead of (-)

may help some one.

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

MySQL - Replace Character in Columns

maybe I'd go by this.

 SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable

I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.

Hope that helps.

Is embedding background image data into CSS as Base64 good or bad practice?

As far as I have researched,

Use : 1. When you are using an svg sprite. 2. When your images are of a lesser size (max 200mb).

Don't Use : 1. When you are bigger images. 2. Icons as svg's. As they are already good and gzipped after compression.

Concatenating Column Values into a Comma-Separated List

Another solution within a query :

select 
    Id, 
    STUFF(
        (select (', "' + od.ProductName + '"')
        from OrderDetails od (nolock)
        where od.Order_Id = o.Id
        order by od.ProductName
        FOR XML PATH('')), 1, 2, ''
    ) ProductNames
from Orders o (nolock)
where o.Customer_Id = 525188
order by o.Id desc

(EDIT: thanks @user007 for the STUFF declaration)

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

I encountered this error that occurred on all outlets in a custom class I had created for a table view prototype cell. The outlets were all correctly connected to the storyboard, and the Class field was correctly named in the identity inspector for the prototype cell.

Deleting and recreating the outlets did not work. Cleaning the build did not work. What finally worked was to change the Class in the storyboard identity inspector to the default UITableViewCell, hit Enter, then change it back to the name of my custom class afterwards. For some reason, this worked.

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).