Programs & Examples On #Directory security

Custom li list-style with font-awesome icon

The CSS Lists and Counters Module Level 3 introduces the ::marker pseudo-element. From what I've understood it would allow such a thing. Unfortunately, no browser seems to support it.

What you can do is add some padding to the parent ul and pull the icon into that padding:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
  padding: 0;_x000D_
}_x000D_
li {_x000D_
  padding-left: 1.3em;_x000D_
}_x000D_
li:before {_x000D_
  content: "\f00c"; /* FontAwesome Unicode */_x000D_
  font-family: FontAwesome;_x000D_
  display: inline-block;_x000D_
  margin-left: -1.3em; /* same as padding-left set on li */_x000D_
  width: 1.3em; /* same as padding-left set on li */_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">_x000D_
<ul>_x000D_
  <li>Item one</li>_x000D_
  <li>Item two</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Adjust the padding/font-size/etc to your liking, and that's it. Here's the usual fiddle: http://jsfiddle.net/joplomacedo/a8GxZ/

=====

This works with any type of iconic font. FontAwesome, however, provides their own way to deal with this 'problem'. Check out Darrrrrren's answer below for more details.

How to check if a String is numeric in Java

String text="hello 123";
if(Pattern.matches([0-9]+))==true
System.out.println("String"+text);

Resetting MySQL Root Password with XAMPP on Localhost

For me much better way is to do it using terminal rather then PhpMyAdmin UI.

The answer is copied from "https://gist.github.com/susanBuck/39d1a384779f3d596afb19fcad6b598c" which I have tried and it works always, try it out..

  • Open C:\xampp\mysql\bin\my.ini (MySQL config file)
  • Find the line [mysqld] and right below it add skip-grant-tables. Example:

    [mysqld] skip-grant-tables port= 3306 socket = "C:/xampp/mysql/mysql.sock" basedir = "C:/xampp/mysql" tmpdir = "C:/xampp/tmp" [...etc...]

  • This should allow you to access MySQL if you don't know your password.

  • Stop and start MySQL from XAMPP to make this change take effect.
  • Next, in command line, connect to MySQL:

C:\xampp\mysql\bin\mysql.exe --user=root

  • Once in MySQL command line "select" the mysql database:

USE mysql;

  • Then, the following command will list all your MySQL users:

SELECT * FROM user \G;

  • You can scan through the rows to see what the root user's password is set to. There will be a few root users listed, with different hosts.
  • To set root user's to have a password of your choice, run this command:

UPDATE user SET password = PASSWORD('secret_pass') WHERE user = 'root';

  • -OR- To set all root user's to have a blank password, run this command:

UPDATE user SET password = '' WHERE user = 'root';

When you're done, run exit; to exit the MySQL command line.

Next, re-enable password checking by removing skip-grant-tables from C:\xampp\mysql\bin\my.ini.

Save changes, restart MySQL from XAMPP.

How to compare LocalDate instances Java 8

LocalDate ld ....;
LocalDateTime ldtime ...;

ld.isEqual(LocalDate.from(ldtime));

Android: Share plain text using intent (to all messaging apps)

100 % Working Code For Gmail Share

    Intent intent = new Intent (Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Any subject if you want");
    intent.setPackage("com.google.android.gm");
    if (intent.resolveActivity(getPackageManager())!=null)
        startActivity(intent);
    else
        Toast.makeText(this,"Gmail App is not installed",Toast.LENGTH_SHORT).show();

How to change navigation bar color in iOS 7 or 6?

Insert the below code in didFinishLaunchingWithOptions() in AppDelegate.m

[[UINavigationBar appearance] setBarTintColor:[UIColor
    colorWithRed:26.0/255.0 green:184.0/255.0 blue:110.0/255.0 alpha:1.0]];

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

Python installation folder > Lib > idlelib > idle.pyw

Double click on it and you're good to go.

Android Failed to install HelloWorld.apk on device (null) Error

When it shows the red writing - the error , don't close the emulator - leave it as is and run the application again.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

In my case checking the check-box

"Copy project into workspace"

did the trick.

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

There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.

The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.

body {
    position:absolute;
    width:1000px;
    left: 50%;
    margin-left:-500px;
}

Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.

Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.

But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.

The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:

// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;

jQuery(document).ready(function () {
    $(document).mousemove(function (e) {
        var bodyOffsets = document.body.getBoundingClientRect();
        tempX = e.pageX - bodyOffsets.left;
        tempY = e.pageY;
    });
}) 

Phew. That took me a while to fix ! I hope this is useful to other developers !

Which JRE am I using?

The following command will tell you a lot of information about your java version, including the vendor:

java -XshowSettings:properties -version

It works on Windows, Mac, and Linux.

How can I get the key value in a JSON object?

When you parse the JSON representation, it'll become a JavaScript array of objects.

Because of this, you can use the .length property of the JavaScript array to see how many elements are contained, and use a for loop to enumerate it.

How to parse the AndroidManifest.xml file inside an .apk package

You can use axml2xml.pl tool developed a while ago within android-random project. It will generate the textual manifest file (AndroidManifest.xml) from the binary one.

I'm saying "textual" and not "original" because like many reverse-engineering tools this one isn't perfect and the result will not be complete. I presume either it was never feature complete or simply not forward-compatible (with newer binary encoding scheme). Whatever the reason, axml2xml.pl tool will not be able to extract all the attribute values correctly. Such attributes are minSdkVersion, targetSdkVersion and basically all attributes that are referencing resources (like strings, icons, etc.), i.e. only class names (of activities, services, etc.) are extracted correctly.

However, you can still find these missing information by running aapt tool on the original Android app file (.apk):

aapt l -a <someapp.apk>

Sort a list alphabetically

There are two ways:

Without LINQ: yourList.Sort();

With LINQ: yourList.OrderBy(x => x).ToList()

You will find more information in: https://www.dotnetperls.com/sort

How do I make a composite key with SQL Server Management Studio?

Open up the table designer in SQL Server Management Studio (right-click table and select 'Design')

Holding down the Ctrl key highlight two or more columns in the left hand table margin

Hit the little 'Key' on the standard menu bar at the top

You're done..

:-)

combining results of two select statements

You can use a Union.

This will return the results of the queries in separate rows.

First you must make sure that both queries return identical columns.

Then you can do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS Number
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

UNION

SELECT tableA.Id, tableA.Name,  '' AS Owner, '' AS ImageUrl, '' AS CompanyImageUrl, COUNT([tableC].Id) AS Number
FROM 
[tableC] 
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id GROUP BY tableA.Id, tableA.Name

As has been mentioned, both queries return quite different data. You would probably only want to do this if both queries return data that could be considered similar.

SO

You can use a Join

If there is some data that is shared between the two queries. This will put the results of both queries into a single row joined by the id, which is probably more what you want to be doing here...

You could do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS NumberOfUsers, query2.NumberOfPlans
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 


INNER JOIN 
  (SELECT tableA.Id, COUNT([tableC].Id) AS NumberOfPlans 
   FROM [tableC] 
   RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id 
   GROUP BY tableA.Id, tableA.Name) AS query2 
ON query2.Id = tableA.Id

GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

How to make a transparent HTML button?

Setting its background image to none also works:

button {
    background-image: none;
}

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

How to install .MSI using PowerShell

In powershell 5.1 you can actually use install-package, but it can't take extra msi arguments.

install-package .\file.msi

Otherwise with start-process and waiting:

start -wait file.msi ALLUSERS=1,INSTALLDIR=C:\FILE

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Another solution that worked:

The data access object that actually throwed this exception is

public List<Foo> findAll() {
    return sessionFactory.getCurrentSession().createQuery("from foo").list();
}

The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.

public List<Foo> findAll() {
    return sessionFactory.getCurrentSession().createQuery("from Foo").list();

Thanks to this blog: https://www.arundhaj.com/blog/querysyntaxexception-not-mapped.html

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How to change the font and font size of an HTML input tag?

in your css :

 #txtComputer {
      font-size: 24px;
 }

You can style an input entirely (background, color, etc.) and even use the hover event.

What does %w(array) mean?

%W and %w allow you to create an Array of strings without using quotes and commas.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.

I would suggest try using DBWeaver from here :

https://dbeaver.io/download/

I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.

ER Diagram using the Community Version Db Viewer

top -c command in linux to filter processes listed based on processname

You can add filters to top while it is running, just press the o key and then type in a filter expression. For example, to monitor all java processes use the filter expression COMMAND=java. You can add multiple filters by pressing the key again, you can filter by user with the u key, and you can clear all filters with the = key.

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

How to run batch file from network share without "UNC path are not supported" message?

My situation is just a little different. I'm running a batch file on startup to distribute the latest version of internal business applications.

In this situation I'm using the Windows Registry Run Key with the following string

cmd /c copy \\serverName\SharedFolder\startup7.bat %USERPROFILE% & %USERPROFILE%\startup7.bat

This runs two commands on startup in the correct sequence. First copying the batch file locally to a directory the user has permission to. Then executing the same batch file. I can create a local directory c:\InternalApps and copy all of the files from the network.

This is probably too late to solve the original poster's question but it may help someone else.

How to extract IP Address in Spring MVC Controller get call?

I use such method to do this

public class HttpReqRespUtils {

    private static final String[] IP_HEADER_CANDIDATES = {
        "X-Forwarded-For",
        "Proxy-Client-IP",
        "WL-Proxy-Client-IP",
        "HTTP_X_FORWARDED_FOR",
        "HTTP_X_FORWARDED",
        "HTTP_X_CLUSTER_CLIENT_IP",
        "HTTP_CLIENT_IP",
        "HTTP_FORWARDED_FOR",
        "HTTP_FORWARDED",
        "HTTP_VIA",
        "REMOTE_ADDR"
    };

    public static String getClientIpAddressIfServletRequestExist() {

        if (RequestContextHolder.getRequestAttributes() == null) {
            return "0.0.0.0";
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        for (String header: IP_HEADER_CANDIDATES) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                String ip = ipList.split(",")[0];
                return ip;
            }
        }

        return request.getRemoteAddr();
    }
}

Generating random integer from a range

The following expression should be unbiased if I am not mistaken:

std::floor( ( max - min + 1.0 ) * rand() ) + min;

I am assuming here that rand() gives you a random value in the range between 0.0 and 1.0 NOT including 1.0 and that max and min are integers with the condition that min < max.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

TRY BELOW SOLUTIONS.

SOLUTION 1:

-> Run Android Studio as Administrator (this is only required for first run or when any issues arise due to automatic updates on any run in future).

Though it shows API 23 is or any other updates are not installed (and wouldn't show any 'Retry' button), BUT still the download and installation of rest of the updates would proceed (you can see the download progress incrementing even after seeing the above errors). So, DO NOT ABORT the operation.

-> At the end of installation (after rest of successful updates are installed) it would this time display the "Retry" button to retry installation for API 23 or any other versions which had failed earlier. Then click the "Retry" button, it would work this time.

This would resolve your issue with successful installation.

-> Next time onward no need to run Android studio as Administrator, unless it does any automatic updates and shows similar issues.

SOLUTION 2:

-> Alternative approach is to install any updates (which ever failed in earlier attempt) from Android SDK Manager first and then later launch Android Studio (which would not need any check for updates and any additional installations).

To install any features or updates, run Android SDK manager as administrator (run as administrator is not mandatory for this but preferred to avoid any permissions related issues) and check the required options and proceed with the installation without any issues.

SOLUTION 3:

-> If still your issue is not resolved, then try the proxy solution as suggested by others or check your internet connectivity if it's working properly or not.

*Any of the above solutions should resolve your issues.

jQuery or CSS selector to select all IDs that start with some string

You can use meta characters like * (http://api.jquery.com/category/selectors/). So I think you just can use $('#player_*').

In your case you could also try the "Attribute starts with" selector: http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')

Replace and overwrite instead of appending

Using truncate(), the solution could be

import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
    #convert to string:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
    f.truncate()

How to "scan" a website (or page) for info, and bring it into my program?

JSoup solution is great, but if you need to extract just something really simple it may be easier to use regex or String.indexOf

As others have already mentioned the process is called scraping

How to round up with excel VBA round()?

I find the following function sufficient:

'
' Round Up to the given number of digits
'
Function RoundUp(x As Double, digits As Integer) As Double

    If x = Round(x, digits) Then
        RoundUp = x
    Else
        RoundUp = Round(x + 0.5 / (10 ^ digits), digits)
    End If

End Function

How to download dependencies in gradle

For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window. enter image description here

Comparing Class Types in Java

Hmmm... Keep in mind that Class may or may not implement equals() -- that is not required by the spec. For instance, HP Fortify will flag myClass.equals(myOtherClass).

How to obtain the last path segment of a URI

I know this is old, but the solutions here seem rather verbose. Just an easily readable one-liner if you have a URL or URI:

String filename = new File(url.getPath()).getName();

Or if you have a String:

String filename = new File(new URL(url).getPath()).getName();

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

Android Studio - mergeDebugResources exception

You may have a corrupted .9.png in your drawables directory

remove empty lines from text file with PowerShell

(Get-Content c:\FileWithEmptyLines.txt) | 
    Foreach { $_ -Replace  "Old content", " New content" } | 
    Set-Content c:\FileWithEmptyLines.txt;

Removing duplicate objects with Underscore for Javascript

If you're looking to remove duplicates based on an id you could do something like this:

var res = [
  {id: 1, content: 'heeey'},
  {id: 2, content: 'woah'}, 
  {id: 1, content:'foo'},
  {id: 1, content: 'heeey'},
];
var uniques = _.map(_.groupBy(res,function(doc){
  return doc.id;
}),function(grouped){
  return grouped[0];
});

//uniques
//[{id: 1, content: 'heeey'},{id: 2, content: 'woah'}]

How to view DB2 Table structure

Control Center already got the feature of that. It's just below the table list.

enter image description here

How to create a simple map using JavaScript/JQuery

This is an old question, but because the existing answers could be very dangerous, I wanted to leave this answer for future folks who might stumble in here...

The answers based on using an Object as a HashMap are broken and can cause extremely nasty consequences if you use anything other than a String as the key. The problem is that Object properties are coerced to Strings using the .toString method. This can lead to the following nastiness:

function MyObject(name) {
  this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");

var map = {};
map[key1] = 1;
map[key2] = 2;

If you were expecting that Object would behave in the same way as a Java Map here, you would be rather miffed to discover that map only contains one entry with the String key [object Object]:

> JSON.stringify(map);
{"[object Object]": 2}

This is clearly not a replacement for Java's HashMap. Bizarrely, given it's age, Javascript does not currently have a general purpose map object. There is hope on the horizon, though: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map although a glance at the Browser Compatability table there will show that this isn't ready to used in general purpose web apps yet.

In the meantime, the best you can do is:

  • Deliberately use Strings as keys. I.e. use explicit strings as keys rather than relying on the implicit .toString-ing of the keys you use.
  • Ensure that the objects you are using as keys have a well-defined .toString() method that suits your understanding of uniqueness for these objects.
  • If you cannot/don't want to change the .toString of the key Objects, when storing and retrieving the entries, convert the objects to a string which represents your understanding of uniqueness. E.g. map[toUniqueString(key1)] = 1

Sometimes, though, that is not possible. If you want to map data based on, for example File objects, there is no reliable way to do this because the attributes that the File object exposes are not enough to ensure its uniqueness. (You may have two File objects that represent different files on disk, but there is no way to distinguish between them in JS in the browser). In these cases, unfortunately, all that you can do is refactor your code to eliminate the need for storing these in a may; perhaps, by using an array instead and referencing them exclusively by index.

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

Remove duplicates in the list using linq

This is how I was able to group by with Linq. Hope it helps.

var query = collection.GroupBy(x => x.title).Select(y => y.FirstOrDefault());

simple Jquery hover enlarge

Demo Link

Tutorial Link

This will show original dimensions of Image on Hover using jQuery custom code

HTML

        <ul class="thumb">
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/1.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/2.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/3.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/4.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/5.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/6.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/7.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/8.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/9.jpg)"></div>
                </a>
            </li>
        </ul>

CSS

    ul.thumb {
        float: left;
        list-style: none;
        padding: 10px;
        width: 360px;
        margin: 80px;
    }

    ul.thumb li {
        margin: 0;
        padding: 5px;
        float: left;
        position: relative;
        /* Set the absolute positioning base coordinate */
        width: 110px;
        height: 110px;
    }

    ul.thumb li .thumbnail-wrap {
        width: 100px;
        height: 100px;
        /* Set the small thumbnail size */
        -ms-interpolation-mode: bicubic;
        /* IE Fix for Bicubic Scaling */
        border: 1px solid #ddd;
        padding: 5px;
        position: absolute;
        left: 0;
        top: 0;
        background-size: cover;
        background-repeat: no-repeat;

        -webkit-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
        -moz-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
        box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);

    }

    ul.thumb li .thumbnail-wrap.hover {
        -webkit-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
        -moz-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
        box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
    }

    .thumnail-zoomed-wrapper {
        display: none;
        position: fixed;
        top: 0px;
        left: 0px;
        height: 100vh;
        width: 100%;
        background: rgba(0, 0, 0, 0.2);
        z-index: 99;
    }

    .thumbnail-zoomed-image {
        margin: auto;
        display: block;
        text-align: center;
        margin-top: 12%;
    }

    .thumbnail-zoomed-image img {
        max-width: 100%;
    }

    .close-image-zoom {
        z-index: 10;
        float: right;
        margin: 10px;
        cursor: pointer;
    }

jQuery

        var perc = 40;
        $("ul.thumb li").hover(function () {
            $("ul.thumb li").find(".thumbnail-wrap").css({
                "z-index": "0"
            });
            $(this).find(".thumbnail-wrap").css({
                "z-index": "10"
            });
            var imageval = $(this).find(".thumbnail-wrap").css("background-image").slice(5);
            var img;
            var thisImage = this;
            img = new Image();
            img.src = imageval.substring(0, imageval.length - 2);
            img.onload = function () {
                var imgh = this.height * (perc / 100);
                var imgw = this.width * (perc / 100);
                $(thisImage).find(".thumbnail-wrap").addClass("hover").stop()
                    .animate({
                        marginTop: "-" + (imgh / 4) + "px",
                        marginLeft: "-" + (imgw / 4) + "px",
                        width: imgw + "px",
                        height: imgh + "px"
                    }, 200);
            }
        }, function () {
            var thisImage = this;
            $(this).find(".thumbnail-wrap").removeClass("hover").stop()
                .animate({
                    marginTop: "0",
                    marginLeft: "0",
                    top: "0",
                    left: "0",
                    width: "100px",
                    height: "100px",
                    padding: "5px"
                }, 400, function () {});
        });

        //Show thumbnail in fullscreen
        $("ul.thumb li .thumbnail-wrap").click(function () {

            var imageval = $(this).css("background-image").slice(5);
            imageval = imageval.substring(0, imageval.length - 2);
            $(".thumbnail-zoomed-image img").attr({
                src: imageval
            });
            $(".thumnail-zoomed-wrapper").fadeIn();
            return false;
        });

        //Close fullscreen preview
        $(".thumnail-zoomed-wrapper .close-image-zoom").click(function () {
            $(".thumnail-zoomed-wrapper").hide();
            return false;
        });

enter image description here

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

How can I write to the console in PHP?

I have abandoned all of the above in favour of Debugger & Logger. I cannot praise it enough!

Just click on one of the tabs at top right, or on the "click here" to expand/hide.

Notice the different "categories". You can click any array to expand/collapse it.

From the web page

Main features:

  • Show globals variables ($GLOBALS, $_POST, $_GET, $_COOKIE, etc.)
  • Show PHP version and loaded extensions
  • Replace PHP built in error handler
  • Log SQL queries
  • Monitor code and SQL queries execution time
  • Inspect variables for changes
  • Function calls tracing
  • Code coverage analysis to check which lines of script where executed
  • Dump of all types of variable
  • File inspector with code highlighter to view source code
  • Send messages to JavaScript console (Chrome only), for Ajax scripts

Enter image description here

How to make a window always stay on top in .Net?

I had a momentary 5 minute lapse and I forgot to specify the form in full like this:

  myformName.ActiveForm.TopMost = true;

But what I really wanted was THIS!

  this.TopMost = true;

Is there a GUI design app for the Tkinter / grid geometry?

The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.

Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.

* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).

How do I join two lines in vi?

In vi, J (that's Shift + J) or :join should do what you want, for the most part. Note that they adjust whitespace. In particular, you'll end up with a space between the two joined lines in many cases, and if the second line is indented that indentation will be removed prior to joining.

In Vim you can also use gJ (G, then Shift + J) or :join!. These will join lines without doing any whitespace adjustments.

In Vim, see :help J for more information.

Replace missing values with column mean

lapply can be used instead of a for loop.

d1[] <- lapply(d1, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))

This doesn't really have any advantages over the for loop, though maybe it's easier if you have non-numeric columns as well, in which case

d1[sapply(d1, is.numeric)] <- lapply(d1[sapply(d1, is.numeric)], function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))

is almost as easy.

git add, commit and push commands in one?

You can use bash script , set alias to launch any command or group of commands

git commit -am "your message" && git push 

How do I find files that do not contain a given string pattern?

grep -irnw "filepath" -ve "pattern"

or

grep -ve "pattern" < file

above command will give us the result as -v finds the inverse of the pattern being searched

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

How to get the full URL of a Drupal page?

The following is more Drupal-ish:

url(current_path(), array('absolute' => true)); 

cannot import name patterns

I Resolved it by cloning my project directly into Eclipse from GIT,

Initially I was cloning it at specific location on file system then importing it as existing project into Eclipse.

How to convert an IPv4 address into a integer in C#?

If you were interested in the function not just the answer here is how it is done:

int ipToInt(int first, int second, 
    int third, int fourth)
{
    return Convert.ToInt32((first * Math.Pow(256, 3))
        + (second * Math.Pow(256, 2)) + (third * 256) + fourth);
}

with first through fourth being the segments of the IPv4 address.

Connecting to MySQL from Android with JDBC

try changing in the gradle file the targetSdkVersion to 8

targetSdkVersion 8

How to display JavaScript variables in a HTML page without document.write

If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.

?var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);??????

Swift Open Link in Safari

Swift 3 & IOS 10.2

UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)

Swift 3 & IOS 10.2

How can I uninstall npm modules in Node.js?

I found this out the hard way, even if it is seemingly obvious.

I initially tried to loop through the node_modules directory running npm uninstall module-name with a simple for loop in a script. I found out it will not work if you call the full path, e.g.,

npm uninstall module-name

was working, but

npm uninstall /full/path/to/node_modules/module-name 

was not working.

How to search multiple columns in MySQL?

Here is a query which you can use to search for anything in from your database as a search result ,

SELECT * FROM tbl_customer 
    WHERE CustomerName LIKE '%".$search."%'
    OR Address LIKE '%".$search."%' 
    OR City LIKE '%".$search."%' 
    OR PostalCode LIKE '%".$search."%' 
    OR Country LIKE '%".$search."%'

Using this code will help you search in for multiple columns easily

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Often using a lock on a method level is too rude. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, you can create dummy objects to implement block level synchronization. The block level is more efficient because it does not lock the whole method.

Here some example

Method Level

class MethodLevel {

  //shared among threads
SharedResource x, y ;

public void synchronized method1() {
   //multiple threads can't access
}
public void synchronized method2() {
  //multiple threads can't access
}

 public void method3() {
  //not synchronized
  //multiple threads can access
 }
}

Block Level

class BlockLevel {
  //shared among threads
  SharedResource x, y ;

  //dummy objects for locking
  Object xLock = new Object();
  Object yLock = new Object();

    public void method1() {
     synchronized(xLock){
    //access x here. thread safe
    }

    //do something here but don't use SharedResource x, y
    // because will not be thread-safe
     synchronized(xLock) {
       synchronized(yLock) {
      //access x,y here. thread safe
      }
     }

     //do something here but don't use SharedResource x, y
     //because will not be thread-safe
    }//end of method1
 }

[Edit]

For Collection like Vector and Hashtable they are synchronized when ArrayList or HashMap are not and you need set synchronized keyword or invoke Collections synchronized method:

Map myMap = Collections.synchronizedMap (myMap); // single lock for the entire map
List myList = Collections.synchronizedList (myList); // single lock for the entire list

How to set image width to be 100% and height to be auto in react native?

For image tag you can use this type of style, it worked for me:

imageStyle: {
    width: Dimensions.get('window').width - 23,
    resizeMode: "contain",
    height: 211,
 },

Xcode project not showing list of simulators

If you updated Xcode to 12.1. Completely quit Xcode and it will install components.

enter image description here

How to fix the session_register() deprecated issue?

To complement Felix Kling's answer, I was studying a codebase that used to have the following code:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        session_register($var);
    }
} else if (!(empty($start_vars))) {
    session_register($start_vars);
}

In order to not use session_register they made the following adjustments:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        $_SESSION[$var] =  $GLOBALS[$var];
    }
} else if (!(empty($start_vars))) {
    $_SESSION[$start_vars] =  $GLOBALS[$start_vars];
}

android button selector

You can't achieve text size change with a state list drawable. To change text color and text size do this:

Text color

To change the text color, you can create color state list resource. It will be a separate resource located in res/color/ directory. In layout xml you have to set it as the value for android:textColor attribute. The color selector will then contain something like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/text_pressed" />
    <item android:color="@color/text_normal" />
</selector>

Text size

You can't change the size of the text simply with resources. There's no "dimen selector". You have to do it in code. And there is no straightforward solution.

Probably the easiest solution might be utilizing View.onTouchListener() and handle the up and down events accordingly. Use something like this:

view.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // change text size to the "pressed value"
                return true;
            case MotionEvent.ACTION_UP:
                // change text size to the "normal value"
                return true;
            default:
                return false;
            }
        }
});

A different solution might be to extend the view and override the setPressed(Boolean) method. The method is internally called when the change of the pressed state happens. Then change the size of the text accordingly in the method call (don't forget to call the super).

dataframe: how to groupBy/count then filter on count in Scala

When you pass a string to the filter function, the string is interpreted as SQL. Count is a SQL keyword and using count as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).

You can easily avoid this by using a column expression instead of a String:

df.groupBy("x").count()
  .filter($"count" >= 2)
  .show()

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

What exactly is Apache Camel?

In short:

When there is a requirement to connect / integrate systems, you will probably need to connect to some data source and then process this data to match your business requirements.

In order to do that:

1) You could develop custom program that would do it (might be time consuming and hard to understand, maintain for other developer)

2) Alternatively, you could use Apache Camel to do it in standardised way (it has most of the connectors already developed for you, you just need to set it up and plug your logic - called Process):

Camel will help you to:

  1. Consume data from any source/format
  2. Process this data
  3. Output data to any source/format

By using Apache Camel you will make it easy to understand / maintain / extend your system to another developer.

Apache Camel is developed with Enterprise Integration Patterns. The patterns help you to integrate systems in a good way :-)

How to add data to DataGridView

LINQ is a "query" language (thats the Q), so modifying data is outside its scope.

That said, your DataGridView is presumably bound to an ItemsSource, perhaps of type ObservableCollection<T> or similar. In that case, just do something like X.ToList().ForEach(yourGridSource.Add) (this might have to be adapted based on the type of source in your grid).

How do I update the element at a certain position in an ArrayList?

 arrList.set(5,newValue);

and if u want to update it then add this line also

 youradapater.NotifyDataSetChanged();

Trying to handle "back" navigation button action in iOS

In Swift 4 or above:

override func didMove(toParent parent: UIViewController?) {
    if parent == nil {
        //"Back pressed"
    }
}

If Python is interpreted, what are .pyc files?

I've been given to understand that Python is an interpreted language...

This popular meme is incorrect, or, rather, constructed upon a misunderstanding of (natural) language levels: a similar mistake would be to say "the Bible is a hardcover book". Let me explain that simile...

"The Bible" is "a book" in the sense of being a class of (actual, physical objects identified as) books; the books identified as "copies of the Bible" are supposed to have something fundamental in common (the contents, although even those can be in different languages, with different acceptable translations, levels of footnotes and other annotations) -- however, those books are perfectly well allowed to differ in a myriad of aspects that are not considered fundamental -- kind of binding, color of binding, font(s) used in the printing, illustrations if any, wide writable margins or not, numbers and kinds of builtin bookmarks, and so on, and so forth.

It's quite possible that a typical printing of the Bible would indeed be in hardcover binding -- after all, it's a book that's typically meant to be read over and over, bookmarked at several places, thumbed through looking for given chapter-and-verse pointers, etc, etc, and a good hardcover binding can make a given copy last longer under such use. However, these are mundane (practical) issues that cannot be used to determine whether a given actual book object is a copy of the Bible or not: paperback printings are perfectly possible!

Similarly, Python is "a language" in the sense of defining a class of language implementations which must all be similar in some fundamental respects (syntax, most semantics except those parts of those where they're explicitly allowed to differ) but are fully allowed to differ in just about every "implementation" detail -- including how they deal with the source files they're given, whether they compile the sources to some lower level forms (and, if so, which form -- and whether they save such compiled forms, to disk or elsewhere), how they execute said forms, and so forth.

The classical implementation, CPython, is often called just "Python" for short -- but it's just one of several production-quality implementations, side by side with Microsoft's IronPython (which compiles to CLR codes, i.e., ".NET"), Jython (which compiles to JVM codes), PyPy (which is written in Python itself and can compile to a huge variety of "back-end" forms including "just-in-time" generated machine language). They're all Python (=="implementations of the Python language") just like many superficially different book objects can all be Bibles (=="copies of The Bible").

If you're interested in CPython specifically: it compiles the source files into a Python-specific lower-level form (known as "bytecode"), does so automatically when needed (when there is no bytecode file corresponding to a source file, or the bytecode file is older than the source or compiled by a different Python version), usually saves the bytecode files to disk (to avoid recompiling them in the future). OTOH IronPython will typically compile to CLR codes (saving them to disk or not, depending) and Jython to JVM codes (saving them to disk or not -- it will use the .class extension if it does save them).

These lower level forms are then executed by appropriate "virtual machines" also known as "interpreters" -- the CPython VM, the .Net runtime, the Java VM (aka JVM), as appropriate.

So, in this sense (what do typical implementations do), Python is an "interpreted language" if and only if C# and Java are: all of them have a typical implementation strategy of producing bytecode first, then executing it via a VM/interpreter.

More likely the focus is on how "heavy", slow, and high-ceremony the compilation process is. CPython is designed to compile as fast as possible, as lightweight as possible, with as little ceremony as feasible -- the compiler does very little error checking and optimization, so it can run fast and in small amounts of memory, which in turns lets it be run automatically and transparently whenever needed, without the user even needing to be aware that there is a compilation going on, most of the time. Java and C# typically accept more work during compilation (and therefore don't perform automatic compilation) in order to check errors more thoroughly and perform more optimizations. It's a continuum of gray scales, not a black or white situation, and it would be utterly arbitrary to put a threshold at some given level and say that only above that level you call it "compilation"!-)

MVC 4 client side validation not working

Use:

@Html.EditorFor

Instead of:

@Html.TextBoxFor

Add multiple items to a list

Thanks to AddRange:

Example:

public class Person
{ 
    private string Name;
    private string FirstName;

    public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}

To add multiple Person to a List<>:

List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
    new Person("John1", "Doe" ),
    new Person("John2", "Doe" ),
    new Person("John3", "Doe" ),
 });

How to generate a git patch for a specific commit?

if you just want diff the specified file, you can :

git diff master 766eceb -- connections/ > 000-mysql-connector.patch

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

Why are my PHP files showing as plain text?

You will need to add handlers in Apache to handle php code.

Edit by command sudo vi /etc/httpd/conf/httpd.conf

Add these two handlers

  AddType application/x-httpd-php .php
  AddType application/x-httpd-php .php3

at position specified below

<IfModule mime_module>

 AddType application/x-compress .Z
 AddType application/x-gzip .gz .tgz

--Add Here--


</IfModule>

for more details on AddType handlers

http://httpd.apache.org/docs/2.2/mod/mod_mime.html

Java double.MAX_VALUE?

this states that Account.deposit(Double.MAX_VALUE); it is setting deposit value to MAX value of Double dataType.to procced for running tests.

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

Only allow specific characters in textbox

    private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
        {
            e.Handled = true;
        }
    }

How to Scroll Down - JQuery

$('.btnMedio').click(function(event) {
    // Preventing default action of the event
    event.preventDefault();
    // Getting the height of the document
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, 50);
//                                       |    |
//                                       |    --- duration (milliseconds) 
//                                       ---- distance from the top
});

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

SnappySnippet

I finally found some time to create this tool. You can install SnappySnippet from Github. It allows easy HTML+CSS extraction from the specified (last inspected) DOM node. Additionally, you can send your code straight to CodePen or JSFiddle. Enjoy!

SnappySnippet Chrome extension

Other features

  • cleans up HTML (removing unnecessary attributes, fixing indentation)
  • optimizes CSS to make it readable
  • fully configurable (all filters can be turned off)
  • works with ::before and ::after pseudo-elements
  • nice UI thanks to Bootstrap & Flat-UI projects

Code

SnappySnippet is open source, and you can find the code on GitHub.

Implementation

Since I've learned quite a lot while making this, I've decided to share some of the problems I've experienced and my solutions to them, maybe someone will find it interesting.

First attempt - getMatchedCSSRules()

At first I've tried retrieving the original CSS rules (coming from CSS files on the website). Quite amazingly, this is very simple thanks to window.getMatchedCSSRules(), however, it didn't work out well. The problem was that we were taking only a part of the HTML and CSS selectors that were matching in the context of the whole document, which were not matching anymore in the context of an HTML snippet. Since parsing and modifying selectors didn't seem like a good idea, I gave up on this attempt.

Second attempt - getComputedStyle()

Then, I've started from something that @CollectiveCognition suggested - getComputedStyle(). However, I really wanted to separate CSS form HTML instead of inlining all styles.

Problem 1 - separating CSS from HTML

The solution here wasn't very beautiful but quite straightforward. I've assigned IDs to all nodes in the selected subtree and used that ID to create appropriate CSS rules.

Problem 2 - removing properties with default values

Assigning IDs to the nodes worked out nicely, however I found out that each of my CSS rules has ~300 properties making the whole CSS unreadable.
Turns out that getComputedStyle() returns all possible CSS properties and values calculated for the given element. Some of them where empty, some had browser default values. To remove default values I had to get them from the browser first (and each tag has different default values). The solution was to compare the styles of the element coming from the website with the same element inserted into an empty <iframe>. The logic here was that there are no style sheets in an empty <iframe>, so each element I've appended there had only default browser styles. This way I was able to get rid of most of the properties that were insignificant.

Problem 3 - keeping only shorthand properties

Next thing I have spotted was that properties having shorthand equivalent were unnecessarily printed out (e.g. there was border: solid black 1px and then border-color: black;, border-width: 1px itd.).
To solve this I've simply created a list of properties that have shorthand equivalents and filtered them out from the results.

Problem 4 - removing prefixed properties

The number of properties in each rule was significantly lower after the previous operation, but I've found that I sill had a lot of -webkit- prefixed properties that I've never hear of (-webkit-app-region? -webkit-text-emphasis-position?).
I was wondering if I should keep any of these properties because some of them seemed useful (-webkit-transform-origin, -webkit-perspective-origin etc.). I haven't figured out how to verify this, though, and since I knew that most of the time these properties are just garbage, I decided to remove them all.

Problem 5 - combining same CSS rules

The next problem I have spotted was that the same CSS rules are repeated over and over (e.g. for each <li> with the exact same styles there was the same rule in the CSS output created).
This was just a matter of comparing rules with each other and combining these that had exactly the same set of properties and values. As a result, instead of #LI_1{...}, #LI_2{...} I got #LI_1, #LI_2 {...}.

Problem 6 - cleaning up and fixing indentation of HTML

Since I was happy with the result, I moved to HTML. It looked like a mess, mostly because the outerHTML property keeps it formatted exactly as it was returned from the server.
The only thing HTML code taken from outerHTML needed was a simple code reformatting. Since it's something available in every IDE, I was sure that there is a JavaScript library that does exactly that. And it turns out that I was right (jquery-clean). What's more, I've got unnecessary attributes removal extra (style, data-ng-repeat etc.).

Problem 7 - filters breaking CSS

Since there is a chance that in some circumstances filters mentioned above may break CSS in the snippet, I've made all of them optional. You can disable them from the Settings menu.

Load an image from a url into a PictureBox

If you are trying to load the image at your form_load, it's a better idea to use the code

pictureBox1.LoadAsync(@"http://google.com/test.png");

not only loading from web but also no lag in your form loading.

Setting PayPal return URL and making it auto return?

Sharing this as I've recently encountered issues similar to this thread

For a long time, my script worked well (basic payment form) and returned the POST variables to my success.php page and the IPN data as POST variables also. However, lately, I noticed the return page (success.php) was no longer receiving any POST vars. I tested in Sandbox and live and I'm pretty sure PayPal have changed something !

The notify_url still receives the correct IPN data allowing me to update DB, but I've not been able to display a success message on my return URL (success.php) page.

Despite trying many combinations to switch options on and off in PayPal website payment preferences and IPN, I've had to make some changes to my script to ensure I can still process a message. I've accomplished this by turning on PDT and Auto Return, after following this excellent guide.

Now it all works fine, but the only issue is the return URL contains all of the PDT variables which is ugly!

You may also find this helpful

Dart/Flutter : Converting timestamp

If you are using firestore (and not just storing the timestamp as a string) a date field in a document will return a Timestamp. The Timestamp object contains a toDate() method.

Using timeago you can create a relative time quite simply:

_ago(Timestamp t) {
  return timeago.format(t.toDate(), 'en_short');
}

build() {
  return  Text(_ago(document['mytimestamp'])));
}

Make sure to set _firestore.settings(timestampsInSnapshotsEnabled: true); to return a Timestamp instead of a Date object.

Creating a UIImage from a UIColor to use as a background image for UIButton

CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

How do I create a link using javascript?

<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

int value under 10 convert to string two digit number

I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.

Now, you can also use String Interpolation for same solution.

Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.

String Interpolation

i.ToString("00")
01

i.ToString("000")
001

i.ToString("0000")
0001

$"Prefix_{i:00}"
Prefix_01

$"Prefix_{i:000}"
Prefix_001

$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix

Get selected text from a drop-down list (select box) using jQuery

Just add the below line

$(this).prop('selected', true);

replaced .att to .prop it worked for all browsers.

How to get the range of occupied cells in excel sheet

The only way I could get it to work in ALL scenarios (except Protected sheets) (based on Farham's Answer):

It supports:

  • Scanning Hidden Row / Columns

  • Ignores formatted cells with no data / formula

Code:

// Unhide All Cells and clear formats
sheet.Columns.ClearFormats();
sheet.Rows.ClearFormats();

// Detect Last used Row - Ignore cells that contains formulas that result in blank values
int lastRowIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                InteropExcel.XlFindLookIn.xlValues,
                InteropExcel.XlLookAt.xlWhole,
                InteropExcel.XlSearchOrder.xlByRows,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Row;
// Detect Last Used Column  - Ignore cells that contains formulas that result in blank values
int lastColIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                InteropExcel.XlSearchOrder.xlByColumns,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Column;

// Detect Last used Row / Column - Including cells that contains formulas that result in blank values
int lastColIncludeFormulas = sheet.UsedRange.Columns.Count;
int lastColIncludeFormulas = sheet.UsedRange.Rows.Count;

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Working with Bjarne Stroustrup Programming Principles and Practice Using C++ "FLTK" example i got the same error but after like 1 hour i got an idea, i tracked one of the libs already seen in Project Properties -> Linker -> Input -> Additional Dependencies, in my case i tracked the kernel32.lib to see where was located and saw there were many kernel32.lib's in different folders. So i started copy the FLTK libs in those folders and the last one i tried worked. Visual Studio 2013 Express found the fltkd.lib and the code worked.

In my case the correct route was C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86

I don't know how to set that route inside Visual Studio.

Not sure if that Windows kits folder was created when i installed Microsoft Windows SDK for Windows 7 and .NET Framework 4 (ISO) http://www.microsoft.com/en-us/download/details.aspx?id=8442

Hope that helps you people.

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

You will also get this if git doesn't have permissions to read the config files. It will just go up in the hierarchy tree until it needs to cross file systems.

Android - Activity vs FragmentActivity?

If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future.

For simple single screen layouts you may still use Activity.

Django database query: How to get object by id?

In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404 importing by from django.shortcuts import get_object_or_404.

Use example:

def myFunc(request, my_pk):
    my_var = get_object_or_404(CLASS_NAME, pk=my_pk)

How to validate date with format "mm/dd/yyyy" in JavaScript?

Moment is really a good one to resolve it. I don't see reason to add complexity just to check date... take a look on moment : http://momentjs.com/

HTML :

<input class="form-control" id="date" name="date" onchange="isValidDate(this);" placeholder="DD/MM/YYYY" type="text" value="">

Script :

 function isValidDate(dateString)  {
    var dateToValidate = dateString.value
    var isValid = moment(dateToValidate, 'MM/DD/YYYY',true).isValid()
    if (isValid) {
        dateString.style.backgroundColor = '#FFFFFF';
    } else {
        dateString.style.backgroundColor = '#fba';
    }   
};

Is there a way for non-root processes to bind to "privileged" ports on Linux?

TLDR: For "the answer" (as I see it), jump down to the >>TLDR<< part in this answer.

OK, I've figured it out (for real this time), the answer to this question, and this answer of mine is also a way of apologizing for promoting another answer (both here and on twitter) that I thought was "the best", but after trying it, discovered that I was mistaken about that. Learn from my mistake kids: don't promote something until you've actually tried it yourself!

Again, I reviewed all the answers here. I've tried some of them (and chose not to try others because I simply didn't like the solutions). I thought that the solution was to use systemd with its Capabilities= and CapabilitiesBindingSet= settings. After wrestling with this for some time, I discovered that this is not the solution because:

Capabilities are intended to restrict root processes!

As the OP wisely stated, it is always best to avoid that (for all your daemons if possible!).

You cannot use the Capabilities related options with User= and Group= in systemd unit files, because capabilities are ALWAYS reset when execev (or whatever the function is) is called. In other words, when systemd forks and drops its perms, the capabilities are reset. There is no way around this, and all that binding logic in the kernel is basic around uid=0, not capabilities. This means that it is unlikely that Capabilities will ever be the right answer to this question (at least any time soon). Incidentally, setcap, as others have mentioned, is not a solution. It didn't work for me, it doesn't work nicely with scripts, and those are reset anyways whenever the file changes.

In my meager defense, I did state (in the comment I've now deleted), that James' iptables suggestion (which the OP also mentions), was the "2nd best solution". :-P

>>TLDR<<

The solution is to combine systemd with on-the-fly iptables commands, like this (taken from DNSChain):

[Unit]
Description=dnschain
After=network.target
Wants=namecoin.service

[Service]
ExecStart=/usr/local/bin/dnschain
Environment=DNSCHAIN_SYSD_VER=0.0.1
PermissionsStartOnly=true
ExecStartPre=/sbin/sysctl -w net.ipv4.ip_forward=1
ExecStartPre=-/sbin/iptables -D INPUT -p udp --dport 5333 -j ACCEPT
ExecStartPre=-/sbin/iptables -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
ExecStartPre=/sbin/iptables -A INPUT -p udp --dport 5333 -j ACCEPT
ExecStartPre=/sbin/iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
ExecStopPost=/sbin/iptables -D INPUT -p udp --dport 5333 -j ACCEPT
ExecStopPost=/sbin/iptables -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 5333
User=dns
Group=dns
Restart=always
RestartSec=5
WorkingDirectory=/home/dns
PrivateTmp=true
NoNewPrivileges=true
ReadOnlyDirectories=/etc

# Unfortunately, capabilities are basically worthless because they're designed to restrict root daemons. Instead, we use iptables to listen on privileged ports.
# Capabilities=cap_net_bind_service+pei
# SecureBits=keep-caps

[Install]
WantedBy=multi-user.target

Here we accomplish the following:

  • The daemon listens on 5333, but connections are successfully accepted on 53 thanks to iptables
  • We can include the commands in the unit file itself, and thus we save people headaches. systemd cleans up the firewall rules for us, making sure to remove them when the daemon isn't running.
  • We never run as root, and we make privilege escalation impossible (at least systemd claims to), supposedly even if the daemon is compromised and sets uid=0.

iptables is still, unfortunately, quite an ugly and difficult-to-use utility. If the daemon is listening on eth0:0 instead of eth0, for example, the commands are slightly different.

Magento addFieldToFilter: Two fields, match as OR, not AND

I've got another way to add an or condition in the field:

->addFieldToFilter(
    array('title', 'content'),
    array(
        array('like'=>'%$titlesearchtext%'), 
        array('like'=>'%$contentsearchtext%')
    )
)

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Count the Number of Tables in a SQL Server Database

USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';

to get table counts

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';

this also works

USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();

What is mapDispatchToProps?

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component.

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read.

https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

Pretty git branch graphs

git-forest is an excellent perl script I've been using for more than a year and I hardly use the git log command directly any more.

These are some of the things I love about this script:

  • It uses unicode characters to draw the lines in the graph giving a more continuous look to the graph lines.
  • You can combine --reverse with the graph output, which is not possible with the regular git log command.
  • It uses git log internally to grab the list of commits, so all options that you pass to git log can also be passed to this script as well.

I have an alias using git-forest as follows:

[alias]
tree = "forest --pretty=format:\"%C(red)%h %C(magenta)(%ar) %C(blue)%an %C(reset)%s\" --style=15 --reverse"

This is how the output looks like on a terminal:

enter image description here

Array.size() vs Array.length

array.length isn't necessarily the number of items in the array:

var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101

The length of the array is one more than the highest index.

As stated before Array.size() is not a valid method.

More information

how to force maven to update local repo

If you are struggling with authenticating to a site, and Maven is caching the results, simply removing the meta-data about the site from the meta-data stash will force Maven to revisit the site.

gvim <local-git-repository>/commons-codec/resolver-status.properties

jQuery UI Dialog OnBeforeUnload

this works for me

$(window).bind('beforeunload', function() {
      return 'Do you really want to leave?' ;
});

Python: most idiomatic way to convert None to empty string?

Use short circuit evaluation:

s = a or '' + b or ''

Since + is not a very good operation on strings, better use format strings:

s = "%s%s" % (a or '', b or '')

What is the path that Django uses for locating and loading templates?

Contrary to some answers posted in this thread, adding 'DIRS': ['templates'] has no effect(it's redundant) since templates is the default path where Django looks for templates.

If you are attempting to reference an app's template, ensure that your app is in the list of INSTALLED_APPS in the main project settings.py.

INSTALLED_APPS': [
   # ...
   'my_app',
]

Quoting Django's Templates documentation:

class DjangoTemplates¶

Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.

When APP_DIRS is True, DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.

When you create an application to your project, there's no templates directory inside the application directory. Since that you can have an application without using templates, Django doesn't create such directory. That is, you have to create it and storing your templates in there.

Here's another paragraph from Django Tutorial documentation, which is even clearer:

Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.

When to use AtomicReference in Java?

Here's a very simple use case and has nothing to do with thread safety.

To share an object between lambda invocations, the AtomicReference is an option:

public void doSomethingUsingLambdas() {

    AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();

    soSomethingThatTakesALambda(() -> {
        yourObjectRef.set(youObject);
    });

    soSomethingElseThatTakesALambda(() -> {
        YourObject yourObject = yourObjectRef.get();
    });
}

I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference is an option.

In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

design a stack such that getMinimum( ) should be O(1)

To getMin elements from Stack. We have to use Two stack .i.e Stack s1 and Stack s2.

  1. Initially, both stacks are empty, so add elements to both stacks

---------------------Recursively call Step 2 to 4-----------------------

  1. if New element added to stack s1.Then pop elements from stack s2

  2. compare new elments with s2. which one is smaller , push to s2.

  3. pop from stack s2(which contains min element)

Code looks like:

package Stack;
import java.util.Stack;
public class  getMin 
{  

        Stack<Integer> s1= new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();

        void push(int x)
        {
            if(s1.isEmpty() || s2.isEmpty())

            {
                 s1.push(x);
                 s2.push(x);
            }
            else
            {

               s1. push(x);
                int y = (Integer) s2.pop();
                s2.push(y);
                if(x < y)
                    s2.push(x);
                        }
        }
        public Integer pop()
        {
            int x;
            x=(Integer) s1.pop();
            s2.pop();
            return x;

        }
    public  int getmin()
        {
            int x1;
            x1= (Integer)s2.pop();
            s2.push(x1);
            return x1;
        }

    public static void main(String[] args) {
        getMin s = new getMin();
            s.push(10);
            s.push(20);
            s.push(30);
            System.out.println(s.getmin());
            s.push(1);
            System.out.println(s.getmin());
        }

}

How to convert an array into an object using stdClass()

The quick and dirty way is using json_encode and json_decode which will turn the entire array (including sub elements) into an object.

$clasa = json_decode(json_encode($clasa)); //Turn it into an object

The same can be used to convert an object into an array. Simply add , true to json_decode to return an associated array:

$clasa = json_decode(json_encode($clasa), true); //Turn it into an array

An alternate way (without being dirty) is simply a recursive function:

function convertToObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = convertToObject($value);
        }
        $object->$key = $value;
    }
    return $object;
}

or in full code:

<?php
    function convertToObject($array) {
        $object = new stdClass();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = convertToObject($value);
            }
            $object->$key = $value;
        }
        return $object;
    }

    $clasa = array(
            'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
            'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
            'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
            'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
            'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
    );

    $obj = convertToObject($clasa);
    print_r($obj);
?>

which outputs (note that there's no arrays - only stdClass's):

stdClass Object
(
    [e1] => stdClass Object
        (
            [nume] => Nitu
            [prenume] => Andrei
            [sex] => m
            [varsta] => 23
        )

    [e2] => stdClass Object
        (
            [nume] => Nae
            [prenume] => Ionel
            [sex] => m
            [varsta] => 27
        )

    [e3] => stdClass Object
        (
            [nume] => Noman
            [prenume] => Alice
            [sex] => f
            [varsta] => 22
        )

    [e4] => stdClass Object
        (
            [nume] => Geangos
            [prenume] => Bogdan
            [sex] => m
            [varsta] => 23
        )

    [e5] => stdClass Object
        (
            [nume] => Vasile
            [prenume] => Mihai
            [sex] => m
            [varsta] => 25
        )

)

So you'd refer to it by $obj->e5->nume.

DEMO

How to split a string by spaces in a Windows batch file?

set a=AAA BBB CCC DDD EEE FFF
set a=%a:~6,1%

This code finds the 5th character in the string. If I wanted to find the 9th string, I would replace the 6 with 10 (add one).

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.

    <div class="featured-image" style="height:300px">
     <img id="thumbnail" src="01.jpg"/>
    </div>

    <div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
    <img src='01.jpg'>
    <img src='02.jpg'>
    <img src='03.jpg'>
    <img src='04.jpg'>
    </div>

    <script type="text/javascript">
            function changeThumbnail()
            {
            $("#thumbnail").fadeOut(200);
            var path=$("#thumbnail").attr('src');
            var arr= new Array(); var i=0;
            $("#thumblist img").each(function(index, element) {
               arr[i]=$(this).attr('src');
               i++;
            });
            var index= arr.indexOf(path);
            if(index==(arr.length-1))
            path=arr[0];
            else
            path=arr[index+1];
            $("#thumbnail").attr('src',path).fadeIn(200);
            setTimeout(changeThumbnail, 5000);  
            }
            setTimeout(changeThumbnail, 5000);
    </script>

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

Concept behind putting wait(),notify() methods in Object class

The other answers to this question all miss the key point that in Java, there is one mutex associated with every object. (I'm assuming you know what a mutex or "lock" is.) This is not the case in most programming languages which have the concept of "locks". For example, in Ruby, you have to explicitly create as many Mutex objects as you need.

I think I know why the creators of Java made this choice (although, in my opinion, it was a mistake). The reason has to do with the inclusion of the synchronized keyword. I believe that the creators of Java (naively) thought that by including synchronized methods in the language, it would become easy for people to write correct multithreaded code -- just encapsulate all your shared state in objects, declare the methods that access that state as synchronized, and you're done! But it didn't work out that way...

Anyways, since any class can have synchronized methods, there needs to be one mutex for each object, which the synchronized methods can lock and unlock.

wait and notify both rely on mutexes. Maybe you already understand why this is the case... if not I can add more explanation, but for now, let's just say that both methods need to work on a mutex. Each Java object has a mutex, so it makes sense that wait and notify can be called on any Java object. Which means that they need to be declared as methods of Object.

Another option would have been to put static methods on Thread or something, which would take any Object as an argument. That would have been much less confusing to new Java programmers. But they didn't do it that way. It's much too late to change any of these decisions; too bad!

How do I change Eclipse to use spaces instead of tabs?

Don't miss Tab policy for both of * Spaces only * Use spaces to indent wrapped lines

I checked only the latter thing and left the Combobox as Tabs Only which kept failing CheckStyle.. FYI, I'm talking about Preferences > Java > Formatter > Edit...

Where does forever store console.log output?

You need to add the log destination specifiers before the filename to run. So

forever -e /path/error.txt -o /path/output.txt start index.js

C# guid and SQL uniqueidentifier

You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

Your method may look like this (provided that your only parameter is the Guid):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

See also: SQL Server's uniqueidentifier

How to remove the first character of string in PHP?

To remove first Character of string in PHP,

$string = "abcdef";     
$new_string = substr($string, 1);

echo $new_string;
Generates: "bcdef"

How to replace (null) values with 0 output in PIVOT

To modify the results under pivot, you can put the columns in the selected fields and then modify them accordingly. May be you can use DECODE for the columns you have built using pivot function.

  • Kranti A

What's the proper value for a checked attribute of an HTML checkbox?

  1. checked
  2. checked=""
  3. checked="checked"

    are equivalent;


according to spec checkbox '----? checked = "checked" or "" (empty string) or empty Specifies that the element represents a selected control.---'

Proper indentation for Python multiline strings

You can use this function trim_indent.

import re


def trim_indent(s: str):
    s = re.sub(r'^\n+', '', s)
    s = re.sub(r'\n+$', '', s)
    spaces = re.findall(r'^ +', s, flags=re.MULTILINE)
    if len(spaces) > 0 and len(re.findall(r'^[^\s]', s, flags=re.MULTILINE)) == 0:
        s = re.sub(r'^%s' % (min(spaces)), '', s, flags=re.MULTILINE)
    return s


print(trim_indent("""


        line one
            line two
                line three
            line two
        line one


"""))

Result:

"""
line one
    line two
        line three
    line two
line one
"""

Download an SVN repository?

Google page have a link that you can download the source code and the full tree.

Go to the Source tab, then click on Browse

then you see the link for Download it as:

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

How to Query an NTP Server using C#?

A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)

public static DateTime GetNetworkTime()
{
  const string NtpServer = "pool.ntp.org";

  const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
  const long TicksPerSecond = 10000000L;
  const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
  const long TicksTo1900 = DaysTo1900 * TicksPerDay;

  var ntpData = new byte[48];
  ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

  var addresses = Dns.GetHostEntry(NtpServer).AddressList;
  var ipEndPoint = new IPEndPoint(addresses[0], 123);
  long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  {
    socket.Connect(ipEndPoint);
    socket.ReceiveTimeout = 5000;
    socket.Send(ntpData);
    pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time

    socket.Receive(ntpData);
    pingDuration = Stopwatch.GetTimestamp() - pingDuration;
  }

  long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;

  // optional: display response-time
  // Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);

  long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
  long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
  long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);

  var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);

  return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}

Pythonic way to return list of every nth item in a larger list

>>> lst = list(range(165))
>>> lst[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]

Note that this is around 100 times faster than looping and checking a modulus for each element:

$ python -m timeit -s "lst = list(range(1000))" "lst1 = [x for x in lst if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "lst = list(range(1000))" "lst1 = lst[0::10]"
100000 loops, best of 3: 4.02 usec per loop

Mocking member variables of a class using Mockito

Lots of others have already advised you to rethink your code to make it more testable - good advice and usually simpler than what I'm about to suggest.

If you can't change the code to make it more testable, PowerMock: https://code.google.com/p/powermock/

PowerMock extends Mockito (so you don't have to learn a new mock framework), providing additional functionality. This includes the ability to have a constructor return a mock. Powerful, but a little complicated - so use it judiciously.

You use a different Mock runner. And you need to prepare the class that is going to invoke the constructor. (Note that this is a common gotcha - prepare the class that calls the constructor, not the constructed class)

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class})

Then in your test set-up, you can use the whenNew method to have the constructor return a mock

whenNew(Second.class).withAnyArguments().thenReturn(mock(Second.class));

Check if an element has event listener on it. No jQuery

There is no JavaScript function to achieve this. However, you could set a boolean value to true when you add the listener, and false when you remove it. Then check against this boolean before potentially adding a duplicate event listener.

Possible duplicate: How to check whether dynamically attached event listener exists or not?

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}

and make sure there is no parent tags with position: relative in it

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

generate random string for div id

A edited version of @jfriend000 version:

    /**
     * Generates a random string
     * 
     * @param int length_
     * @return string
     */
    function randomString(length_) {

        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
        if (typeof length_ !== "number") {
            length_ = Math.floor(Math.random() * chars.length_);
        }
        var str = '';
        for (var i = 0; i < length_; i++) {
            str += chars[Math.floor(Math.random() * chars.length)];
        }
        return str;
    }

MongoDB query multiple collections at once

You can use $lookup ( multiple ) to get the records from multiple collections:

Example:

If you have more collections ( I have 3 collections for demo here, you can have more than 3 ). and I want to get the data from 3 collections in single object:

The collection are as:

db.doc1.find().pretty();

{
    "_id" : ObjectId("5901a4c63541b7d5d3293766"),
    "firstName" : "shubham",
    "lastName" : "verma"
}

db.doc2.find().pretty();

{
    "_id" : ObjectId("5901a5f83541b7d5d3293768"),
    "userId" : ObjectId("5901a4c63541b7d5d3293766"),
    "address" : "Gurgaon",
    "mob" : "9876543211"
}

db.doc3.find().pretty();

{
    "_id" : ObjectId("5901b0f6d318b072ceea44fb"),
    "userId" : ObjectId("5901a4c63541b7d5d3293766"),
    "fbURLs" : "http://www.facebook.com",
    "twitterURLs" : "http://www.twitter.com"
}

Now your query will be as below:

db.doc1.aggregate([
    { $match: { _id: ObjectId("5901a4c63541b7d5d3293766") } },
    {
        $lookup:
        {
            from: "doc2",
            localField: "_id",
            foreignField: "userId",
            as: "address"
        }
    },
    {
        $unwind: "$address"
    },
    {
        $project: {
            __v: 0,
            "address.__v": 0,
            "address._id": 0,
            "address.userId": 0,
            "address.mob": 0
        }
    },
    {
        $lookup:
        {
            from: "doc3",
            localField: "_id",
            foreignField: "userId",
            as: "social"
        }
    },
    {
        $unwind: "$social"
    },

  {   
    $project: {      
           __v: 0,      
           "social.__v": 0,      
           "social._id": 0,      
           "social.userId": 0
       }
 }

]).pretty();

Then Your result will be:

{
    "_id" : ObjectId("5901a4c63541b7d5d3293766"),
    "firstName" : "shubham",
    "lastName" : "verma",

    "address" : {
        "address" : "Gurgaon"
    },
    "social" : {
        "fbURLs" : "http://www.facebook.com",
        "twitterURLs" : "http://www.twitter.com"
    }
}

If you want all records from each collections then you should remove below line from query:

{
            $project: {
                __v: 0,
                "address.__v": 0,
                "address._id": 0,
                "address.userId": 0,
                "address.mob": 0
            }
        }

{   
        $project: {      
               "social.__v": 0,      
               "social._id": 0,      
               "social.userId": 0
           }
     }

After removing above code you will get total record as:

{
    "_id" : ObjectId("5901a4c63541b7d5d3293766"),
    "firstName" : "shubham",
    "lastName" : "verma",
    "address" : {
        "_id" : ObjectId("5901a5f83541b7d5d3293768"),
        "userId" : ObjectId("5901a4c63541b7d5d3293766"),
        "address" : "Gurgaon",
        "mob" : "9876543211"
    },
    "social" : {
        "_id" : ObjectId("5901b0f6d318b072ceea44fb"),
        "userId" : ObjectId("5901a4c63541b7d5d3293766"),
        "fbURLs" : "http://www.facebook.com",
        "twitterURLs" : "http://www.twitter.com"
    }
}

How to pass optional parameters while omitting some other optional parameters?

You can specify multiple method signatures on the interface then have multiple method overloads on the class method:

interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter: number);
}

class MyNotificationService implements INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter?: number);
    error(message: string, param1?: (string|number), param2?: number) {
        var autoHideAfter: number,
            title: string;

        // example of mapping the parameters
        if (param2 != null) {
            autoHideAfter = param2;
            title = <string> param1;
        }
        else if (param1 != null) {
            if (typeof param1 === "string") {
                title = param1;
            }
            else {
                autoHideAfter = param1;
            }
        }

        // use message, autoHideAfter, and title here
    }
}

Now all these will work:

var service: INotificationService = new MyNotificationService();
service.error("My message");
service.error("My message", 1000);
service.error("My message", "My title");
service.error("My message", "My title", 1000);

...and the error method of INotificationService will have the following options:

Overload intellisense

Playground

Converting a string to JSON object

var Data=[{"id": "name2", "label": "Quantity"}]

Pass the string variable into Json parse :

Objdata= Json.parse(Data);

"Parser Error Message: Could not load type" in Global.asax

I too faced the same problem. Despite of following every Answer it didnt work. Then I changed the "Inherits=namespace.class" to "Inherits=fully qualified assemble name" i.e "Inherits=namespace.class,assemblyname, Version=, Culture=, PublicKeyToken=" Hope it helps.

How to easily duplicate a Windows Form in Visual Studio?

  1. Add a sub-folder to your project.
  2. Right-click on the sub-folder, and click Add Existing Item.
  3. Browse to the form you want to copy, and select its .cs file. This will duplicate the original form (partial and resx and all) in the sub-folder. The name will not conflict with the original, because the sub-folder will be included in its namespace.
  4. Right-click on the .cs file, click Refactor | Rename and enter the new name. This will also rename the partial and the resx for you.

I'm generally averse to methods of doing this that involve opening up the files in notepad or whatever, since I always think a common task like this should have a built-in way of doing it in Visual Studio. In this case, there is.

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

Automating running command on Linux from Windows using PuTTY

You can write a TCL script and establish SSH session to that Linux machine and issue commands automatically. Check http://wiki.tcl.tk/11542 for a short tutorial.

Differences between cookies and sessions?

Cookie is basically a global array accessed across web browsers. Many a times used to send/receive values. it acts as a storage mechanism to access values between forms. Cookies can be disabled by the browser which adds a constraint to their use in comparison to session.

Session can be defined as something between logging in and logging out. the time between the user logging in and logging out is a session. Session stores values only for the session time i.e before logging out. Sessions are used to track the activities of the user, once he logs on.

Validate phone number using javascript

Add a word boundary \b at the end of the regex:

/^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/

if the space after ) is optional:

/^(\([0-9]{3}\)\s*|[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/

How to get response body using HttpURLConnection, when code other than 2xx is returned?

This is an easy way to get a successful response from the server like PHP echo otherwise an error message.

BufferedReader br = null;
if (conn.getResponseCode() == 200) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
}

SQLAlchemy ORDER BY DESCENDING?

from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))

Usage from @jpmc26

Opening a folder in explorer and selecting a file

Using Process.Start on explorer.exe with the /select argument oddly only works for paths less than 120 characters long.

I had to use a native windows method to get it to work in all cases:

[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);

[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);

public static void OpenFolderAndSelectItem(string folderPath, string file)
{
    IntPtr nativeFolder;
    uint psfgaoOut;
    SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);

    if (nativeFolder == IntPtr.Zero)
    {
        // Log error, can't find folder
        return;
    }

    IntPtr nativeFile;
    SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);

    IntPtr[] fileArray;
    if (nativeFile == IntPtr.Zero)
    {
        // Open the folder without the file selected if we can't find the file
        fileArray = new IntPtr[0];
    }
    else
    {
        fileArray = new IntPtr[] { nativeFile };
    }

    SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);

    Marshal.FreeCoTaskMem(nativeFolder);
    if (nativeFile != IntPtr.Zero)
    {
        Marshal.FreeCoTaskMem(nativeFile);
    }
}

Limiting the output of PHP's echo to 200 characters

In this code we define a method and then we can simply call it. we give it two parameters. first one is text and the second one should be count of characters that you wanna display.

function the_excerpt(string $text,int $length){
    if(strlen($text) > $length){$text = substr($text,0,$length);}
    return $text; 
}

How to tell 'PowerShell' Copy-Item to unconditionally copy files

From the documentation (help copy-item -full):

-force <SwitchParameter>
    Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Accept wildcard characters?  false

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

How may I sort a list alphabetically using jQuery?

Something like this:

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

Above code will sort your unordered list with id 'myUL'.

OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort

MySQL Sum() multiple columns

You could change the database structure such that all subject rows become a column variable (like spreadsheet). This makes such analysis much easier

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

The connection to adb is down, and a severe error has occurred

I had a similar problem with adb.exe and Eclipse last time I updated ADT plugin. The solution was to run Eclipse as administrator and reinstall ADT.

anaconda update all possible packages?

TL;DR: dependency conflicts: Updating one requires (by it's requirements) to downgrade another

You are right:

conda update --all

is actually the way to go1. Conda always tries to upgrade the packages to the newest version in the series (say Python 2.x or 3.x).

Dependency conflicts

But it is possible that there are dependency conflicts (which prevent a further upgrade). Conda usually warns very explicitly if they occur.

e.g. X requires Y <5.0, so Y will never be >= 5.0

That's why you 'cannot' upgrade them all.

Resolving

To add: maybe it could work but a newer version of X working with Y > 5.0 is not available in conda. It is possible to install with pip, since more packages are available in pip. But be aware that pip also installs packages if dependency conflicts exist and that it usually breaks your conda environment in the sense that you cannot reliably install with conda anymore. If you do that, do it as a last resort and after all packages have been installed with conda. It's rather a hack.

A safe way you can try is to add conda-forge as a channel when upgrading (add -c conda-forge as a flag) or any other channel you find that contains your package if you really need this new version. This way conda does also search in this places for available packages.

Considering your update: You can upgrade them each separately, but doing so will not only include an upgrade but also a downgrade of another package as well. Say, to add to the example above:

X > 2.0 requires Y < 5.0, X < 2.0 requires Y > 5.0

So upgrading Y > 5.0 implies downgrading X to < 2.0 and vice versa.

(this is a pedagogical example, of course, but it's the same in reality, usually just with more complicated dependencies and sub-dependencies)

So you still cannot upgrade them all by doing the upgrades separately; the dependencies are just not satisfiable so earlier or later, an upgrade will downgrade an already upgraded package again. Or break the compatibility of the packages (which you usually don't want!), which is only possible by explicitly invoking an ignore-dependencies and force-command. But that is only to hack your way around issues, definitely not the normal-user case!


1 If you actually want to update the packages of your installation, which you usually don't. The command run in the base environment will update the packages in this, but usually you should work with virtual environments (conda create -n myenv and then conda activate myenv). Executing conda update --all inside such an environment will update the packages inside this environment. However, since the base environment is also an environment, the answer applies to both cases in the same way.

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
  tab3.desc = "XYZ" and
  tab4.ss = tab3.ss

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

Moving items around in an ArrayList

A simple swap is far better for "moving something up" in an ArrayList:

if(i > 0) {
    Item toMove = arrayList.get(i);
    arrayList.set(i, arrayList.get(i-1));
    arrayList.set(i-1, toMove);
}

Because an ArrayList uses an array, if you remove an item from an ArrayList, it has to "shift" all the elements after that item upward to fill in the gap in the array. If you insert an item, it has to shift all the elements after that item to make room to insert it. These shifts can get very expensive if your array is very big. Since you know that you want to end up with the same number of elements in the list, doing a swap like this allows you to "move" an element to another location in the list very efficiently.

As Chris Buckler and Michal Kreuzman point out, there is even a handy method in the Collections class to reduce these three lines of code to one:

Collections.swap(arrayList, i, i-1);

Correct way to quit a Qt program?

You can call qApp.exit();. I always use that and never had a problem with it.

If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

LINQ - Full Outer Join

Update 1: providing a truly generalized extension method FullOuterJoin
Update 2: optionally accepting a custom IEqualityComparer for the key type
Update 3: this implementation has recently become part of MoreLinq - Thanks guys!

Edit Added FullOuterGroupJoin (ideone). I reused the GetOuter<> implementation, making this a fraction less performant than it could be, but I'm aiming for 'highlevel' code, not bleeding-edge optimized, right now.

See it live on http://ideone.com/O36nWc

static void Main(string[] args)
{
    var ax = new[] { 
        new { id = 1, name = "John" },
        new { id = 2, name = "Sue" } };
    var bx = new[] { 
        new { id = 1, surname = "Doe" },
        new { id = 3, surname = "Smith" } };

    ax.FullOuterJoin(bx, a => a.id, b => b.id, (a, b, id) => new {a, b})
        .ToList().ForEach(Console.WriteLine);
}

Prints the output:

{ a = { id = 1, name = John }, b = { id = 1, surname = Doe } }
{ a = { id = 2, name = Sue }, b =  }
{ a = , b = { id = 3, surname = Smith } }

You could also supply defaults: http://ideone.com/kG4kqO

    ax.FullOuterJoin(
            bx, a => a.id, b => b.id, 
            (a, b, id) => new { a.name, b.surname },
            new { id = -1, name    = "(no firstname)" },
            new { id = -2, surname = "(no surname)" }
        )

Printing:

{ name = John, surname = Doe }
{ name = Sue, surname = (no surname) }
{ name = (no firstname), surname = Smith }

Explanation of terms used:

Joining is a term borrowed from relational database design:

  • A join will repeat elements from a as many times as there are elements in b with corresponding key (i.e.: nothing if b were empty). Database lingo calls this inner (equi)join.
  • An outer join includes elements from a for which no corresponding element exists in b. (i.e.: even results if b were empty). This is usually referred to as left join.
  • A full outer join includes records from a as well as b if no corresponding element exists in the other. (i.e. even results if a were empty)

Something not usually seen in RDBMS is a group join[1]:

  • A group join, does the same as described above, but instead of repeating elements from a for multiple corresponding b, it groups the records with corresponding keys. This is often more convenient when you wish to enumerate through 'joined' records, based on a common key.

See also GroupJoin which contains some general background explanations as well.


[1] (I believe Oracle and MSSQL have proprietary extensions for this)

Full code

A generalized 'drop-in' Extension class for this

internal static class MyExtensions
{
    internal static IEnumerable<TResult> FullOuterGroupJoin<TA, TB, TKey, TResult>(
        this IEnumerable<TA> a,
        IEnumerable<TB> b,
        Func<TA, TKey> selectKeyA, 
        Func<TB, TKey> selectKeyB,
        Func<IEnumerable<TA>, IEnumerable<TB>, TKey, TResult> projection,
        IEqualityComparer<TKey> cmp = null)
    {
        cmp = cmp?? EqualityComparer<TKey>.Default;
        var alookup = a.ToLookup(selectKeyA, cmp);
        var blookup = b.ToLookup(selectKeyB, cmp);

        var keys = new HashSet<TKey>(alookup.Select(p => p.Key), cmp);
        keys.UnionWith(blookup.Select(p => p.Key));

        var join = from key in keys
                   let xa = alookup[key]
                   let xb = blookup[key]
                   select projection(xa, xb, key);

        return join;
    }

    internal static IEnumerable<TResult> FullOuterJoin<TA, TB, TKey, TResult>(
        this IEnumerable<TA> a,
        IEnumerable<TB> b,
        Func<TA, TKey> selectKeyA, 
        Func<TB, TKey> selectKeyB,
        Func<TA, TB, TKey, TResult> projection,
        TA defaultA = default(TA), 
        TB defaultB = default(TB),
        IEqualityComparer<TKey> cmp = null)
    {
        cmp = cmp?? EqualityComparer<TKey>.Default;
        var alookup = a.ToLookup(selectKeyA, cmp);
        var blookup = b.ToLookup(selectKeyB, cmp);

        var keys = new HashSet<TKey>(alookup.Select(p => p.Key), cmp);
        keys.UnionWith(blookup.Select(p => p.Key));

        var join = from key in keys
                   from xa in alookup[key].DefaultIfEmpty(defaultA)
                   from xb in blookup[key].DefaultIfEmpty(defaultB)
                   select projection(xa, xb, key);

        return join;
    }
}

Google Gson - deserialize list<class> object? (generic type)

Another way is to use an array as a type, e.g.:

MyClass[] mcArray = gson.fromJson(jsonString, MyClass[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:

List<MyClass> mcList = Arrays.asList(mcArray);

IMHO this is much more readable.

And to make it be an actual list (that can be modified, see limitations of Arrays.asList()) then just do the following:

List<MyClass> mcList = new ArrayList<>(Arrays.asList(mcArray));

Updating GUI (WPF) using a different thread

Here is a full example that updates UI textboxes

<Window x:Class="WpfThreading.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfThreading"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="216.84">
<Grid Margin="0,0,2,0">
    <Button Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0"
            VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    <TextBox HorizontalAlignment="Left" Margin="10,35,0,10" TextWrapping="Wrap" Name="mtextBox" Width="87"   VerticalScrollBarVisibility="Auto"/>
    <TextBox HorizontalAlignment="Left" Margin="111,35,0,10" TextWrapping="Wrap" x:Name="mtextBox2" Width="87"   VerticalScrollBarVisibility="Auto"/>
</Grid></Window>

and in the code

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        new Thread(DoSomething).Start();
        new Thread(DoSomething2).Start();
    }


    public void DoSomething()
    {
        for (int i = 0; i < 100; i++)
        {
            Dispatcher.BeginInvoke(new Action(() => {
                mtextBox.Text += $"{i.ToString()}{Environment.NewLine}";
            }), DispatcherPriority.SystemIdle);

            Thread.Sleep(100);
        }

    }

    public void DoSomething2()
    {
        for (int i = 100; i > 0; i--)
        {
            Dispatcher.BeginInvoke(new Action(() => {
                mtextBox2.Text += $"{i.ToString()}{Environment.NewLine}";
            }), DispatcherPriority.SystemIdle);

            Thread.Sleep(100);
        }

    }
}

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

Can anyone recommend a simple Java web-app framework?

I recommend Apache Click as well. If you pass the test of ten minutes(I think that's the time you will take to read the Quick Start Guide) you won't come back!

Regards,

Gilberto

How to secure an ASP.NET Web API

Web API introduced an Attribute [Authorize] to provide security. This can be set globally (global.asx)

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}

Or per controller:

[Authorize]
public class ValuesController : ApiController{
...

Of course your type of authentication may vary and you may want to perform your own authentication, when this occurs you may find useful inheriting from Authorizate Attribute and extending it to meet your requirements:

public class DemoAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (Authorize(actionContext))
        {
            return;
        }
        HandleUnauthorizedRequest(actionContext);
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
        throw new HttpResponseException(challengeMessage);
    }

    private bool Authorize(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            var someCode = (from h in actionContext.Request.Headers where h.Key == "demo" select h.Value.First()).FirstOrDefault();
            return someCode == "myCode";
        }
        catch (Exception)
        {
            return false;
        }
    }
}

And in your controller:

[DemoAuthorize]
public class ValuesController : ApiController{

Here is a link on other custom implemenation for WebApi Authorizations:

http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/

React - Preventing Form Submission

You have prevent the default action of the event and return false from the function.

function onTestClick(e) {
    e.preventDefault();
    return false;
}

React / JSX Dynamic Component Name

I used a bit different Approach, as we always know our actual components so i thought to apply switch case. Also total no of component were around 7-8 in my case.

getSubComponent(name) {
    let customProps = {
       "prop1" :"",
       "prop2":"",
       "prop3":"",
       "prop4":""
    }

    switch (name) {
      case "Component1": return <Component1 {...this.props} {...customProps} />
      case "Component2": return <Component2 {...this.props} {...customProps} />
      case "component3": return <component3 {...this.props} {...customProps} />

    }
  }

How to delete a localStorage item when the browser window/tab is closed?

Here's a simple test to see if you have browser support when working with local storage:

if(typeof(Storage)!=="undefined") {
  console.log("localStorage and sessionStorage support!");
  console.log("About to save:");
  console.log(localStorage);
  localStorage["somekey"] = 'hello';
  console.log("Key saved:");
  console.log(localStorage);
  localStorage.removeItem("somekey");  //<--- key deleted here
  console.log("key deleted:");
  console.log(localStorage);
  console.log("DONE ===");
} else {
  console.log("Sorry! No web storage support..");
}

It worked for me as expected (I use Google Chrome). Adapted from: http://www.w3schools.com/html/html5_webstorage.asp.

Initialize Array of Objects using NSArray

No one commenting on the randomAge method?

This is so awfully wrong, it couldn't be any wronger.

NSInteger is a primitive type - it is most likely typedef'd as int or long. In the randomAge method, you calculate a number from about 1 to 98.

Then you can cast that number to an NSNumber. You had to add a cast because the compiler gave you a warning that you didn't understand. That made the warning go away, but left you with an awful bug: That number was forced to be a pointer, so now you have a pointer to an integer somewhere in the first 100 bytes of memory.

If you access an NSInteger through the pointer, your program will crash. If you write through the pointer, your program will crash. If you put it into an array or dictionary, your program will crash.

Change it either to NSInteger or int, which is probably the best, or to NSNumber if you need an object for some reason. Then create the object by calling [NSNumber numberWithInteger:99] or whatever number you want.

Rename Files and Directories (Add Prefix)

This could be done running a simple find command:

find * -maxdepth 0 -exec mv {} PRE_{} \;

The above command will prefix all files and folders in the current directory with PRE_.

How can I generate a tsconfig.json file?

i am using this,

yarn tsc --init

this fixed it for me

How to connect PHP with Microsoft Access database

Are you sure the odbc connector is well created ? if not check the step "Create an ODBC Connection" again

EDIT: Connection without DSN from php.net

// Microsoft Access

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

in your case it might be if your filename is northwind and your file extension mdb:

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=northwind", "", "");

C++ unordered_map using a custom class type as the key

I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:

  1. You can define a comparison function for an unordered_map separately, instead of using the equality comparison operator (operator==). This might be helpful, for example, if you want to use the latter for comparing all members of two Node objects to each other, but only some specific members as key of an unordered_map.
  2. You can also use lambda expressions instead of defining the hash and comparison functions.

All in all, for your Node class, the code could be written as follows:

using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);

Notes:

  • I just reused the hashing method at the end of jogojapan's answer, but you can find the idea for a more general solution here (if you don't want to use Boost).
  • My code is maybe a bit too minified. For a slightly more readable version, please see this code on Ideone.

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

SQLite DateTime comparison

Right now i am developing using System.Data.SQlite NuGet package (version 1.0.109.2). Which using SQLite version 3.24.0.

And this works for me.

SELECT * FROM tables WHERE datetime 
BETWEEN '2018-10-01 00:00:00' AND '2018-10-10 23:59:59';

I don't net to use the datetime() function. Perhaps they already updated the SQL query on that SQLite version.

Is there a way to get the XPath in Google Chrome?

Google Chrome provides a built-in debugging tool called "Chrome DevTools" out of the box, which includes a handy feature that can evaluate or validate XPath/CSS selectors without any third party extensions.

This can be done by two approaches:

Use the search function inside Elements panel to evaluate XPath/CSS selectors and highlight matching nodes in the DOM. Execute tokens $x("some_xpath") or $$("css-selectors") in Console panel, which will both evaluate and validate.

From Elements panel

  1. Press F12 to open up Chrome DevTools.

  2. Elements panel should be opened by default.

  3. Press Ctrl + F to enable DOM searching in the panel.

  4. Type in XPath or CSS selectors to evaluate.

  5. If there are matched elements, they will be highlighted in DOM. However, if there are matching strings inside DOM, they will be considered as valid results as well. For example, CSS selector header should match everything (inline CSS, scripts etc.) that contains the word header, instead of match only elements.

enter image description here

From Console panel

  1. Press F12 to open up Chrome DevTools.

  2. Switch to Console panel.

  3. Type in XPath like $x(".//header") to evaluate and validate.

  4. Type in CSS selectors like $$("header") to evaluate and validate.

  5. Check results returned from console execution.

If elements are matched, they will be returned in a list. Otherwise an empty list [ ] is shown.

$x(".//article")
[<article class="unit-article layout-post">…</article>]

$x(".//not-a-tag")
[ ]

If the XPath or CSS selector is invalid, an exception will be shown in red text. For example:

$x(".//header/")
SyntaxError: Failed to execute 'evaluate' on 'Document': The string './/header/' is not a valid XPath expression.

$$("header[id=]")
SyntaxError: Failed to execute 'querySelectorAll' on 'Document': 'header[id=]' is not a valid selector.

Is CSS Turing complete?

Turing-completeness is not only about "defining functions" or "have ifs/loops/etc". For example, Haskell doesn't have "loop", lambda-calculus don't have "ifs", etc...

For example, this site: http://experthuman.com/programming-with-nothing. The author uses Ruby and create a "FizzBuzz" program with only closures (no strings, numbers, or anything like that)...

There are examples when people compute some arithmetical functions on Scala using only the type system

So, yes, in my opinion, CSS3+HTML is turing-complete (even if you can't exactly do any real computation with then without becoming crazy)

Create thumbnail image

Here is a version based on the accepted answer. It fixes two problems...

  1. Improper disposing of the images.
  2. Maintaining the aspect ratio of the image.

I found this tool to be fast and effective for both JPG and PNG files.

private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
{
    const int thumbnailSize = 150;
    using (var image = Image.FromFile(imageFileName))
    {
        var imageHeight = image.Height;
        var imageWidth = image.Width;
        if (imageHeight > imageWidth)
        {
            imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
            imageHeight = thumbnailSize;
        }
        else
        {
            imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
            imageWidth = thumbnailSize;
        }

        using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
            //Save off the new thumbnail
            thumb.Save(thumbnailFileName);
    }

    return new FileInfo(thumbnailFileName);
}

Nested objects in javascript, best practices

var defaultSettings = {
    ajaxsettings: {},
    uisettings: {}
};

Take a look at this site: http://www.json.org/

Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.

Oracle select most recent date record

select *
from (select
  staff_id, site_id, pay_level, date, 
  rank() over (partition by staff_id order by date desc) r
  from owner.table
  where end_enrollment_date is null
)
where r = 1

How to detect current state within directive

Also you can use ui-sref-active directive:

<ul>
  <li ui-sref-active="active" class="item">
    <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  </li>
  <!-- ... -->
</ul>

Or filters: "stateName" | isState & "stateName" | includedByState

How to open the Google Play Store directly from my Android application?

As the official docs use https:// instead of market://, this combines Eric's and M3-n50's answer with code reuse (don't repeat yourself):

Intent intent = new Intent(Intent.ACTION_VIEW)
    .setData(Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
try {
    startActivity(new Intent(intent)
                  .setPackage("com.android.vending"));
} catch (android.content.ActivityNotFoundException exception) {
    startActivity(intent);
}

It tries to open with the GPlay app if it exists and falls back to default.

How to create file execute mode permissions in Git on Windows?

If the files already have the +x flag set, git update-index --chmod=+x does nothing and git thinks there's nothing to commit, even though the flag isn't being saved into the repo.

You must first remove the flag, run the git command, then put the flag back:

chmod -x <file>
git update-index --chmod=+x <file>
chmod +x <file>

then git sees a change and will allow you to commit the change.

Directory index forbidden by Options directive

Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/

HttpGet with HTTPS : SSLPeerUnverifiedException

Note: Do not do this in production code, use http instead, or the actual self signed public key as suggested above.

On HttpClient 4.xx:

import static org.junit.Assert.assertEquals;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class HttpClientTrustingAllCertsTest {

    @Test
    public void shouldAcceptUnsafeCerts() throws Exception {
        DefaultHttpClient httpclient = httpClientTrustingAllSSLCerts();
        HttpGet httpGet = new HttpGet("https://host_with_self_signed_cert");
        HttpResponse response = httpclient.execute( httpGet );
        assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
    }

    private DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        return httpclient;
    }

    private TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

        } };
        return trustAllCerts;
    }
}

IOException: The process cannot access the file 'file path' because it is being used by another process

As other answers in this thread have pointed out, to resolve this error you need to carefully inspect the code, to understand where the file is getting locked.

In my case, I was sending out the file as an email attachment before performing the move operation.

So the file got locked for couple of seconds until SMTP client finished sending the email.

The solution I adopted was to move the file first, and then send the email. This solved the problem for me.

Another possible solution, as pointed out earlier by Hudson, would've been to dispose the object after use.

public static SendEmail()
{
           MailMessage mMailMessage = new MailMessage();
           //setup other email stuff

            if (File.Exists(attachmentPath))
            {
                Attachment attachment = new Attachment(attachmentPath);
                mMailMessage.Attachments.Add(attachment);
                attachment.Dispose(); //disposing the Attachment object
            }
} 

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

List all environment variables from the command line

Don't lose time. Search for it in the registry:

reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

returns less than the SET command.

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

How to extract text from an existing docx file using python-docx

I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP

How to iterate (keys, values) in JavaScript?

You can use below script.

var obj={1:"a",2:"b",c:"3"};
for (var x=Object.keys(obj),i=0;i<x.length,key=x[i],value=obj[key];i++){
    console.log(key,value);
}

outputs
1 a
2 b
c 3

Reading Space separated input in python

You can do the following if you already know the number of fields of the input:

client_name = raw_input("Enter you first and last name: ")
first_name, last_name = client_name.split() 

and in case you want to iterate through the fields separated by spaces, you can do the following:

some_input = raw_input() # This input is the value separated by spaces
for field in some_input.split():
    print field # this print can be replaced with any operation you'd like
    #             to perform on the fields.

A more generic use of the "split()" function would be:

    result_list = some_string.split(DELIMITER)

where DELIMETER is replaced with the delimiter you'd like to use as your separator, with single quotes surrounding it.

An example would be:

    result_string = some_string.split('!')    

The code above takes a string and separates the fields using the '!' character as a delimiter.

Python IndentationError unindent does not match any outer indentation level

make sure """ comments are only a tab away and not 5 spaces

Dynamically add properties to a existing object

Take a look at the ExpandoObject.

For example:

dynamic person = new ExpandoObject();
person.Name = "Mr bar";
person.Sex = "No Thanks";
person.Age = 123;

Additional reading here.

"multiple target patterns" Makefile error

I met with the same error. After struggling, I found that it was due to "Space" in the folder name.

For example :

Earlier My folder name was : "Qt Projects"

Later I changed it to : "QtProjects"

and my issue was resolved.

Its very simple but sometimes a major issue.