Programs & Examples On #Posixct

In the R language, the classes "POSIXct" and "POSIXlt" are representing calendar dates and times (to the nearest second).

Extracting time from POSIXct

Many solutions have been provided, but I have not seen this one, which uses package chron:

hours = times(strftime(times, format="%T"))
plot(val~hours)

(sorry, I am not entitled to post an image, you'll have to plot it yourself)

Why do I get "'property cannot be assigned" when sending an SMTP email?

public static void SendMail(MailMessage Message)
{
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.googlemail.com";
    client.Port = 587;
    client.UseDefaultCredentials = false;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential("[email protected]", "password");
    client.Send(Message); 
}

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}

How to remove last n characters from a string in Bash?

This worked for me by calculating size of string.
It is easy you need to echo the value you need to return and then store it like below

removechars(){
        var="some string.rtf"
        size=${#var}
        echo ${var:0:size-4}  
    }
    removechars
    var2=$?

some string

jquery data selector

If you also use jQueryUI, you get a (simple) version of the :data selector with it that checks for the presence of a data item, so you can do something like $("div:data(view)"), or $( this ).closest(":data(view)").

See http://api.jqueryui.com/data-selector/ . I don't know for how long they've had it, but it's there now!

Mapping two integers to one, in a unique and deterministic way

Although Stephan202's answer is the only truly general one, for integers in a bounded range you can do better. For example, if your range is 0..10,000, then you can do:

#define RANGE_MIN 0
#define RANGE_MAX 10000

unsigned int merge(unsigned int x, unsigned int y)
{
    return (x * (RANGE_MAX - RANGE_MIN + 1)) + y;
}

void split(unsigned int v, unsigned int &x, unsigned int &y)
{
    x = RANGE_MIN + (v / (RANGE_MAX - RANGE_MIN + 1));
    y = RANGE_MIN + (v % (RANGE_MAX - RANGE_MIN + 1));
}

Results can fit in a single integer for a range up to the square root of the integer type's cardinality. This packs slightly more efficiently than Stephan202's more general method. It is also considerably simpler to decode; requiring no square roots, for starters :)

Oracle: how to set user password unexpire?

If you create a user using a profile like this:

CREATE PROFILE my_profile LIMIT
       PASSWORD_LIFE_TIME 30;
ALTER USER scott PROFILE my_profile;

then you can change the password lifetime like this:

ALTER PROFILE my_profile LIMIT
  PASSWORD_LIFE_TIME UNLIMITED;

I hope that helps.

Sass - Converting Hex to RGBa for background opacity

you can try this solution, is the best... url(github)

// Transparent Background
// From: http://stackoverflow.com/questions/6902944/sass-mixin-for-background-transparency-back-to-ie8

// Extend this class to save bytes
.transparent-background {
  background-color: transparent;
  zoom: 1;
}

// The mixin
@mixin transparent($color, $alpha) {
  $rgba: rgba($color, $alpha);
  $ie-hex-str: ie-hex-str($rgba);
  @extend .transparent-background;
  background-color: $rgba;
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex-str},endColorstr=#{$ie-hex-str});
}

// Loop through opacities from 90 to 10 on an alpha scale
@mixin transparent-shades($name, $color) {
  @each $alpha in 90, 80, 70, 60, 50, 40, 30, 20, 10 {
    .#{$name}-#{$alpha} {
      @include transparent($color, $alpha / 100);
    }
  }
}

// Generate semi-transparent backgrounds for the colors we want
@include transparent-shades('dark', #000000);
@include transparent-shades('light', #ffffff);

Should I use 'has_key()' or 'in' on Python dicts?

in wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:

$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d'
10000000 loops, best of 3: 0.0983 usec per loop
$ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)'
1000000 loops, best of 3: 0.21 usec per loop

While the following observation is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why -mtimeit is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)

How to convert a PIL Image into a numpy array?

Open I as an array:

>>> I = numpy.asarray(PIL.Image.open('test.jpg'))

Do some stuff to I, then, convert it back to an image:

>>> im = PIL.Image.fromarray(numpy.uint8(I))

Filter numpy images with FFT, Python

If you want to do it explicitly for some reason, there are pil2array() and array2pil() functions using getdata() on this page in correlation.zip.

Best way to remove from NSMutableArray while iterating?

Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.

MySQL/Writing file error (Errcode 28)

Today. I have same problem... my solution:

1) check inode: df -i I saw:

root@vm22433:/etc/mysql# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 124696 304 124392 1% /dev
tmpfs 127514 452 127062 1% /run
/dev/vda1 1969920 1969920 0 100% /
tmpfs 127514 1 127513 1% /dev/shm
tmpfs 127514 3 127511 1% /run/lock
tmpfs 127514 15 127499 1% /sys/fs/cgroup
tmpfs 127514 12 127502 1% /run/user/1002

2) I began to look what folders use the maximum number of inods:

 for i in /*; do echo $i; find $i |wc -l; done

soon I found in /home/tomnolane/tmp folder, which contained a huge number of files.

3) I removed /home/tomnolane/tmp folder PROFIT.

4) checked:

Filesystem      Inodes  IUsed   IFree IUse% Mounted on
udev            124696    304  124392    1% /dev
tmpfs           127514    454  127060    1% /run
/dev/vda1      1969920 450857 1519063   23% /
tmpfs           127514      1  127513    1% /dev/shm
tmpfs           127514      3  127511    1% /run/lock
tmpfs           127514     15  127499    1% /sys/fs/cgroup
tmpfs           127514     12  127502    1% /run/user/1002

it's ok.

5) restart mysql service - it's ok!!!!

Zip lists in Python

zip creates a new list, filled with tuples containing elements from the iterable arguments:

>>> zip ([1,2],[3,4])
[(1,3), (2,4)]

I expect what you try to so is create a tuple where each element is a list.

Reading data from DataGridView in C#

If you wish, you can also use the column names instead of column numbers.

For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.

dataGridView.Rows[4].Cells["Name"].Value.ToString();

Hope it helps.

How to copy a file from one directory to another using PHP?

You can use both rename() and copy().

I tend to prefer to use rename if I no longer require the source file to stay in its location.

C# convert int to string with padding zeros?

i.ToString("D4");

See MSDN on format specifiers.

Shell equality operators (=, ==, -eq)

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

Can you change what a symlink points to after it is created?

Wouldn't unlinking it and creating the new one do the same thing in the end anyway?

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

Apply jQuery datepicker to multiple instances

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

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

Reordering arrays

Immutable version, no side effects (doesn’t mutate original array):

const testArr = [1, 2, 3, 4, 5];

function move(from, to, arr) {
    const newArr = [...arr];

    const item = newArr.splice(from, 1)[0];
    newArr.splice(to, 0, item);

    return newArr;
}

console.log(move(3, 1, testArr));

// [1, 4, 2, 3, 5]

codepen: https://codepen.io/mliq/pen/KKNyJZr

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Check if a String contains a special character

Pattern p = Pattern.compile("[\\p{Alpha}]*[\\p{Punct}][\\p{Alpha}]*");
        Matcher m = p.matcher("Afsff%esfsf098");
        boolean b = m.matches();

        if (b == true)
           System.out.println("There is a sp. character in my string");
        else
            System.out.println("There is no sp. char.");

Convert byte to string in Java

You have to construct a new string out of a byte array. The first element in your byteArray should be 0x63. If you want to add any more letters, make the byteArray longer and add them to the next indices.

byte[] byteArray = new byte[1];
byteArray[0] = 0x63;

try {
    System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
    // TODO: Handle exception.
    e.printStackTrace();
}

Note that specifying the encoding will eventually throw an UnsupportedEncodingException and you must handle that accordingly.

Could not find folder 'tools' inside SDK

If you get the "Failed to find DDMS files..." do this:

  1. Open eclipse
  2. Open install new software
  3. Click "Add..." -> type in (e.g.) "Android_over_HTTP" and in address put "http://dl-ssl.google.com/android/eclipse/".

Don't be alarmed that its not https, this helps to fetch stuff over http. This trick helped me to resolve the issue on MAC, I believe that this also should work on Windows / Linux

Hope this helps !

Uploading an Excel sheet and importing the data into SQL Server database

Try Using

string filename = Path.GetFileName(FileUploadControl.FileName);

Then Save the file at specified location using:

FileUploadControl.PostedFile.SaveAs(strpath + filename);

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

For PDOException: could not find driver for MySQL, and if it is Debian based OS,

sudo apt-get -y install php5-mysql

CSS Child vs Descendant selectors

Be aware that the child selector is not supported in Internet Explorer 6. (If you use the selector in a jQuery/Prototype/YUI etc selector rather than in a style sheet it still works though)

How to sort an array in Bash

There is a workaround for the usual problem of spaces and newlines:

Use a character that is not in the original array (like $'\1' or $'\4' or similar).

This function gets the job done:

# Sort an Array may have spaces or newlines with a workaround (wa=$'\4')
sortarray(){ local wa=$'\4' IFS=''
             if [[ $* =~ [$wa] ]]; then
                 echo "$0: error: array contains the workaround char" >&2
                 exit 1
             fi

             set -f; local IFS=$'\n' x nl=$'\n'
             set -- $(printf '%s\n' "${@//$nl/$wa}" | sort -n)
             for    x
             do     sorted+=("${x//$wa/$nl}")
             done
       }

This will sort the array:

$ array=( a b 'c d' $'e\nf' $'g\1h')
$ sortarray "${array[@]}"
$ printf '<%s>\n' "${sorted[@]}"
<a>
<b>
<c d>
<e
f>
<gh>

This will complain that the source array contains the workaround character:

$ array=( a b 'c d' $'e\nf' $'g\4h')
$ sortarray "${array[@]}"
./script: error: array contains the workaround char

description

  • We set two local variables wa (workaround char) and a null IFS
  • Then (with ifs null) we test that the whole array $*.
  • Does not contain any woraround char [[ $* =~ [$wa] ]].
  • If it does, raise a message and signal an error: exit 1
  • Avoid filename expansions: set -f
  • Set a new value of IFS (IFS=$'\n') a loop variable x and a newline var (nl=$'\n').
  • We print all values of the arguments received (the input array $@).
  • but we replace any new line by the workaround char "${@//$nl/$wa}".
  • send those values to be sorted sort -n.
  • and place back all the sorted values in the positional arguments set --.
  • Then we assign each argument one by one (to preserve newlines).
  • in a loop for x
  • to a new array: sorted+=(…)
  • inside quotes to preserve any existing newline.
  • restoring the workaround to a newline "${x//$wa/$nl}".
  • done

Removing a Fragment from the back stack

I created a code to jump to the desired back stack index, it worked fine to my purpose.

ie. I have Fragment1, Fragment2 and Fragment3, I want to jump from Fragment3 to Fragment1

I created a method called onBackPressed in Fragment3 that jumps to Fragment1

Fragment3:

public void onBackPressed() {
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-2).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

In the activity, I need to know if my current fragment is the Fragment3, so I call the onBackPressed of my fragment instead calling super

FragmentActivity:

@Override
public void onBackPressed() {
    Fragment f = getSupportFragmentManager().findFragmentById(R.id.my_fragment_container);
    if (f instanceof Fragment3)
    {
        ((Fragment3)f).onBackPressed();
    } else {
        super.onBackPressed();
    }
}

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Is there a way to split a widescreen monitor in to two or more virtual monitors?

Right now, I'm using twinsplay to organize my windows side by side.

I tried Winsplit before, but I couldn't get it to work because the default hotkeys ( Ctrl-Alt-Left, Ctrl-Alt-Right ) clashed with the graphics card hotkeys for rotating my screen and setting different hotkeys just didn't work. Twinsplay just worked for me out of the box.

Another nice thing about twinsplay is that it also allows me to save and restore windows "sessions" - so I can save my work environment ( eclipse, total commander, visual studio, msdn, outlook, firefox ) before turning off the computer at night and then quickly get back to it in the morning.

What is the difference between Python and IPython?

From my experience I've found that some commands which run in IPython do not run in base Python. For example, pwd and ls don't work alone in base Python. However they will work if prefaced with a % such as: %pwd and %ls.

Also, in IPython, you can run the cd command like: cd C:\Users\... This doesn't seem to work in base python, even when prefaced with a % however.

Query an XDocument for elements by name at any depth

Descendants should work absolutely fine. Here's an example:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string xml = @"
<root>
  <child id='1'/>
  <child id='2'>
    <grandchild id='3' />
    <grandchild id='4' />
  </child>
</root>";
        XDocument doc = XDocument.Parse(xml);

        foreach (XElement element in doc.Descendants("grandchild"))
        {
            Console.WriteLine(element);
        }
    }
}

Results:

<grandchild id="3" />
<grandchild id="4" />

How do we download a blob url video

If the blob is instantiated with data from an F4M manifest (check the Network Tab in Chrome's Developer Tools), you can download the video file using the php script posted here: https://n1njahacks.wordpress.com/2015/01/29/how-to-save-hds-flash-streams-from-any-web-page/

By putting:

  if ($manifest == '')
    $manifest = $_GET['manifest'];

before:

  if ($manifest)

you could even run it on a webserver, using requests with the query string: ?manifest=[manifest url].

Note that you'll probably want to use an FTP client to retrieve the downloaded video file and clean up after the script (it leaves all the downloaded video parts).

List all virtualenv

If you came here from Google, trying to find where your previously created virtualenv installation ended up, and why there is no command to find it, here's the low-down.

The design of virtualenv has a fundamental flaw of not being able to keep track of it's own created environments. Someone was not quite in their right mind when they created virtualenv without having a rudimentary way to keep track of already created environments, and certainly not fit for a time and age when most pip requirements require multi-giga-byte installations, which should certainly not go into some obscure .virtualenvs sub-directory of your ~/home.

IMO, the created virtualenv directory should be created in $CWD and a file called ~/.virtualenv (in home) should keep track of the name and path of that creation. Which is a darn good reason to use Conda/Miniconda3 instead, which does seem to keep good track of this.

As answered here, the only way to keep track of this, is to install yet another package called virtualenvwrapper. If you don't do that, you will have to search for the created directory by yourself. Clearly, if you don't remember the name or the location it was created with/at, you will most likely never find your virtual environment again...

One try to remedy the situation in windows, is by putting the following functions into your powershell profile:

# wrap virtualenv.exe and write last argument (presumably 
# your virtualenv name) to the file: $HOME/.virtualenv.
function ven { if( $args.count -eq 0) {Get-Content ~/.virtualenv } else {virtualenv.exe "$args"; Write-Output ("{0} `t{1}" -f $args[-1],$PWD) | Out-File -Append $HOME/.virtualenv }}

# List what's in the file or the directories under ~/.virtualenvs
function lsven { try {Get-Content ~/.virtualenv } catch {Get-ChildItem ~\.virtualenvs -Directory | Select-Object -Property Name } }

WARNING: This will write to ~\.virtualenv...

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

AngularJS: how to implement a simple file upload with multipart form?

You can use the simple/lightweight ng-file-upload directive. It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
  $scope.onFileSelect = function($files) {
  Upload.upload({
    url: 'my/upload/url',
    file: $files,            
  }).progress(function(e) {
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

}];

Sending email in .NET through Gmail

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

What is the simplest and most robust way to get the user's current location on Android?

public static Location getBestLocation(Context ctxt) {
    Location gpslocation = getLocationByProvider(
        LocationManager.GPS_PROVIDER, ctxt);
    Location networkLocation = getLocationByProvider(
        LocationManager.NETWORK_PROVIDER, ctxt);
    Location fetchedlocation = null;
    // if we have only one location available, the choice is easy
    if (gpslocation != null) {
        Log.i("New Location Receiver", "GPS Location available.");
        fetchedlocation = gpslocation;
    } else {
        Log.i("New Location Receiver",
            "No GPS Location available. Fetching Network location lat="
                + networkLocation.getLatitude() + " lon ="
                + networkLocation.getLongitude());
        fetchedlocation = networkLocation;
    }
    return fetchedlocation;
}

/**
 * get the last known location from a specific provider (network/gps)
 */
private static Location getLocationByProvider(String provider, Context ctxt) {
    Location location = null;
    // if (!isProviderSupported(provider)) {
    // return null;
    // }
    LocationManager locationManager = (LocationManager) ctxt
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.i("New Location Receiver", "Cannot access Provider " + provider);
    }
    return location;
}

What are the ways to sum matrix elements in MATLAB?

Avoid for loops whenever possible.

sum(A(:))

is great however if you have some logical indexing going on you can't use the (:) but you can write

% Sum all elements under 45 in the matrix
sum ( sum ( A *. ( A < 45 ) )

Since sum sums the columns and sums the row vector that was created by the first sum. Note that this only works if the matrix is 2-dim.

What is the difference between supervised learning and unsupervised learning?

Supervised learning: say a kid goes to kinder-garden. here teacher shows him 3 toys-house,ball and car. now teacher gives him 10 toys. he will classify them in 3 box of house,ball and car based on his previous experience. so kid was first supervised by teachers for getting right answers for few sets. then he was tested on unknown toys. aa

Unsupervised learning: again kindergarten example.A child is given 10 toys. he is told to segment similar ones. so based on features like shape,size,color,function etc he will try to make 3 groups say A,B,C and group them. bb

The word Supervise means you are giving supervision/instruction to machine to help it find answers. Once it learns instructions, it can easily predict for new case.

Unsupervised means there is no supervision or instruction how to find answers/labels and machine will use its intelligence to find some pattern in our data. Here it will not make prediction, it will just try to find clusters which has similar data.

PHP How to fix Notice: Undefined variable:

Declare them before the while loop.

$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";

You are getting the notice because the variables are declared and assigned inside the loop.

Stacked Tabs in Bootstrap 3

To get left and right tabs (now also with sideways) support for Bootstrap 3, bootstrap-vertical-tabs component can be used.

https://github.com/dbtek/bootstrap-vertical-tabs

Command /usr/bin/codesign failed with exit code 1

Some of the answers above allude to the problem but don't clearly spell out the steps to correct it.

Here is my attempt at after it has become super frustrating which seems to have worked for me so far :

The problem is caused because there is duplicate certificates in your Apple Developer portal or potentially in your machine. I haven't had any negative consequences from doing this and its worked so far.

  1. Close Xcode!

  2. You have to remove the existing certs from your developer account visit : https://developer.apple.com/account/ios/certificate/development/ and select development account ( there should be multiple certs) I revoked each one by clicking on them and selecting revoke.

select development certs

2.remove certs from your keychain on your Mac

  • Open Keychain app by pressing clover+space and typing in keychaing
    and pressing enter
  • Search in the top right hand corner for "developer"
  • Select the potential duplicate keys and export/delete them so they aren't in the list.

search by developer

  1. Lastly regenerate your certs in XCode and rebooot

    • Reopen xcode
    • regenerate a new cert by going to project -> General --> Signing
    • reselect your "Team Account"

signing setup

  • a new cert should be generated
  • Reboot for good measure - and enjoy being free from this bug ( which Apple should really sort out, if it was at all possible to replicate easily)

How to pass Multiple Parameters from ajax call to MVC Controller

In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.

var dataObject = JSON.stringify({
                    'input': $('#myInput').val(),
                    'name': $('#myName').val(),
                });

Now use it in ajax call

$.ajax({
          url: "/Home/SaveChart",
          type: 'POST',
          async: false,
          dataType: 'json',
          contentType: 'application/json',
          data: dataObject,
          success: function (data) { },
          error: function (xhr) { }            )};

Find files and tar them (with spaces)

Why not:

tar czvf backup.tar.gz *

Sure it's clever to use find and then xargs, but you're doing it the hard way.

Update: Porges has commented with a find-option that I think is a better answer than my answer, or the other one: find -print0 ... | xargs -0 ....

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

Dynamically select data frame columns using $ and a character value

Another solution is to use #get:

> cols <- c("cyl", "am")
> get(cols[1], mtcars)
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

Finding the id of a parent div using Jquery

find() and closest() seems slightly slower than:

$(this).parent().attr("id");

Use Device Login on Smart TV / Console

i've been researching for that too but unfortunately the facebook device auth is still on experimental and they didn't give new keys (partner) to use the device auth.

You can find the working example here: http://oauth-device-demo.appspot.com/ Just look at the website source and you can have the appID that works with it.

The other one is twitter PIN oauth it's working and publicly available (i'm using it) https://dev.twitter.com/docs/auth/pin-based-authorization

Relative path to absolute path in C#?

string exactPath = Path.GetFullPath(yourRelativePath);

works

Undoing a 'git push'

git revert is less dangerous than some of the approaches suggested here:

prompt> git revert 35f6af6f77f116ef922e3d75bc80a4a466f92650
[master 71738a9] Revert "Issue #482 - Fixed bug."
 4 files changed, 30 insertions(+), 42 deletions(-)
prompt> git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
prompt>

Replace 35f6af6f77f116ef922e3d75bc80a4a466f92650 with your own commit.

How to pass object from one component to another in Angular 2?

you could also store your data in an service with an setter and get it over a getter

import { Injectable } from '@angular/core';

@Injectable()
export class StorageService {

    public scope: Array<any> | boolean = false;

    constructor() {
    }

    public getScope(): Array<any> | boolean {
        return this.scope;
    }

    public setScope(scope: any): void {
        this.scope = scope;
    }
}

qmake: could not find a Qt installation of ''

For others in my situation, the solution was:

qmake -qt=qt5

This was on Ubuntu 14.04 after install qt5-qmake. qmake was a symlink to qtchooser which takes the -qt argument.

cmake - find_library - custom library location

There is no way to automatically set CMAKE_PREFIX_PATH in a way you want. I see following ways to solve this problem:

  1. Put all libraries files in the same dir. That is, include/ would contain headers for all libs, lib/ - binaries, etc. FYI, this is common layout for most UNIX-like systems.

  2. Set global environment variable CMAKE_PREFIX_PATH to D:/develop/cmake/libs/libA;D:/develop/cmake/libs/libB;.... When you run CMake, it would aautomatically pick up this env var and populate it's own CMAKE_PREFIX_PATH.

  3. Write a wrapper .bat script, which would call cmake command with -D CMAKE_PREFIX_PATH=... argument.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How to initialize HashSet values by construction?

There are a few ways:

Double brace initialization

This is a technique which creates an anonymous inner class which has an instance initializer which adds Strings to itself when an instance is created:

Set<String> s = new HashSet<String>() {{
    add("a");
    add("b");
}}

Keep in mind that this will actually create an new subclass of HashSet each time it is used, even though one does not have to explicitly write a new subclass.

A utility method

Writing a method that returns a Set which is initialized with the desired elements isn't too hard to write:

public static Set<String> newHashSet(String... strings) {
    HashSet<String> set = new HashSet<String>();

    for (String s : strings) {
        set.add(s);
    }
    return set;
}

The above code only allows for a use of a String, but it shouldn't be too difficult to allow the use of any type using generics.

Use a library

Many libraries have a convenience method to initialize collections objects.

For example, Google Collections has a Sets.newHashSet(T...) method which will populate a HashSet with elements of a specific type.

How to allow CORS in react.js?

Use this.

app.use((req,res, next)=>{
    res.setHeader('Access-Control-Allow-Origin',"http://localhost:3000");
    res.setHeader('Access-Control-Allow-Headers',"*");
    res.header('Access-Control-Allow-Credentials', true);
    next();
});

How to easily import multiple sql files into a MySQL database?

in windows open windows powershell and go to the folder where sql files are then run this command

cat *.sql |  C:\xampp\mysql\bin\mysql.exe -u username -p databasename

Replace all occurrences of a String using StringBuilder?

How about create a method and let String.replaceAll do it for you:

public static void replaceAll(StringBuilder sb, String regex, String replacement)
{
    String aux = sb.toString();
    aux = aux.replaceAll(regex, replacement);
    sb.setLength(0);
    sb.append(aux);     
}

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

How to convert Set<String> to String[]?

Guava style:

Set<String> myset = myMap.keySet();
FluentIterable.from(mySet).toArray(String.class);

more info: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html

Java balanced expressions check {[()]}

public static void main(String[] args) {
    System.out.println("is balanced : "+isBalanced("(){}[]<>"));
    System.out.println("is balanced : "+isBalanced("({})[]<>"));
    System.out.println("is balanced : "+isBalanced("({[]})<>"));
    System.out.println("is balanced : "+isBalanced("({[<>]})"));
    System.out.println("is balanced : "+isBalanced("({})[<>]"));


    System.out.println("is balanced : "+isBalanced("({[}])[<>]"));
    System.out.println("is balanced : "+isBalanced("([{})]"));
    System.out.println("is balanced : "+isBalanced("[({}])"));
    System.out.println("is balanced : "+isBalanced("[(<{>})]"));

    System.out.println("is balanced : "+isBalanced("["));
    System.out.println("is balanced : "+isBalanced("]"));

    System.out.println("is balanced : "+isBalanced("asdlsa"));
}

private static boolean isBalanced(String brackets){
    char[] bracketsArray = brackets.toCharArray();
    Stack<Character> stack = new Stack<Character>();
    Map<Character, Character> openingClosingMap = initOpeningClosingMap();

    for (char bracket : bracketsArray) {
        if(openingClosingMap.keySet().contains(bracket)){ 
            stack.push(bracket);
        }else if(openingClosingMap.values().contains(bracket)){
            if(stack.isEmpty() || openingClosingMap.get(stack.pop())!=bracket){
                return false;
            }
        }else{
            System.out.println("Only  < > ( ) { } [ ] brackets  are allowed .");
            return false;
        }
    }
    return stack.isEmpty();
}

private static Map<Character, Character> initOpeningClosingMap() {
    Map<Character, Character> openingClosingMap = new HashMap<Character, Character>();
    openingClosingMap.put(Character.valueOf('('), Character.valueOf(')'));
    openingClosingMap.put(Character.valueOf('{'), Character.valueOf('}'));
    openingClosingMap.put(Character.valueOf('['), Character.valueOf(']'));
    openingClosingMap.put(Character.valueOf('<'), Character.valueOf('>'));
    return openingClosingMap;
}

Simplifying and making readable. Using One Map only and minimum conditions to get desired result.

Difference between request.getSession() and request.getSession(true)

Method with boolean argument :

  request.getSession(true);

returns new session, if the session is not associated with the request

  request.getSession(false);

returns null, if the session is not associated with the request.

Method without boolean argument :

  request.getSession();

returns new session, if the session is not associated with the request and returns the existing session, if the session is associated with the request.It won't return null.

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

How can I delete a file from a Git repository?

I tried a lot of the suggested options and none appeared to work (I won't list the various problems). What I ended up doing, which worked, was simple and intuitive (to me) was:

  1. move the whole local repo elsewhere
  2. clone the repo again from master to your local drive
  3. copy back the files/folder from your original copy in #1 back into the new clone from #2
  4. make sure that the problem large file is either not there or excluded in the .gitignore file
  5. do the usual git add/git commit/git push

Salt and hash a password in Python

passlib seems to be useful if you need to use hashes stored by an existing system. If you have control of the format, use a modern hash like bcrypt or scrypt. At this time, bcrypt seems to be much easier to use from python.

passlib supports bcrypt, and it recommends installing py-bcrypt as a backend: http://pythonhosted.org/passlib/lib/passlib.hash.bcrypt.html

You could also use py-bcrypt directly if you don't want to install passlib. The readme has examples of basic use.

see also: How to use scrypt to generate hash for password and salt in Python

What character represents a new line in a text area

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

If you use anything else you will cause issues with cut and paste on Windows platforms.

The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.

Interestingly, in spite of the Unix line end convention being \n, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n. Yes, it may not make a lot of sense, but that's history and evolving standards for you!

What underlies this JavaScript idiom: var self = this?

As others have explained, var self = this; allows code in a closure to refer back to the parent scope.

However, it's now 2018 and ES6 is widely supported by all major web browsers. The var self = this; idiom isn't quite as essential as it once was.

It's now possible to avoid var self = this; through the use of arrow functions.

In instances where we would have used var self = this:

function test() {
    var self = this;
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", function() {
        console.log(self.hello); // logs "world"
    });
};

We can now use an arrow function without var self = this:

function test() {
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", () => {
        console.log(this.hello); // logs "world"
    });
};

Arrow functions do not have their own this and simply assume the enclosing scope.

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

How to hide elements without having them take space on the page?

here's a different take on putting them back after display:none. don't use display:block/inline etc. Instead (if using javascript) set css property display to '' (i.e. blank)

How can I hide a TD tag using inline JavaScript or CSS?

We can hide the content inside a by using the following inline css:

<div style="visibility:hidden"></div>

for example:

<td><div style="visibility:hidden">Your Content Goes Here:</div></td>

how to find seconds since 1970 in java

Another option is to use the TimeUtils utility method:

TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)

How to get the current time in Google spreadsheet using script editor?

I considered with timezone in my Google Docs like this:

timezone = "GMT+" + new Date().getTimezoneOffset()/60
var date = Utilities.formatDate(new Date(), timezone, "yyyy-MM-dd HH:mm"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"

my script for Google docs

crop text too long inside div

Why not use relative units?

.cropText {
    max-width: 20em;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Android Viewpager as Image Slide Gallery

Image Viewer with ViewPager Implementation, check this project https://github.com/chiuki/android-swipe-image-viewer

Refer this discussion also Swiping images (not layouts) with viewpager

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

How to Populate a DataTable from a Stored Procedure

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

can we use xpath with BeautifulSoup?

BeautifulSoup has a function named findNext from current element directed childern,so:

father.findNext('div',{'class':'class_value'}).findNext('div',{'id':'id_value'}).findAll('a') 

Above code can imitate the following xpath:

div[class=class_value]/div[id=id_value]

Install Windows Service created in Visual Studio

Another possible problem (which I ran into):

Be sure that the ProjectInstaller class is public. To be honest, I am not sure how exactly I did it, but I added event handlers to ProjectInstaller.Designer.cs, like:

this.serviceProcessInstaller1.BeforeInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_BeforeInstall);

I guess during the automatical process of creating the handler function in ProjectInstaller.cs it changed the class definition from

public class ProjectInstaller : System.Configuration.Install.Installer

to

partial class ProjectInstaller : System.Configuration.Install.Installer

replacing the public keyword with partial. So, in order to fix it it must be

public partial class ProjectInstaller : System.Configuration.Install.Installer

I use Visual Studio 2013 Community edition.

Detect HTTP or HTTPS then force HTTPS in JavaScript

Hi i used this solution works perfectly.No Need to check, just use https.

<script language="javascript" type="text/javascript">
document.location="https:" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
</script>

MySQL - length() vs char_length()

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

How to test code dependent on environment variables using JUnit?

I think the cleanest way to do this is with Mockito.spy(). It's a bit more lightweight than creating a separate class to mock and pass around.

Move your environment variable fetching to another method:

@VisibleForTesting
String getEnvironmentVariable(String envVar) {
    return System.getenv(envVar);
}

Now in your unit test do this:

@Test
public void test() {
    ClassToTest classToTest = new ClassToTest();
    ClassToTest classToTestSpy = Mockito.spy(classToTest);
    Mockito.when(classToTestSpy.getEnvironmentVariable("key")).thenReturn("value");
    // Now test the method that uses getEnvironmentVariable
    assertEquals("changedvalue", classToTestSpy.methodToTest());
}

Request Permission for Camera and Library in iOS 10 - Info.plist

Great way of implementing Camera session in Swift 5, iOS 13

https://github.com/egzonpllana/CameraSession

Camera Session is an iOS app that tries to make the simplest possible way of implementation of AVCaptureSession.

Through the app you can find these camera session implemented:

  • Native camera to take a picture or record a video.
  • Native way of importing photos and videos.
  • The custom way to select assets like photos and videos, with an option to select one or more assets from the Library.
  • Custom camera to take a photo(s) or video(s), with options to hold down the button and record.
  • Separated camera permission requests.

The custom camera features like torch and rotate camera options.

Linux find file names with given string recursively

Use the find command,

find . -type f -name "*John*"

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

Lower mm means minutes, so

DateTime.Now.ToString("dd/MM/yyyy");  

or

DateTime.Now.ToString("d");  

or

DateTime.Now.ToShortDateString()

works.

Standard Date and Time Format Strings

Error: The type exists in both directories

In my case, I have to items with same name but different extensions in my project. One was accountRep.aspx and the other accountRep.rpt made by Crystal Report. Problem solved when I changed accountRep.rpt to accountReport.rpt

Check if checkbox is checked with jQuery

Something like this can help

togglecheckBoxs =  function( objCheckBox ) {

    var boolAllChecked = true;

    if( false == objCheckBox.checked ) {
        $('#checkAll').prop( 'checked',false );
    } else {
        $( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
            if( false == chkbox.checked ) {
                $('#checkAll').prop( 'checked',false );
                boolAllChecked = false;
            }
        });

        if( true == boolAllChecked ) {
            $('#checkAll').prop( 'checked',true );
        }
    }
}

Procedure or function !!! has too many arguments specified

In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.

Many developers will mistakenly use for loop or foreach and leave the SqlCommand to execute outside the loop, to avoid that make sure that you have like this code sample for example:

public static void Save(List<myClass> listMyClass)
    {
        using (var Scope = new System.Transactions.TransactionScope())
        {
            if (listMyClass.Count > 0)
            {
                for (int i = 0; i < listMyClass.Count; i++)
                {
                    SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Clear();

                    cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
                    cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
                    cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);

                    try
                    {
                        myConnection.Open();
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqe)
                    {
                        throw new Exception(sqe.Message);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        myConnection.Close();
                    }
                }
            }
            else
            {
                throw new Exception("List is empty");
            }

            Scope.Complete();
        }
    }

How can I set the Secure flag on an ASP.NET Session Cookie?

There are two ways, one httpCookies element in web.config allows you to turn on requireSSL which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.

Edit for clarity: Put this in <system.web>

<httpCookies requireSSL="true" />

How to change the Content of a <textarea> with JavaScript

If it's jQuery...

$("#myText").val('');

or

document.getElementById('myText').value = '';

Reference: Text Area Object

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

Control the dashed border stroke length and distance between strokes

I just recently had the same problem.

I managed to solve it with two absolutely positioned divs carrying the border (one for horizontal and one for vertical), and then transforming them. The outer box just needs to be relatively positioned.

<div class="relative">
    <div class="absolute absolute--fill overflow-hidden">
        <div class="absolute absolute--fill b--dashed b--red"
            style="
                border-width: 4px 0px 4px 0px;
                transform: scaleX(2);
        "></div>
        <div class="absolute absolute--fill b--dashed b--red"
            style="
                border-width: 0px 4px 0px 4px;
                transform: scaleY(2);
        "></div>
    </div>

    <div> {{Box content goes here}} </div>
</div>

Note: i used tachyons in this example, but i guess the classes are kind of self-explanatory.

Why are C++ inline functions in the header?

The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.

Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)

How to print a groupby object

I found a tricky way, just for brainstorm, see the code:

df['a'] = df['A']  # create a shadow column for MultiIndexing
df.sort_values('A', inplace=True)
df.set_index(["A","a"], inplace=True)
print(df)

the output:

             B
A     a
one   one    0
      one    1
      one    5
three three  3
      three  4
two   two    2

The pros is so easy to print, as it returns a dataframe, instead of Groupby Object. And the output looks nice. While the con is that it create a series of redundant data.

How to align an indented line in a span that wraps into multiple lines?

<!DOCTYPE html>
<html>
<body>

<span style="white-space:pre-wrap;">
Line no one
Line no two
And many more line.
This is Manik
End of Line
</span>

</body>
</html>

What is the correct way to create a single-instance WPF application?

Here is my 2 cents

 static class Program
    {
        [STAThread]
        static void Main()
        {
            bool createdNew;
            using (new Mutex(true, "MyApp", out createdNew))
            {
                if (createdNew) {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    var mainClass = new SynGesturesLogic();
                    Application.ApplicationExit += mainClass.tray_exit;
                    Application.Run();
                }
                else
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName).Where(process => process.Id != current.Id))
                    {
                        NativeMethods.SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }
            }
        }
    }

How to get value by class name in JavaScript or jquery?

If you get the the text inside the element use

Text()

$(".element-classname").text();

In your code:

$('.HOEnZb').text();

if you want get all the data including html Tags use:

html()

 $(".element-classname").html();

In your code:

$('.HOEnZb').html();

Hope it helps:)

How to use JavaScript with Selenium WebDriver Java

JavaScript With Selenium WebDriver

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

    public static WebDriver driver;
    public static void main(String[] args) {
        driver = new FirefoxDriver(); // This opens a window    
        String url = "----";


        /*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
        driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/

        JavascriptExecutor jse = (JavascriptExecutor) driver;       
        if (jse instanceof WebDriver) {
            //Launching the browser application
            jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");


//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();            
jse.executeScript("window.history.go(0)");
            jse.executeScript("window.history.go(-2)");
            jse.executeScript("window.history.forward(-2)");

            String title = (String)jse.executeScript("return document.title");
            System.out.println(" Title Of site : "+title);

            String domain = (String)jse.executeScript("return document.domain");
            System.out.println("Web Site Domain-Name : "+domain);

            // To get all NodeList[1052] document.querySelectorAll('*');  or document.all
            jse.executeAsyncScript("document.getElementsByTagName('*')");

            String error=(String) jse.executeScript("return window.jsErrors");
            System.out.println("Windowerrors  :   "+error);



            System.out.println("To Find the input tag position from top"); 
            ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
                    "var source = [];"+
                    "var inputs = document.getElementsByTagName('input');"+
                    "for(var i = 0; i < inputs.length; i++) { " +
                       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
                    "}"+
                    "return source"                 
                    );//inputs[i].offsetParent.offsetTop     inputs[i].type

            System.out.println("next");
            System.out.println("array : "+al);

            // (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
            Keys k = null;
            String selectAll = Keys.chord(Keys.CONTROL, "a");
            WebElement body = driver.findElement(By.tagName("body"));
            body.sendKeys(selectAll);

            // Search for text in Site. Gets all ViewSource content and checks their.
            if (driver.getPageSource().contains("login")) {
                System.out.println("Text present in Web Site");
            }

        Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
        System.out.println("Client Body Height : "+clent_height);

        // using selenium we con only execute script but not JS-functions.

    }
    driver.quit(); // to close browser
}

To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
        String js_TxtFile = ""; 
            while (sc.hasNext()) {          
                String[] s = sc.next().split("\r\n");   
                for (int i = 0; i < s.length; i++) {
                    js_TxtFile += s[i];
                    js_TxtFile += " ";
                }           
            }
        String title =  (String) jse.executeScript(js_TxtFile);
        System.out.println("Title  : "+title);

document.title & document.getElementById() is a property/method available in Browsers.

JsFile.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}

regular expression for DOT

. matches any character so needs escaping i.e. \., or \\. within a Java string (because \ itself has special meaning within Java strings.)

You can then use \.\. or \.{2} to match exactly 2 dots.

How to create a sleep/delay in nodejs that is Blocking?

It's pretty trivial to implement with native addon, so someone did that: https://github.com/ErikDubbelboer/node-sleep.git

How to set only time part of a DateTime variable in C#

I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...

You can specify 12/25/2010 4:58 PM by using

DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");

OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:

DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);

The ExistingTime.Date will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.

What does .class mean in Java?

In generics, an unknown type is represented by the wildcard character "?". Read here for official example.

Constructors in Go

Go has objects. Objects can have constructors (although not automatic constructors). And finally, Go is an OOP language (data types have methods attached, but admittedly there are endless definitions of what OOP is.)

Nevertheless, the accepted best practice is to write zero or more constructors for your types.

As @dystroy posted his answer before me finishing this answer, let me just add an alternative version of his example constructor, which I would probably write instead as:

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33} // <- 33: a very sensible default value
}

The reason I want to show you this version is that pretty often "inline" literals can be used instead of a "constructor" call.

a := NewThing("foo")
b := &Thing{"foo", 33}

Now *a == *b.

Eclipse Build Path Nesting Errors

I had the same problem even when I created a fresh project. I was creating the Java project within Eclipse, then mavenize it, then going into java build path properties removing src/ and adding src/main/java and src/test/java. When I run Maven update it used to give nested path error.
Then I finally realized -because I had not seen that entry before- there is a <sourceDirectory>src</sourceDirectory> line in pom file written when I mavenize it. It was resolved after removing it.

Get difference between 2 dates in JavaScript?

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

Git cli: get user info from username

You can try this to get infos like:

  • username: git config --get user.name
  • user email: git config --get user.email

There's nothing like "first name" and "last name" for the user.

Hope this will help.

Bootstrap col-md-offset-* not working

If you are ok with small tweak - we know that bootstrap works with a width of 12

<div class="row">
      <div class="col-md-1">
            Keep it blank it becomes left offset
      </div> 
      <div class="col-md-5">
      </div>
      <div class="col-md-5">
      </div>
      <div class="col-md-1">
            Keep it blank it becomes right offset
      </div
</div>

I am sure there is a better way to do this, but i was in a hurry so used this trick

Compare objects in Angular

Assuming that the order is the same in both objects, just stringify them both and compare!

JSON.stringify(obj1) == JSON.stringify(obj2);

How do you push just a single Git branch (and no other branches)?

So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.

To push the contents of foo to origin/master, you first need to set its upstream:

git checkout foo
git branch -u origin/master

Then you can push to this branch using:

git push origin HEAD:master

In the last command you can add --force to replace the entire history of origin/master with that of foo.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

"cannot resolve symbol R" in Android Studio

Take into account the following IDE functionalities:

  • Sync Project with gradle files
  • Build -> Clean Project
  • Build -> Rebuild Project
  • File -> Invalidate caches

My simple solution is:

  1. Check that there is no error line in the dependencies of the build.gradle of the app or in all the resource files in the /res directory; where some common errors are when the attribute values are left without references when using:
    • "@string/.."
    • "@style/.."
  2. Make sure you are not getting an error of the type Android resource linking failed when the project is rebuilt.
  3. Open the file that contains the line with the error Cannot resolve symbol 'R'
  4. Scrolling to the last line of the class with said error line
  5. Click on a position to the right of the closing key } of the class

In this way, the IDE alert dialog appears to perform the import of the R-class.

GL

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

how to create dynamic two dimensional array in java?

Since the number of columns is a constant, you can just have an List of int[].

    import java.util.*;
    //...

    List<int[]> rowList = new ArrayList<int[]>();

    rowList.add(new int[] { 1, 2, 3 });
    rowList.add(new int[] { 4, 5, 6 });
    rowList.add(new int[] { 7, 8 });

    for (int[] row : rowList) {
        System.out.println("Row = " + Arrays.toString(row));
    } // prints:
      // Row = [1, 2, 3]
      // Row = [4, 5, 6]
      // Row = [7, 8]

    System.out.println(rowList.get(1)[1]); // prints "5"

Since it's backed by a List, the number of rows can grow and shrink dynamically. Each row is backed by an int[], which is static, but you said that the number of columns is fixed, so this is not a problem.

Java check if boolean is null

In Java, null only applies to object references; since boolean is a primitive type, it cannot be assigned null.

It's hard to get context from your example, but I'm guessing that if hideInNav is not in the object returned by getProperties(), the (default value?) you've indicated will be false. I suspect this is the bug that you're seeing, as false is not equal to null, so hideNavigation is getting the empty string?

You might get some better answers with a bit more context to your code sample.

How do I execute a *.dll file

While many people have pointed out that you can't execute dlls directly and should use rundll32.exe to execute exported functions instead, here is a screenshot of an actual dll file running just like an executable:

enter image description here

While you cannot run dll files directly, I suspect it is possible to run them from another process using a WinAPI function CreateProcess:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx

How to count the number of set bits in a 32-bit integer?

This will also work fine :

int ans = 0;
while(num){
 ans += (num &1);
 num = num >>1;
}    
return ans;

Copying formula to the next row when inserting a new row

If you have a worksheet with many rows that all contain the formula, by far the easiest method is to copy a row that is without data (but it does contain formulas), and then "insert copied cells" below/above the row where you want to add. The formulas remain. In a pinch, it is OK to use a row with data. Just clear it or overwrite it after pasting.

How to remove blank lines from a Unix file

with awk

awk 'NF > 0' filename

Convert PDF to PNG using ImageMagick

when you set the density to 96, doesn't it look good?

when i tried it i saw that saving as jpg resulted with better quality, but larger file size

Add Text on Image using PIL

First install pillow

pip install pillow

Example

from PIL import Image, ImageDraw, ImageFont

image = Image.open('Focal.png')
width, height = image.size 

draw = ImageDraw.Draw(image)

text = 'https://devnote.in'
textwidth, textheight = draw.textsize(text)

margin = 10
x = width - textwidth - margin
y = height - textheight - margin

draw.text((x, y), text)

image.save('devnote.png')

# optional parameters like optimize and quality
image.save('optimized.png', optimize=True, quality=50)

Local file access with JavaScript

If you're deploying on Windows, the Windows Script Host offers a very useful JScript API to the file system and other local resources. Incorporating WSH scripts into a local web application may not be as elegant as you might wish, however.

How do I capitalize first letter of first name and last name in C#?

CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");

css 'pointer-events' property alternative for IE

Use OnClientClick = "return false;"

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Why not negate the padding added by container-fluid by marking left and right padding as 0?

<div class="container-fluid pl-0 pr-0">

even better way? no padding at all at the container level (cleaner)

<div class="container-fluid pl-0 pr-0">

Bootstrap 3 Gutter Size

@Bass Jobsen and @ElwoodP attempted to answer this question in reverse--giving the outer margins the same DOUBLE size as the gutters. The OP (and me, as well) was searching for a way to have a SINGLE size gutter in all places. Here are the correct CSS adjustments to do so:

.row {
    margin-left: -7px;
    margin-right: -7px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
    padding-left: 7px;
    padding-right: 7px;
}
.container {
    padding-left: 14px;
    padding-right: 14px;
}

This leaves a 14px gutter and outside margin in all places.

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

IIS Manager in Windows 10

Launch Windows Features On/Off and select your IIS options for installation.

For custom site configuration, ensure IIS Management Console is marked for installation under Web Management Tools.

How do I position one image on top of another in HTML?

You can absolutely position pseudo elements relative to their parent element.

This gives you two extra layers to play with for every element - so positioning one image on top of another becomes easy - with minimal and semantic markup (no empty divs etc).

markup:

<div class="overlap"></div>

css:

.overlap
{
    width: 100px;
    height: 100px;
    position: relative;
    background-color: blue;
}
.overlap:after
{
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    top: 5px;
    left: 5px;
    background-color: red;
}

Here's a LIVE DEMO

Jaxb, Class has two properties of the same name

You need to configure class ModeleREP as well with @XmlAccessorType(XmlAccessType.FIELD) as you did with class TimeSeries.

Have al look at OOXS

Angularjs - ng-cloak/ng-show elements blink

None of the solutions listed above worked for me. I then decided to look at the actual function and realised that when “$scope.watch ” was fired, it was putting a value in the name field which was not meant to be the case. So in the code I set and oldValue and newValue then

$scope.$watch('model.value', function(newValue, oldValue) {
if (newValue !== oldValue) {
validateValue(newValue);
}
});

Essentially when scope.watch is fired in this case, AngularJS monitors the changes to the name variable (model.value)

Hide a EditText & make it visible by clicking a menu

Try phoneNumber.setVisibility(View.GONE);

How to check that a string is parseable to a double?

Google's Guava library provides a nice helper method to do this: Doubles.tryParse(String). You use it like Double.parseDouble but it returns null rather than throwing an exception if the string does not parse to a double.

Subset a dataframe by multiple factor levels

Here's another:

data[data$Code == "A" | data$Code == "B", ]

It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,

data[Code == "A" | Code == "B", ]

also works, which is one of the really useful things about R.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

Converting a number with comma as decimal point to float

from PHP manual:

str_replace — Replace all occurrences of the search string with the replacement string

I would go down that route, and then convert from string to float - floatval

How to 'foreach' a column in a DataTable using C#?

Something like this:

 DataTable dt = new DataTable();

 // For each row, print the values of each column.
    foreach(DataRow row in dt .Rows)
    {
        foreach(DataColumn column in dt .Columns)
        {
            Console.WriteLine(row[column]);
        }
    }

http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx

Why AVD Manager options are not showing in Android Studio

Fixed by enabling Groovy plugin. Enabling it also enables the "SDK manager" option.

  1. Ctr+Shift+A
  2. Write "Plugins"
  3. Search for "Groovy"
  4. Enable it and restart Android Studio.

Postgresql SELECT if string contains

A proper way to search for a substring is to use position function instead of like expression, which requires escaping %, _ and an escape character (\ by default):

SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;

How to make circular background using css?

Here is a solution for doing it with a single div element with CSS properties, border-radius does the magic.

CSS:

.circle{
    width:100px;
    height:100px;
    border-radius:50px;
    font-size:20px;
    color:#fff;
    line-height:100px;
    text-align:center;
    background:#000
}

HTML:

<div class="circle">Hello</div>

Facebook Open Graph not clearing cache

  1. Go to http://developers.facebook.com/tools/debug
  2. Enter the URL following by fbrefresh=CAN_BE_ANYTHING

Examples:

  1. http://www.example.com?fbrefresh=CAN_BE_ANYTHING
  2. http://www.example.com?postid=1234&fbrefresh=CAN_BE_ANYTHING
  3. OR visit: http://developers.facebook.com/tools/debug/og/object?q=http://www.example.com/?p=3568&fbrefresh=89127348912

I was having the same issue last night, and I got this solution from some website.

Facebook saves your cache thumbnail. It won't refresh even if you delete the thumnail/image from your server. But Facebook allows you to refresh by using fbrefresh

I hope this helps.

How to get href value using jQuery?

if the page have one <a> It Works,but,many <a> ,have to use var href = $(this).attr('href');

Why "no projects found to import"?

Reason : your ID is not able to find the .project file. This happens in git commit where many time people don't push .project file

Solution : If you have maven install then use following stapes

  1. mvn eclipse:clean
  2. mvn eclipse:eclipse

Enjoy!

Add Custom Headers using HttpWebRequest

IMHO it is considered as malformed header data.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

The second way is true.

How to compress a String in Java?

When you create a String, you can think of it as a list of char's, this means that for each character in your String, you need to support all the possible values of char. From the sun docs

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

If you have a reduced set of characters you want to support you can write a simple compression algorithm, which is analogous to binary->decimal->hex radix converstion. You go from 65,536 (or however many characters your target system supports) to 26 (alphabetical) / 36 (alphanumeric) etc.

I've used this trick a few times, for example encoding timestamps as text (target 36 +, source 10) - just make sure you have plenty of unit tests!

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

How to use enums in C++

This should not work in C++:

Days.Saturday

Days is not a scope or object that contains members you can access with the dot operator. This syntax is just a C#-ism and is not legal in C++.

Microsoft has long maintained a C++ extension that allows you to access the identifiers using the scope operator:

enum E { A, B, C };

A;
E::B; // works with Microsoft's extension

But this is non-standard before C++11. In C++03 the identifiers declared in an enum exist only in the same scope as the enum type itself.

A;
E::B; // error in C++03

C++11 makes it legal to qualify enum identifiers with the enum name, and also introduces enum classes, which create a new scope for the identifiers instead of placing them in the surrounding scope.

A;
E::B; // legal in C++11

enum class F { A, B, C };

A; // error
F::B;

How can I merge two MySQL tables?

You can also try:

INSERT IGNORE
  INTO table_1 
SELECT *
  FROM table_2
     ;

which allows those rows in table_1 to supersede those in table_2 that have a matching primary key, while still inserting rows with new primary keys.

Alternatively,

REPLACE
   INTO table_1
 SELECT *
   FROM table_2
      ;

will update those rows already in table_1 with the corresponding row from table_2, while inserting rows with new primary keys.

"No rule to make target 'install'"... But Makefile exists

I also came across the same error. Here is the fix: If you are using Cmake-GUI:

  1. Clean the cache of the loaded libraries in Cmake-GUI File menu.
  2. Configure the libraries.
  3. Generate the Unix file.

If you missed the 3rd step:

*** No rule to make target `install'. Stop.

error will occur.

'IF' in 'SELECT' statement - choose output value based on column values

SELECT id, 
       IF(type = 'P', amount, amount * -1) as amount
FROM report

See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.

Additionally, you could handle when the condition is null. In the case of a null amount:

SELECT id, 
       IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report

The part IFNULL(amount,0) means when amount is not null return amount else return 0.

How do I determine the size of my array in C?

You can use the & operator. Here is the source code:

#include<stdio.h>
#include<stdlib.h>
int main(){

    int a[10];

    int *p; 

    printf("%p\n", (void *)a); 
    printf("%p\n", (void *)(&a+1));
    printf("---- diff----\n");
    printf("%zu\n", sizeof(a[0]));
    printf("The size of array a is %zu\n", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));


    return 0;
};

Here is the sample output

1549216672
1549216712
---- diff----
4
The size of array a is 10

'mat-form-field' is not a known element - Angular 5 & Material2

When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts

Please import below:

import { MatInputModule } from '@angular/material';

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

HQL Hibernate INNER JOIN

Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team, of type int, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:

@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;

Then, the following query will work flawlessly:

select e from Employee e inner join e.team

Which will load all the employees, except those that aren't associated to any team.

The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss, id_profession).

It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.

Event handlers for Twitter Bootstrap dropdowns?

Without having to change your button group at all, you can do the following. Below, I assume your dropdown button has an id of fldCategory.

<script type="text/javascript">

$(document).ready(function(){

  $('#fldCategory').parent().find('UL LI A').click(function (e) {
    var sVal = e.currentTarget.text;
    $('#fldCategory').html(sVal + ' <span class="caret"></span>');
    console.log(sVal);
  });

});

</script>

Now, if you set the .btn-group of this item itself to have the id of fldCategory, that's actually more efficient jQuery and runs a little faster:

<script type="text/javascript">

$(document).ready(function(){

  $('#fldCategory UL LI A').click(function (e) {
    var sVal = e.currentTarget.text;
    $('#fldCategory BUTTON').html(sVal + ' <span class="caret"></span>');
    console.log(sVal);
  });

});

</script>

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Bootstrap 3: Text overlay on image

try the following example. Image overlay with text on image. demo

<div class="thumbnail">
  <img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..."   />
  <div class="caption post-content">  
  </div> 
  <div class="details">
    <h3>Robots!</h3>
    <p>Lorem ipsum dolor sit amet</p>   
  </div>  
</div>

css

.post-content {
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
    opacity: 0.5;
    top:0;
    left:0;
    min-width: 500px;
    min-height: 500px; 
    position: absolute;
    color: #ffffff; 
}

.thumbnail{
    position:relative;

}
.details {
    position: absolute; 
    z-index: 2; 
    top: 0;
    color: #ffffff; 
}

SQL update statement in C#

string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account  SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();

Reset Entity-Framework Migrations

In EF6

  1. Delete all your files in 'migrations' folder... But not the 'initial create' or 'config'.
  2. Delete the database.
  3. Now run Add-Migration Initial.
  4. Now you can 'update-database' and all will be well.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET

4.5.2 didn't work for us with the above problem, while 4.6.1 was OK

If you need to keep the .NET version, then set

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

How do I find the current executable filename?

Environment.GetCommandLineArgs()[0]

How to find all duplicate from a List<string>?

I'm assuming each string in your list contains several words, let me know if that's incorrect.

List<string> list = File.RealAllLines("foobar.txt").ToList();

var words = from line in list
            from word in line.Split(new[] { ' ', ';', ',', '.', ':', '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
            select word;

var duplicateWords = from w in words
                     group w by w.ToLower() into g
                     where g.Count() > 1
                     select new
                     {
                         Word = g.Key,
                         Count = g.Count()
                     }

How to get the new value of an HTML input after a keypress has modified it?

Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.

As you will see from the table, the keypress and change event do not have uniform support whereas the keyup event does.

Also make sure you attach the event handler using a cross-browser-compatible method...

PHP CURL & HTTPS

One important note, the solution mentioned above will not work on local host, you have to upload your code to server and then it will work. I was getting no error, than bad request, the problem was I was using localhost (test.dev,myproject.git). Both solution above work, the solution that uses SSL cert is recommended.

  1. Go to https://curl.haxx.se/docs/caextract.html, download the latest cacert.pem. Store is somewhere (not in public folder - but will work regardless)

  2. Use this code

".$result; //echo "
Path:".$_SERVER['DOCUMENT_ROOT'] . "/ssl/cacert.pem"; // this is for troubleshooting only ?>
  1. Upload the code to live server and test.

Setting up connection string in ASP.NET to SQL SERVER

I found this very difficult to get an answer to but eventually figured it out. So I will write the steps below.

  1. Before you setup your connection string in code, ensure you actually can access your database. Start obviously by logging into the database server using SSMS (Sql Server Management Studio or it's equivalent in other databases) locally to ensure you have access using whatever details you intend to use.

  2. Next (if needed), if you are trying to access the database on a separate server, ensure you can do likewise in SSMS. So setup SSMS on a computer and ensure you can access the server with the username and password to that database server.

If you don't get the above 2 right, you are simply wasting your time as you cant access the database. This can either be because the user you setup is wrong, doesn't have remote access enabled (if needed), or the ports are not opened (if needed), among many other reasons but these being the most common.

Once you have verified that you can access the database using SSMS. The next step, just for the sake of automating the process and avoiding mistakes, is to let the system do the work for you.

  1. Start up an empty project, add your choice of Linq to SQL or Dataset (EF is good but the connection string is embedded inside of an EF con string, I want a clean one), and connect to your database using the details verified above in the con string wizzard. Add any table and save the file.

Now go into the web config, and magically, you will see nice clean working connection string there with all the details you need.


{ Below was part of an old post so you can ignore this, I leave it in for reference as its the most basic way to access the database from only code behind. Please scroll down and continue from step 2 below. }

Lets assume the above steps start you off with something like the following as your connection string in the code behind:

string conString = "Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;";

This step is very important. Make sure you have the above format of connection string working before taking the following steps. Make sure you actually can access your data using some form of sql command text which displays some data from a table in labels or text boses or whatever, as this is the simplest way to do a connection string.

Once you are sure the above style works its now time to take the next steps:

1. Export your string literal (the stuff in the quotes, including the quotes) to the following section of the web.config file (for multiple connection strings, just do multiple lines:

<configuration>
    <connectionStrings>
        <add name="conString" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
        <add name="conString2" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
        <add name="conString3" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

{ The above was part of an old post, after doing the top 3 steps this whole process will be done for you, so you can ignore it. I just leave it here for my own reference. }


2. Now add the following line of code to the C# code behind, prefrably just under the class definition (i.e. not inside a method). This points to the root folder of your project. Essentially it is the project name. This is usually the location of the web.config file (in this case my project is called MyProject.

static Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/MyProject");

3. Now add the following line of code to the C# code behind. This sets up a string constant to which you can refer in many places throughout your code should you need a conString in different methods.

const string CONSTRINGNAME = "conString";

4. Next add the following line of code to the C# code behind. This gets the connection string from the web.config file with the name conString (from the constant above)

ConnectionStringSettings conString = rootWebConfig.ConnectionStrings.ConnectionStrings[CONSTRINGNAME];

5. Finally, where you origionally would have had something similar to this line of code:

SqlConnection con = new SqlConnection(conString)

you will replace it with this line of code:

SqlConnection con = new SqlConnection(conString.ConnectionString)

After doing these 5 steps your code should work as it did before. Hense the reason you test the constring first in its origional format so you know if it is a problem with the connection string or if it is a problem with the code.

I am new to C#, ASP.Net and Sql Server. So I am sure there must be a better way to do this code. I also would appreicate feedback on how to improve these steps if possible. I have looked all over for something like this but I eventually figured it out after many weeks of hard work. Looking at it myself, I still think, there must be an easier way.

I hope this is helpful.

How to display my application's errors in JSF?

In case anyone was curious, I was able to figure this out based on all of your responses combined!

This is in the Facelet:

<h:form id="myform">
  <h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
  <h:message class="error" for="newPassword1" id="newPassword1Error" />
  <h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
  <h:message class="error" for="newPassword2" id="newPassword2Error" />
  <h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>

This is in the continueButton() method:

FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));

And it works! Thanks for the help!

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);

Get size of folder or file

public static long getFolderSize(File dir) {
    long size = 0;
    for (File file : dir.listFiles()) {
        if (file.isFile()) {
            System.out.println(file.getName() + " " + file.length());
            size += file.length();
        }
        else
            size += getFolderSize(file);
    }
    return size;
}

Get a CSS value with JavaScript

Cross-browser solution to checking CSS values without DOM manipulation:

function get_style_rule_value(selector, style)
{
 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
   if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector)
   {
    return myrules[j].style[style];
   }
  }
 }
};

Usage:

get_style_rule_value('.chart-color', 'backgroundColor')

Sanitized version (forces selector input to lowercase, and allows for use case without leading ".")

function get_style_rule_value(selector, style)
{
 var selector_compare=selector.toLowerCase();
 var selector_compare2= selector_compare.substr(0,1)==='.' ?  selector_compare.substr(1) : '.'+selector_compare;

 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
    if (myrules[j].selectorText)
    {
     var check = myrules[j].selectorText.toLowerCase();
     switch (check)
     {
      case selector_compare  :
      case selector_compare2 : return myrules[j].style[style];
     }
    }
   }
  }
 }

UITableViewCell, show delete button on swipe

During startup in (-viewDidLoad or in storyboard) do:

self.tableView.allowsMultipleSelectionDuringEditing = NO;

Override to support conditional editing of the table view. This only needs to be implemented if you are going to be returning NO for some items. By default, all items are editable.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
    }    
}

How to remove responsive features in Twitter Bootstrap 3?

Source from: http://getbootstrap.com/getting-started/#disable-responsive

  1. Omit the viewport <meta> mentioned in the CSS docs
  2. Override the width on the .container for each grid tier with a single width, for example width: 970px !important; Be sure that this comes after the default Bootstrap CSS. You can optionally avoid the !important with media queries or some selector-fu.
  3. If using navbars, remove all navbar collapsing and expanding behavior.
  4. For grid layouts, use .col-xs-* classes in addition to, or in place of, the medium/large ones. Don't worry, the extra-small device grid scales to all resolutions.

How to add and remove classes in Javascript without jQuery

The following 3 functions work in browsers which don't support classList:

function hasClass(el, className)
{
    if (el.classList)
        return el.classList.contains(className);
    return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}

function addClass(el, className)
{
    if (el.classList)
        el.classList.add(className)
    else if (!hasClass(el, className))
        el.className += " " + className;
}

function removeClass(el, className)
{
    if (el.classList)
        el.classList.remove(className)
    else if (hasClass(el, className))
    {
        var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
        el.className = el.className.replace(reg, ' ');
    }
}

https://jaketrent.com/post/addremove-classes-raw-javascript/

Fetch the row which has the Max value for a column

check this link if your questions seems similar to that page then i would suggest you the following query which will give the solution for that link

select distinct sno,item_name,max(start_date) over(partition by sno),max(end_date) over(partition by sno),max(creation_date) over(partition by sno), max(last_modified_date) over(partition by sno) from uniq_select_records order by sno,item_name asc;

will given accurate results related to that link

Can you set a border opacity in CSS?

try this:

<h2>Snippet for making borders transparent</h2>
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.
    Mauris massa. Vestibulum lacinia arcu eget nulla. <b>Lorem ipsum dolor sit amet, consectetur adipiscing elit</b>. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim
    lacinia nunc. <i>Lorem ipsum dolor sit amet, consectetur adipiscing elit</i>. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor.
    <i>Lorem ipsum dolor sit amet, consectetur adipiscing elit</i>. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod
    in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis
    turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. <b>Nam nec ante</b>. Suspendisse in justo eu magna luctus suscipit. Sed lectus. <i>Sed convallis tristique sem</i>.
    Integer euismod lacus luctus magna. <b>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos</b>. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum
    ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc,
    viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. <b>Suspendisse in justo eu magna luctus suscipit</b>. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. </p>
</div>
<div id="transparentBorder">
  This &lt;div&gt; has transparent borders.
</div>

And here comes our magical CSS..

* {
  padding: 10pt;
  font: 13px/1.5 Helvetica Neue, Arial, Helvetica, 'Liberation Sans', FreeSans, sans-serif;
}

b {
  font-weight: bold;
}

i {
  font-style: oblique;
}

H2 {
  font-size: 2em;
}

div[id='transparentBorder'] {
  height: 100px;
  width: 200px;
  padding: 10px;
  position: absolute;
  top: 40%;
  left: 30%;
  text-align: center;
  background: Black;
  border-radius: 4px;
  border: 10pt solid rgba(0, 0, 0, 0.5);
  -moz-background-clip: border;
  /* Firefox 3.6 */
  -webkit-background-clip: border;
  /* Safari 4? Chrome 6? */
  background-clip: border-box;
  /* Firefox 4, Safari 5, Opera 10, IE 9 */
  -moz-background-clip: padding;
  /* Firefox 3.6 */
  -webkit-background-clip: padding;
  /* Safari 4? Chrome 6? */
  background-clip: padding-box;
  /* Firefox 4, Safari 5, Opera 10, IE 9 */
  text-align: center;
  margin: 0;
  color: #fff;
  cursor: pointer;
}

Check out the Demo here.

How to put a tooltip on a user-defined function

I know you've accepted an answer for this, but there's now a solution that lets you get an intellisense style completion box pop up like for the other excel functions, via an Excel-DNA add in, or by registering an intellisense server inside your own add in. See here.

Now, i prefer the C# way of doing it - it's much simpler, as inside Excel-DNA, any class that implements IExcelAddin is picked up by the addin framework and has AutoOpen() and AutoClose() run when you open/close the add in. So you just need this:

namespace MyNameSpace {
    public class Intellisense : IExcelAddIn {
        public void AutoClose() {
        }
        public void AutoOpen() {
            IntelliSenseServer.Register();
        }
    }
}

and then (and this is just taken from the github page), you just need to use the ExcelDNA annotations on your functions:

[ExcelFunction(Description = "A useful test function that adds two numbers, and returns the sum.")]
public static double AddThem(
    [ExcelArgument(Name = "Augend", Description = "is the first number, to which will be added")] 
    double v1,
    [ExcelArgument(Name = "Addend", Description = "is the second number that will be added")]     
    double v2)
{
    return v1 + v2;
}

which are annotated using the ExcelDNA annotations, the intellisense server will pick up the argument names and descriptions.

enter image description here enter image description here

There are examples for using it with just VBA too, but i'm not too into my VBA, so i don't use those parts.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

How do I install cygwin components from the command line?

For a more convenient installer, you may want to use apt-cyg as your package manager. Its syntax similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps

wget https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg
chmod +x apt-cyg
mv apt-cyg /usr/local/bin

Now that apt-cyg is installed. Here are few examples of installing some packages

apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

Finding the second highest number in array

public class secondLargestElement 
{
    public static void main(String[] args) 
    {
        int []a1={1,0};
        secondHigh(a1);
    }

    public static void secondHigh(int[] arr)
    {
        try
        {
            int highest,sec_high;
            highest=arr[0];
            sec_high=arr[1];

                for(int i=1;i<arr.length;i++)
                {
                    if(arr[i]>highest)
                    {           
                        sec_high=highest;
                        highest=arr[i]; 
                    }
                    else 
                    // The first condition before the || is to make sure that second highest is not actually same as the highest , think 
                        // about {5,4,5}, you don't want the last  5 to be reported as the sec_high
                        // The other half after || says if the first two elements are same then also replace the sec_high with incoming integer
                        // Think about {5,5,4}
                    if(arr[i]>sec_high && arr[i]<highest || highest==sec_high)
                        sec_high=arr[i];
                }
            //System.out.println("high="+highest +"sec"+sec_high);
            if(highest==sec_high)
                System.out.println("All the elements in the input array are same");
             else
                 System.out.println("The second highest element in the array is:"+ sec_high);

         }

        catch(ArrayIndexOutOfBoundsException e)
        {
        System.out.println("Not enough elements in the array");
        //e.printStackTrace();
        }
    }
}

How do I create a constant in Python?

I've recently found a very succinct update to this which automatically raises meaningful error messages and prevents access via __dict__:

class CONST(object):
    __slots__ = ()
    FOO = 1234

CONST = CONST()

# ----------

print(CONST.FOO)    # 1234

CONST.FOO = 4321              # AttributeError: 'CONST' object attribute 'FOO' is read-only
CONST.__dict__['FOO'] = 4321  # AttributeError: 'CONST' object has no attribute '__dict__'
CONST.BAR = 5678              # AttributeError: 'CONST' object has no attribute 'BAR'

We define over ourselves as to make ourselves an instance and then use slots to ensure that no additional attributes can be added. This also removes the __dict__ access route. Of course, the whole object can still be redefined.

Edit - Original solution

I'm probably missing a trick here, but this seems to work for me:

class CONST(object):
    FOO = 1234

    def __setattr__(self, *_):
        pass

CONST = CONST()

#----------

print CONST.FOO    # 1234

CONST.FOO = 4321
CONST.BAR = 5678

print CONST.FOO    # Still 1234!
print CONST.BAR    # Oops AttributeError

Creating the instance allows the magic __setattr__ method to kick in and intercept attempts to set the FOO variable. You could throw an exception here if you wanted to. Instantiating the instance over the class name prevents access directly via the class.

It's a total pain for one value, but you could attach lots to your CONST object. Having an upper class, class name also seems a bit grotty, but I think it's quite succinct overall.

How to stop IIS asking authentication for default website on localhost

It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.

I did it and my problem solved.

How to import the class within the same directory or sub directory?

I'm not sure why this work but using Pycharm build from file_in_same_dir import class_name

The IDE complained about it but it seems it still worked. I'm using Python 3.7

tsc is not recognized as internal or external command

In the VSCode file tasks.json, the "command": "tsc" will try to find the tsc windows command script in some folder that it deems to be your modules folder.

If you know where the command npm install -g typescript or npm install typescript is saving to, I would recommend replacing:

"command": "tsc"

with

"command": "D:\\Projects\\TS\\Tutorial\\node_modules\\.bin\\tsc"

where D:\\...\\bin is the folder that contains my tsc windows executable

Will determine where my vscode is natively pointing to right now to find the tsc and fix it I guess.

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;

SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;

An SQLfiddle to test with.

Angular 2 - Redirect to an external URL and open in a new tab

var url = "https://yourURL.com";
var win = window.open(url, '_blank');
    win.opener = null;
    win.focus();

This will resolve the issue, here you don't need to use DomSanitizer. Its work for me

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

Getting selected value of a combobox

The problem you have with the SelectedValue is not converting into integer. This is the main problem so usinge the following code snippet will help you:

int selectedValue;
bool parseOK = Int32.TryParse(cmb.SelectedValue.ToString(), out selectedValue);

Pass variables between two PHP pages without using a form or the URL of page

Have you tried adding both to $_SESSION?

Then at the top of your page2.php just add:

<?php
session_start();

MySQL Orderby a number, Nulls last

SELECT * FROM tablename WHERE visible=1 ORDER BY CASE WHEN `position` = 0 THEN 'a' END , position ASC

Scanf/Printf double variable C

As far as I read manual pages, scanf says that 'l' length modifier indicates (in case of floating points) that the argument is of type double rather than of type float, so you can have 'lf, le, lg'.

As for printing, officially, the manual says that 'l' applies only to integer types. So it might be not supported on some systems or by some standards. For instance, I get the following error message when compiling with gcc -Wall -Wextra -pedantic

a.c:6:1: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]

So you may want to doublecheck if your standard supports the syntax.

To conclude, I would say that you read with '%lf' and you print with '%f'.

Change NULL values in Datetime format to empty string

declare @mydatetime datetime
set @mydatetime = GETDATE() -- comment out for null value
--set @mydatetime = GETDATE()

select 
case when @mydatetime IS NULL THEN ''
else convert(varchar(20),@mydatetime,120)
end as converted_date

In this query, I worked out the result came from current date of the day.

Programmatically select a row in JTable

It is an old post, but I came across this recently

Selecting a specific interval

As @aleroot already mentioned, by using

table.setRowSelectionInterval(index0, index1);

You can specify an interval, which should be selected.

Adding an interval to the existing selection

You can also keep the current selection, and simply add additional rows by using this here

table.getSelectionModel().addSelectionInterval(index0, index1);

This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.

SELECT CONVERT(VARCHAR(10), GETDATE(), 110) what is the meaning of 110 here?

That number indicates Date and Time Styles

You need to look at CAST and CONVERT (Transact-SQL). Here you can find the meaning of all these Date and Time Styles.

Styles with century (e.g. 100, 101 etc) means year will come in yyyy format. While styles without century (e.g. 1,7,10) means year will come in yy format.

You can also refer to SQL Server Date Formats. Here you can find all date formats with examples.

How to set environment variables in PyCharm?

None of the above methods worked for me. If you are on Windows, try this on PyCharm terminal:

setx YOUR_VAR "VALUE"

You can access it in your scripts using os.environ['YOUR_VAR'].

How to check if a column exists in a SQL Server table?

This worked for me in SQL 2000:

IF EXISTS 
(
    SELECT * 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE table_name = 'table_name' 
    AND column_name = 'column_name'
)
BEGIN
...
END