Programs & Examples On #Modified date

Finding modified date of a file/folder

If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:

Get-Item c:\folder | Format-List  

Or you can access the property directly like so:

Get-Item c:\folder | Foreach {$_.LastWriteTime}

To start to filter folders & files based on last write time you can do this:

Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

ApplicationContext (Root Application Context) : Every Spring MVC web application has an applicationContext.xml file which is configured as the root of context configuration. Spring loads this file and creates an applicationContext for the entire application. This file is loaded by the ContextLoaderListener which is configured as a context param in web.xml file. And there will be only one applicationContext per web application.

WebApplicationContext : WebApplicationContext is a web aware application context i.e. it has servlet context information. A single web application can have multiple WebApplicationContext and each Dispatcher servlet (which is the front controller of Spring MVC architecture) is associated with a WebApplicationContext. The webApplicationContext configuration file *-servlet.xml is specific to a DispatcherServlet. And since a web application can have more than one dispatcher servlet configured to serve multiple requests, there can be more than one webApplicationContext file per web application.

How to print a double with two decimals in Android?

yourTextView.setText(String.format("Value of a: %.2f", a));

How can I URL encode a string in Excel VBA?

No, nothing built-in (until Excel 2013 - see this answer).

There are three versions of URLEncode() in this answer.

  • A function with UTF-8 support. You should probably use this one (or the alternative implementation by Tom) for compatibility with modern requirements.
  • For reference and educational purposes, two functions without UTF-8 support:
    • one found on a third party website, included as-is. (This was the first version of the answer)
    • one optimized version of that, written by me

A variant that supports UTF-8 encoding and is based on ADODB.Stream (include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):

Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function

This function was found on freevbcode.com:

Public Function URLEncode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim CurChr As Integer
  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    Select Case Asc(Mid(StringToEncode, CurChr, 1))
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case Else
        TempAns = TempAns & "%" & _
          Right("0" & Hex(Asc(Mid(StringToEncode, _
          CurChr, 1))), 2)
    End Select

    CurChr = CurChr + 1
  Loop

  URLEncode = TempAns
End Function

I've corrected a little bug that was in there.


I would use more efficient (~2× as fast) version of the above:

Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String

  Dim StringLen As Long: StringLen = Len(StringVal)

  If StringLen > 0 Then
    ReDim result(StringLen) As String
    Dim i As Long, CharCode As Integer
    Dim Char As String, Space As String

    If SpaceAsPlus Then Space = "+" Else Space = "%20"

    For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Char
        Case 32
          result(i) = Space
        Case 0 To 15
          result(i) = "%0" & Hex(CharCode)
        Case Else
          result(i) = "%" & Hex(CharCode)
      End Select
    Next i
    URLEncode = Join(result, "")
  End If
End Function

Note that neither of these two functions support UTF-8 encoding.

Offline Speech Recognition In Android (JellyBean)

I was dealing with this and I noticed that you need to install the offline package for your Language. My language setting was "Español (Estados Unidos)" but there is not offline package for that language, so when I turned off all network connectivity I was getting an alert from RecognizerIntent saying that can't reach Google, then I change the language to "English (US)" (because I already have the offline package) and launched the RecognizerIntent it just worked out.

Keys: Language setting == Offline Voice Recognizer Package

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

iOS UIImagePickerController result image orientation after upload

Here is an UIImage extension in Swift 2 based on the accepted answer by @Anomie. It uses a clearer switch case. It also takes the optional value returned by CGBitmapContextCreateImage() into consideration.

extension UIImage {
    func rotateImageByOrientation() -> UIImage {
        // No-op if the orientation is already correct
        guard self.imageOrientation != .Up else {
            return self
        }

        // We need to calculate the proper transformation to make the image upright.
        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
        var transform = CGAffineTransformIdentity;

        switch (self.imageOrientation) {
        case .Down, .DownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI))

        case .Left, .LeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))

        case .Right, .RightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height)
            transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))

        default:
            break
        }

        switch (self.imageOrientation) {
        case .UpMirrored, .DownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformScale(transform, -1, 1)

        case .LeftMirrored, .RightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0)
            transform = CGAffineTransformScale(transform, -1, 1)

        default:
            break
        }

        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
        let ctx = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height),
            CGImageGetBitsPerComponent(self.CGImage), 0,
            CGImageGetColorSpace(self.CGImage),
            CGImageGetBitmapInfo(self.CGImage).rawValue)
        CGContextConcatCTM(ctx, transform)
        switch (self.imageOrientation) {
        case .Left, .LeftMirrored, .Right, .RightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage)

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage)
        }

        // And now we just create a new UIImage from the drawing context
        if let cgImage = CGBitmapContextCreateImage(ctx) {
            return UIImage(CGImage: cgImage)
        } else {
            return self
        }
    }
}

How do I restart nginx only after the configuration test was successful on Ubuntu?

As of nginx 1.8.0, the correct solution is

sudo nginx -t && sudo service nginx reload

Note that due to a bug, configtest always returns a zero exit code even if the config file has an error.

How to get last inserted id?

I tried the above but they didn't work, i found this thought, that works a just fine for me.

var ContactID = db.GetLastInsertId();

Its less code and i easy to put in.

Hope this helps someone.

Date vs DateTime

Unfortunately, not in the .Net BCL. Dates are usually represented as a DateTime object with the time set to midnight.

As you can guess, this means that you have all the attendant timezone issues around it, even though for a Date object you'd want absolutely no timezone handling.

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

Retrieve specific commit from a remote Git repository

If the requested commit is in the pull requests of the remote repo, you can get it by its ID:

# Add the remote repo path, let's call it 'upstream':
git remote add upstream https://github.com/repo/project.git

# checkout the pull ID, for example ID '60':
git fetch upstream pull/60/head && git checkout FETCH_HEAD

How to scroll HTML page to given anchor?

_x000D_
_x000D_
jQuery("a[href^='#']").click(function(){_x000D_
    jQuery('html, body').animate({_x000D_
        scrollTop: jQuery( jQuery(this).attr('href') ).offset().top_x000D_
    }, 1000);_x000D_
    return false;_x000D_
});
_x000D_
_x000D_
_x000D_

Can I use an image from my local file system as background in HTML?

Jeff Bridgman is correct. All you need is
background: url('pic.jpg')
and this assumes that pic is in the same folder as your html.

Also, Roberto's answer works fine. Tested in Firefox, and IE. Thanks to Raptor for adding formatting that displays full picture fit to screen, and without scrollbars... In a folder f, on the desktop is this html and a picture, pic.jpg, using your userid. Make those substitutions in the below:

<html>
<head>
    <style>
        body {

        background: url('file:///C:/Users/userid/desktop/f/pic.jpg') no-repeat center center fixed;

        background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
        -webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
        -moz-background-size: cover; /* optional for Firefox 3.6 */ 
        -o-background-size: cover; /* for Opera 9.5 */
        margin: 0; /* to remove the default white margin of body */
        padding: 0; /* to remove the default white margin of body */
        overflow: hidden;
             }
    </style>
</head>
<body>
hello
</body>
</html>

jQuery: Best practice to populate drop down?

$.get(str, function(data){ 
            var sary=data.split('|');
            document.getElementById("select1").options.length = 0;
            document.getElementById("select1").options[0] = new Option('Select a State');
            for(i=0;i<sary.length-1;i++){
                document.getElementById("select1").options[i+1] = new Option(sary[i]);
                document.getElementById("select1").options[i+1].value = sary[i];
            }
            });

Jquery Setting Value of Input Field

$('.formData').attr('value','YOUR_VALUE')

Order by multiple columns with Doctrine

The orderBy method requires either two strings or an Expr\OrderBy object. If you want to add multiple order declarations, the correct thing is to use addOrderBy method, or instantiate an OrderBy object and populate it accordingly:

   # Inside a Repository method:
   $myResults = $this->createQueryBuilder('a')
       ->addOrderBy('a.column1', 'ASC')
       ->addOrderBy('a.column2', 'ASC')
       ->addOrderBy('a.column3', 'DESC')
   ;

   # Or, using a OrderBy object:
   $orderBy = new OrderBy('a.column1', 'ASC');
   $orderBy->add('a.column2', 'ASC');
   $orderBy->add('a.column3', 'DESC');

   $myResults = $this->createQueryBuilder('a')
       ->orderBy($orderBy)
   ;

Attempt to write a readonly database - Django w/ SELinux error

I faced the same problem but on Ubuntu Server. So all I did is changed to superuser before I activate virtual environment for django and then I ran the django server. It worked fine for me.

First copy paste

sudo su

Then activate the virtual environment if you have one.

source myvenv/bin/activate

At last run your django server.

python3 manage.py runserver

Hope, this will help you.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

What's the fastest way of checking if a point is inside a polygon in python

If speed is what you need and extra dependencies are not a problem, you maybe find numba quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing approach you proposed can be easily ported to numba by using numba @jit decorator and casting the polygon to a numpy array. The code should look like:

@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

The first execution will take a little longer than any subsequent call:

%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for 
point in points]

CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms

Which, after compilation will decrease to:

CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms

If you need speed at the first call of the function you can then pre-compile the code in a module using pycc. Store the function in a src.py like:

from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')


@cc.export('ray_tracing',  'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


if __name__ == "__main__":
    cc.compile()

Build it with python src.py and run:

import nbspatial

import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
np.linspace(0,2*np.pi,lenpoly)[:-1]]

# random points set of points to test 
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))

polygon = np.array(polygon)

%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]

CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms

In the numba code I used: 'b1(f8, f8, f8[:,:])'

In order to compile with nopython=True, each var needs to be declared before the for loop.

In the prebuild src code the line:

@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')

Is used to declare the function name and its I/O var types, a boolean output b1 and two floats f8 and a two-dimensional array of floats f8[:,:] as input.

Edit Jan/4/2021

For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D    

Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT compilation) see: https://github.com/numba/numba/issues/3336

Test:


import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))

For N=10000 on a 72 core machine, returns:

%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Edit 17 Feb '21:

  • fixing loop to start from 0 instead of 1 (thanks @mehdi):

for i in numba.prange(0, len(D))

Edit 20 Feb '21:

Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon method, from the cuspatial library:

    import numpy as np
    import cudf
    import cuspatial

    N = 100000002
    lenpoly = 1000
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
    np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))


    x_pnt = points[:,0]
    y_pnt = points[:,1]
    x_poly =polygon[:,0]
    y_poly = polygon[:,1]
    result = cuspatial.point_in_polygon(
        x_pnt,
        y_pnt,
        cudf.Series([0], index=['geom']),
        cudf.Series([0], name='r_pos', dtype='int32'), 
        x_poly, 
        y_poly,
    )

Following @Mehdi comparison. For N=100000002 and lenpoly=1000 - I got the following results:

 time_parallelpointinpolygon:         161.54760098457336 
 time_mpltPath:                       307.1664695739746 
 time_ray_tracing_numpy_numba:        353.07356882095337 
 time_is_inside_sm_parallel:          37.45389246940613 
 time_is_inside_postgis_parallel:     127.13793849945068 
 time_is_inside_rapids:               4.246025562286377

point in poligon methods comparison, #poins: 10e07

hardware specs:

  • CPU Intel xeon E1240
  • GPU Nvidia GTX 1070

Notes:

  • The cuspatial.point_in_poligon method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)

  • The numba methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda of fastest method mentioned by @Mehdi (is_inside_sm).

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

How can I make text appear on next line instead of overflowing?

Just add

white-space: initial;

to the text, a line text will come automatically in the next line.

What is SOA "in plain english"?

SOA is acronym for Service Oriented Architecture.

SOA is designing and writing software applications in such a way that distinct software modules can be integrated seamlessly with high degree of re-usability.

Most of the people restrict SOA as writing client/server software-web-services. But it is too small context of SOA. SOA is much larger than that and over the past few years web-services have been primary medium of communcation which is probably the reason why people think of SOA as web-services in general restricting the boundaries and meaning of SOA.

You can think of writing a database-access module which is so independent that it can work on its own without any dependencies. This module can expose classes which can be used by any host-software that needs database access. There's no start-up configuration in host-application. Whatever is needed or required is communicated through classes exposes by database-access module. We can call these classes as services and consider the module as service-enabled.

Practicing SOA gives high degree of re-usability by enforcing DRY [Don't repeat your self] which results into highly maintainable software. Maintainability is the first thing any software architecture thinks of - SOA gives you that.

How can I initialize base class member variables in derived class constructor?

While this is usefull in rare cases (if that was not the case, the language would've allowed it directly), take a look at the Base from Member idiom. It's not a code free solution, you'd have to add an extra layer of inheritance, but it gets the job done. To avoid boilerplate code you could use boost's implementation

How to decrypt hash stored by bcrypt

# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password 
encrypted and test with the current Password not encrypted to verify 
if it's the same User. 

For example :

public function updateUser(Request $req)
      {
         $entityManager = $this->getDoctrine()->getManager();
         $repository = $entityManager->getRepository(User::class);
         $user = $repository->find($req->get(id)); /// get User from your DB

         if($user == null){
            throw  $this->createNotFoundException('User don't exist!!', $user);
         }
         $password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
         $passwordToUpdate = $req->get('password'); // not encrypted yet from request.

         $passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);

          ////////////VERIFY IF IT'S THE SAME PASSWORD
         $isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );

         if($isPass === false){ // failure
            throw  $this->createNotFoundException('Your password it's not verify', null);
         }

        return $isPass; //// true!! it's the same password !!!

      }

Jackson: how to prevent field serialization

One should ask why you would want a public getter method for the password. Hibernate, or any other ORM framework, will do with a private getter method. For checking whether the password is correct, you can use

public boolean checkPassword(String password){
  return this.password.equals(anyHashingMethod(password));
}

Does it matter what extension is used for SQLite database files?

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

Convert Rtf to HTML

If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.

Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.

I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.

How to fix 'Microsoft Excel cannot open or save any more documents'

I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.

Way 01:

Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.

Way 02:

This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.

Laravel Pagination links not including other GET parameters

Pass the page number for pagination as well. Some thing like this

_x000D_
_x000D_
$currentPg = Input::get('page') ? Input::get('page') : '1';_x000D_
    $boards = Cache::remember('boards'.$currentPg, 60, function(){ return WhatEverModel::paginate(15); });
_x000D_
_x000D_
_x000D_

How to find foreign key dependencies in SQL Server?

Just a note for @"John Sansom" answer,

If the foreign key dependencies are sought, I think that the PT Where clause should be:

i1.CONSTRAINT_TYPE = 'FOREIGN KEY'  -- instead of 'PRIMARY KEY'

and its the ON condition:

ON PT.TABLE_NAME = FK.TABLE_NAME – instead of PK.TABLE_NAME

As commonly is used the primary key of the foreign table, I think this issue has not been noticed before.

How to format a JavaScript date

You should have a look at date.js. It adds many convenient helpers for working with dates, for example, in your case:

var date = Date.parse('2010-08-10');
console.log(date.toString('dd-MMM-yyyy'));

Getting started: http://www.datejs.com/2007/11/27/getting-started-with-datejs/

matching query does not exist Error in Django

In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:

user = UniversityDetails.objects.get(email=email)

is email a str, or a None? or an int?

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

In your home directory, you should edit .bash_profile if you have Git for Windows 2.21.0 or later (as of this writing).

You could direct .bash_profile to just source .bashrc, but if something happens to your .bash_profile, then it will be unclear why your .bashrc is again not working.

I put all my aliases and other environment stuff in .bash_profile, and I also added this line:

echo "Sourcing ~/.bash_profile - this version of Git Bash doesn't use .bashrc"

And THEN, in .bashrc I have

echo "This version of Git Bash doesn't use .bashrc. Use .bash_profile instead"

(Building on @harsel's response. I woulda commented, but I have no points yet.)

What is a segmentation fault?

Segmentation fault is also caused by hardware failures, in this case the RAM memories. This is the less common cause, but if you don't find an error in your code, maybe a memtest could help you.

The solution in this case, change the RAM.

edit:

Here there is a reference: Segmentation fault by hardware

Prepare for Segue in Swift

Prepare for Segue in Swift 4.2 and Swift 5.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "OrderVC") {
        // pass data to next view
        let viewController = segue.destination as? MyOrderDetailsVC
        viewController!.OrderData = self.MyorderArray[selectedIndex]


    }
}

How to Call segue On specific Event(Like Button Click etc):

performSegue(withIdentifier: "OrderVC", sender: self)

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

How do I encrypt and decrypt a string in python?

Encrypt Data

First, we need to install the cryptography library:

pip3 install cryptography
  • From the cryptography library, we need to import Fernet and start generating a key - this key is required for symmetric encryption/decryption.

  • To generate a key, we call the generate_key() method.

    • We only need to execute the above method once to generate a key.

    You need to keep this key in a safe place. If you lose the key, you won't be able to decrypt the data that was encrypted with this key.

  • Once we have generated a key, we need to load the key with load_key()

Encrypt a Message

This is a three step process:

  1. encode the message
  2. initialize the Fernet class
  3. pass the encoded message to encrypt() method

Below is a full working example of encrypting a message :

from cryptography.fernet import Fernet

def generate_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def encrypt_message(message):
    """
    Encrypts a message
    """
    key = load_key()
    encoded_message = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_message)

    print(encrypted_message)

if __name__ == "__main__":
    # generate_key() # execute only once 
    encrypt_message("Hello stackoverflow!")

output:

b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80='

Decrypt Data

To decrypt the message, we just call the decrypt() method from the Fernet library. Remember, we also need to load the key as well, because the key is needed to decrypt the message.

from cryptography.fernet import Fernet

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def decrypt_message(encrypted_message):
    """
    Decrypts an encrypted message
    """
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message)

    print(decrypted_message.decode())

if __name__ == "__main__":
    decrypt_message(b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80=')

output:

Hello stackoverflow!


Your password is in the secret.key in a form similar to the password below:

B8wtXqwBA_zb2Iaz5pW8CIQIwGSYSFoBiLsVz-vTqzw=

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

Easy, example with txt file

echo $null >> filename.txt

Global variables in AngularJS

You can also do something like this ..

function MyCtrl1($scope) {
    $rootScope.$root.name = 'anonymous'; 
}

function MyCtrl2($scope) {
    var name = $rootScope.$root.name;
}

Want to download a Git repository, what do I need (windows machine)?

Install mysysgit. (Same as Greg Hewgill's answer.)

Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

Mutex lock threads

Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).

Code for your reference:

#include <stdio.h>
#include <pthread.h>

void in_progress_feedback(int);

int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {

    pthread_t ptid = pthread_self();
    printf("ptid : %08x \n", (int)ptid);    

    int i;
    int lock_ret = 1;   
    do{

        lock_ret = pthread_mutex_trylock(&mutex);
        if(lock_ret){
            printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid,  lock_ret);
            sleep(2);  //wait time here..
        }else{  //ret =0 is successful lock
            printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
            break;
        }

    } while(lock_ret);

        for (i = 0; i < 10*10 ; i++) 
        global++;

    //do some stuff here
    in_progress_feedback(10);  //processing-time here..

    lock_ret = pthread_mutex_unlock(&mutex);
    printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);

     return NULL;
}

void in_progress_feedback(int prog_delay){

    int i=0;
    for(;i<prog_delay;i++){
    printf(". ");
    sleep(1);
    fflush(stdout);
    }

    printf("\n");
    fflush(stdout);
}

int main(void)
{
    pthread_t tid0,tid1;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid0, NULL, compute, NULL);
    pthread_create(&tid1, NULL, compute, NULL);
    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    printf("global = %d\n", global);
    pthread_mutex_destroy(&mutex);
          return 0;
}

How do you determine the ideal buffer size when using FileInputStream?

Optimum buffer size is related to a number of things: file system block size, CPU cache size and cache latency.

Most file systems are configured to use block sizes of 4096 or 8192. In theory, if you configure your buffer size so you are reading a few bytes more than the disk block, the operations with the file system can be extremely inefficient (i.e. if you configured your buffer to read 4100 bytes at a time, each read would require 2 block reads by the file system). If the blocks are already in cache, then you wind up paying the price of RAM -> L3/L2 cache latency. If you are unlucky and the blocks are not in cache yet, the you pay the price of the disk->RAM latency as well.

This is why you see most buffers sized as a power of 2, and generally larger than (or equal to) the disk block size. This means that one of your stream reads could result in multiple disk block reads - but those reads will always use a full block - no wasted reads.

Now, this is offset quite a bit in a typical streaming scenario because the block that is read from disk is going to still be in memory when you hit the next read (we are doing sequential reads here, after all) - so you wind up paying the RAM -> L3/L2 cache latency price on the next read, but not the disk->RAM latency. In terms of order of magnitude, disk->RAM latency is so slow that it pretty much swamps any other latency you might be dealing with.

So, I suspect that if you ran a test with different cache sizes (haven't done this myself), you will probably find a big impact of cache size up to the size of the file system block. Above that, I suspect that things would level out pretty quickly.

There are a ton of conditions and exceptions here - the complexities of the system are actually quite staggering (just getting a handle on L3 -> L2 cache transfers is mind bogglingly complex, and it changes with every CPU type).

This leads to the 'real world' answer: If your app is like 99% out there, set the cache size to 8192 and move on (even better, choose encapsulation over performance and use BufferedInputStream to hide the details). If you are in the 1% of apps that are highly dependent on disk throughput, craft your implementation so you can swap out different disk interaction strategies, and provide the knobs and dials to allow your users to test and optimize (or come up with some self optimizing system).

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

If you can decode JWT, how are they secure?

You can go to jwt.io, paste your token and read the contents. This is jarring for a lot of people initially.

The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.

The logical question is what is the motivation for not concerning itself with encrypted contents?

  1. The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure (is not transmitted via HTTP, only via HTTPS) and httpOnly (can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.

  2. This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).

  3. JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.

It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.

How to jump back to NERDTree from file in tab?

Ctrl-ww

This will move between open windows (so you could hop between the NERDTree window, the file you are editing and the help window, for example... just hold down Ctrl and press w twice).

How to install a plugin in Jenkins manually

Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/ directory.

Convert a negative number to a positive one in JavaScript

Math.abs(x) or if you are certain the value is negative before the conversion just prepend a regular minus sign: x = -x.

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.

@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {

    @ApiObjectField(description = "The code which is to be verified.")
    @NotBlank(message = "mandatory")
    private final String code;

    @ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
    private final String maskedMobileNumber;

    public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
        this.code = code;
        this.maskedMobileNumber = maskedMobileNumber;
    }

    public String getcode() {
        return code;
    }

    public String getMaskedMobileNumber() {
        return maskedMobileNumber;
    }
}

The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been

public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
    this.code = code;
    this.maskedMobileNumber = maskedMobileNumber;
}

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Thought I'd give a full answer combining some of the possible intricacies required for completeness.

  1. Check if you have 32-bit or 64-bit IIS installed:
    • Go to IIS Manager ? Application Pools, choose the appropriate app pool then Advanced Settings.
    • Check the setting "Enable 32-bit Applications". If that's true, that means the worker process is forced to run in 32-bit. If the setting is false, then the app pool is running in 64-bit mode.
    • You can also open up Task Manager and check w3wp.exe. If it's showing as w3wp*32.exe then it's 32-bit.
  2. Download the appropriate version here: https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads.
  3. Install it.
  4. Close and reopen IIS Manager to ensure the URL Rewrite module appears.

Declare multiple module.exports in Node.js

One way that you can do it is creating a new object in the module instead of replacing it.

for example:

var testone = function () {
    console.log('test one');
};
var testTwo = function () {
    console.log('test two');
};
module.exports.testOne = testOne;
module.exports.testTwo = testTwo;

and to call

var test = require('path_to_file').testOne:
testOne();

Changing minDate and maxDate on the fly using jQuery DatePicker

I know you are using Datepicker, but for some people who are just using HTML5 input date like me, there is an example how you can do the same: JSFiddle Link

$('#start_date').change(function(){
  var start_date = $(this).val();
  $('#end_date').prop({
    min: start_date
  });
});


/*  prop() method works since jquery 1.6, if you are using a previus version, you can use attr() method.*/

Java - Convert integer to string

One that I use often:

 Integer.parseInt("1234");

Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you'd have to ask someone else.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.

theoretically one server can only run as many requests concurrently as number of cores on it..

It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?

also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking

If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler

mongo - couldn't connect to server 127.0.0.1:27017

Another solution that resolved this same error for me, though this one might only be if you are accessing mongo (locally) via a SSH connection via a virtual machine (at least that's my setup), and may be a linux specific environment variable issue:

export LC_ALL=C

Also, I have had more success running mongo as a daemon service then with sudo service start, my understanding is this uses command line arguments rather then the config file so it likely is an issue with my config file:

mongod --fork --logpath /var/log/mongodb.log --auth --port 27017 --dbpath /var/lib/mongodb/admin

Connect Device to Mac localhost Server?

My problem was the same, but the solution had to do with changing a firewall setting. It turned out that node was set to block incoming traffic. I knew something was up because I used to be able to get to my localhost server from my phone.

Go to System Preferences -> Security & Privacy -> Firewall -> Firewall Options, and then scroll down until you find node and make sure node's setting is set to Allow incoming connections.

After changing the setting, I could reach the localhost server (port 3000) running on my Mac by going to http://192.168.1.11:3000

Find Active Tab using jQuery and Twitter Bootstrap

First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.

  <ul class='nav nav-tabs'>
    <li class='active'><a href='#home'>Home</a></li>
    <li><a href='#menu1'>Menu 1</a></li>
    <li><a href='#menu2'>Menu 2</a></li>
    <li><a href='#menu3'>Menu 3</a></li>
  </ul>

  <div class='tab-content'>
    <div id='home' class='tab-pane fade in active'>
      <h3>HOME</h3>
    <div id='menu1' class='tab-pane fade'>
      <h3>Menu 1</h3>
    </div>
    <div id='menu2' class='tab-pane fade'>
      <h3>Menu 2</h3>
    </div>
    <div id='menu3' class='tab-pane fade'>
      <h3>Menu 3</h3>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
// Handling data-toggle manually
    $('.nav-tabs a').click(function(){
        $(this).tab('show');
    });
// The on tab shown event
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        alert('Hello from the other siiiiiide!');
        var current_tab = e.target;
        var previous_tab = e.relatedTarget;
    });
});
</script>

How does Trello access the user's clipboard?

Disclosure: I wrote the code that Trello uses; the code below is the actual source code Trello uses to accomplish the clipboard trick.


We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press Ctrl+C.

Sounds like you've figured it out; we take advantage of the fact that when you want to hit Ctrl+C, you have to hit the Ctrl key first. When the Ctrl key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the C key is hit. (Then we hide the textarea when the Ctrl key comes up.)

Specifically, Trello does this:

TrelloClipboard = new class
  constructor: ->
    @value = ""

    $(document).keydown (e) =>
      # Only do this if there's something to be put on the clipboard, and it
      # looks like they're starting a copy shortcut
      if !@value || !(e.ctrlKey || e.metaKey)
        return

      if $(e.target).is("input:visible,textarea:visible")
        return

      # Abort if it looks like they've selected some text (maybe they're trying
      # to copy out a bit of the description or something)
      if window.getSelection?()?.toString()
        return

      if document.selection?.createRange().text
        return

      _.defer =>
        $clipboardContainer = $("#clipboard-container")
        $clipboardContainer.empty().show()
        $("<textarea id='clipboard'></textarea>")
        .val(@value)
        .appendTo($clipboardContainer)
        .focus()
        .select()

    $(document).keyup (e) ->
      if $(e.target).is("#clipboard")
        $("#clipboard-container").empty().hide()

  set: (@value) ->

In the DOM we've got:

<div id="clipboard-container"><textarea id="clipboard"></textarea></div>

CSS for the clipboard stuff:

#clipboard-container {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 0px;
  height: 0px;
  z-index: 100;
  display: none;
  opacity: 0;
}
#clipboard {
  width: 1px;
  height: 1px;
  padding: 0px;
}

... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.

When you hover over a card, it calls

TrelloClipboard.set(cardUrl)

... so then the clipboard helper knows what to select when the Ctrl key is pressed.

How to use default Android drawables

To use the default android drawable resource, no need copy anything.. you can just import it first with..

import android.R;

but i will make your own resources will have an error if you want to use it. The error will be something like:

R. cannot be resolved

So, I prefer not to import android.R but import *my.own.package*.R;

then when I can normally use my own resource with R.drawable.*something* without error, and put android.R.*something_default* to use the default android resources.

Change the Theme in Jupyter Notebook?

You Can Follow These Steps.

  1. pip install jupyterthemes or pip install --upgrade jupyterthemes to upgrade to latest version of theme.
  2. after that to list all the themes you have :jt -l
  3. after that jt-t <themename>for example jt -t solarizedl

How to use EditText onTextChanged event when I press the number?

Here, I wrote something similar to what u need:

    inputBoxNumberEt.setText(".     ");
    inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
    inputBoxNumberEt.addTextChangedListener(new TextWatcher() {

        boolean ignoreChange = false;

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {
            if (!ignoreChange) {
                String string = s.toString();
                string = string.replace(".", "");
                string = string.replace(" ", "");
                if (string.length() == 0)
                    string = ".     ";
                else if (string.length() == 1)
                    string = ".  " + string;
                else if (string.length() == 2)
                    string = "." + string;
                else if (string.length() > 2)
                    string = string.substring(0, string.length() - 2) + "." + string.substring(string.length() - 2, string.length());
                ignoreChange = true;
                inputBoxNumberEt.setText(string);
                inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
                ignoreChange = false;
            }
        }
    });

How to apply `git diff` patch without Git installed?

Use

git apply patchfile

if possible.

patch -p1 < patchfile 

has potential side-effect.

git apply also handles file adds, deletes, and renames if they're described in the git diff format, which patch won't do. Finally, git apply is an "apply all or abort all" model where either everything is applied or nothing is, whereas patch can partially apply patch files, leaving your working directory in a weird state.

AngularJs .$setPristine to reset form

Just for those who want to get $setPristine without having to upgrade to v1.1.x, here is the function I used to simulate the $setPristine function. I was reluctant to use the v1.1.5 because one of the AngularUI components I used is no compatible.

var setPristine = function(form) {
    if (form.$setPristine) {//only supported from v1.1.x
        form.$setPristine();
    } else {
        /*
         *Underscore looping form properties, you can use for loop too like:
         *for(var i in form){ 
         *  var input = form[i]; ...
         */
        _.each(form, function (input) {
            if (input.$dirty) {
                input.$dirty = false;
            }
        });
    }
};

Note that it ONLY makes $dirty fields clean and help changing the 'show error' condition like $scope.myForm.myField.$dirty && $scope.myForm.myField.$invalid.

Other parts of the form object (like the css classes) still need to consider, but this solve my problem: hide error messages.

how to call a onclick function in <a> tag?

Use the onclick as an attribute of your a, not part of the href

<a onclick='window.open("lead_data.php?leadid=1", myWin, scrollbars=yes, width=400, height=650);'>1</a>

Fiddle: http://jsfiddle.net/Wt5La/

Delete all rows in a table based on another table

This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:

ORA-00933: SQL command not properly ended.

Angular 2 declaring an array of objects

type NumberArray = Array<{id: number, text: string}>;

const arr: NumberArray = [
    {id: 0, text: 'Number 0'},
    {id: 1, text: 'Number 1'},
    {id: 2, text: 'Number 2'},
    {id: 3, text: 'Number 3 '},
    {id: 4, text: 'Number 4 '},
    {id: 5, text: 'Number 5 '},
];

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:

ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() ); 

Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.

Code that does AES encyrption:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Test 
{
    final String ALGORITHM = "AES";                       //symmetric algorithm for data encryption
    final String PADDING_MODE = "/CBC/PKCS5Padding";      //Padding for symmetric algorithm
    final String CHAR_ENCODING = "UTF-8";                 //character encoding
    //final String CRYPTO_PROVIDER = "SunMSCAPI";             //provider for the crypto

    int AES_KEY_SIZE = 256;  //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files  installed

    private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
    {
        byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);

        //get the symmetric key generator
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(AES_KEY_SIZE); //set the key size

        //generate the key
        SecretKey skey = keyGen.generateKey();

        //convert to binary
        byte[] rawAesKey = skey.getEncoded();

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);

        //set it to encrypt mode, with the generated key
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        //get the initialization vector being used (to be returned)
        byte[] aesIV = aesCipher.getIV();

        //encrypt the data
        byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);    

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);

        //set it to decrypt mode with the AES key, and IV
        aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));

        //decrypt and return the data
        byte[] decryptedData = aesCipherDec.doFinal(encryptedData);

        return new String(decryptedData, CHAR_ENCODING);
    }

    public static void main(String[] args)
    {
        String text = "Lets encrypt me";

        Test test = new Test();

        try {
            System.out.println(test.doCrypto(text));
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Does this code work for you?

You might also want to try specifying your bouncy castle provider in this line:

Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");

And see if it could be an error associated with bouncy castle.

Error in Eclipse: "The project cannot be built until build path errors are resolved"

If you can't find the build path error, sometimes menu Project ? Clean... works like a charm.

How to get first and last day of week in Oracle?

First day of week (Monday):

SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)-1 first_day_week FROM dual;

Last day of week (Sunday):

SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)+5 last_day_week FROM dual;

Substituting your date or date field in these formulas will work for you!

Passing arguments to AsyncTask, and returning results

I dont do it like this. I find it easier to overload the constructor of the asychtask class ..

public class calc_stanica extends AsyncTask>

String String mWhateveryouwantToPass;

 public calc_stanica( String whateveryouwantToPass)
{

    this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use  whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/   ...  ...  

NGINX to reverse proxy websockets AND enable SSL (wss://)?

A good, concise article by Pankaj Malhotra discusses how to do this with NGINX and is available here.

The basic NGINX configuration is reproduced below:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

upstream appserver {
    server 192.168.100.10:9222; # appserver_ip:ws_port
}

server {
    listen 8888; // client_wss_port

    ssl on;
    ssl_certificate /path/to/crt;
    ssl_certificate_key /path/to/key;


    location / {
        proxy_pass http://appserver;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

What's the difference between using "let" and "var"?

The difference is in the scope of the variables declared with each.

In practice, there are a number of useful consequences of the difference in scope:

  1. let variables are only visible in their nearest enclosing block ({ ... }).
  2. let variables are only usable in lines of code that occur after the variable is declared (even though they are hoisted!).
  3. let variables may not be redeclared by a subsequent var or let.
  4. Global let variables are not added to the global window object.
  5. let variables are easy to use with closures (they do not cause race conditions).

The restrictions imposed by let reduce the visibility of the variables and increase the likelihood that unexpected name collisions will be found early. This makes it easier to track and reason about variables, including their reachability(helping with reclaiming unused memory).

Consequently, let variables are less likely to cause problems when used in large programs or when independently-developed frameworks are combined in new and unexpected ways.

var may still be useful if you are sure you want the single-binding effect when using a closure in a loop (#5) or for declaring externally-visible global variables in your code (#4). Use of var for exports may be supplanted if export migrates out of transpiler space and into the core language.

Examples

1. No use outside nearest enclosing block: This block of code will throw a reference error because the second use of x occurs outside of the block where it is declared with let:

{
    let x = 1;
}
console.log(`x is ${x}`);  // ReferenceError during parsing: "x is not defined".

In contrast, the same example with var works.

2. No use before declaration:
This block of code will throw a ReferenceError before the code can be run because x is used before it is declared:

{
    x = x + 1;  // ReferenceError during parsing: "x is not defined".
    let x;
    console.log(`x is ${x}`);  // Never runs.
}

In contrast, the same example with var parses and runs without throwing any exceptions.

3. No redeclaration: The following code demonstrates that a variable declared with let may not be redeclared later:

let x = 1;
let x = 2;  // SyntaxError: Identifier 'x' has already been declared

4. Globals not attached to window:

var button = "I cause accidents because my name is too common.";
let link = "Though my name is common, I am harder to access from other JS files.";
console.log(link);  // OK
console.log(window.link);  // undefined (GOOD!)
console.log(window.button);  // OK

5. Easy use with closures: Variables declared with var do not work well with closures inside loops. Here is a simple loop that outputs the sequence of values that the variable i has at different points in time:

for (let i = 0; i < 5; i++) {
    console.log(`i is ${i}`), 125/*ms*/);
}

Specifically, this outputs:

i is 0
i is 1
i is 2
i is 3
i is 4

In JavaScript we often use variables at a significantly later time than when they are created. When we demonstrate this by delaying the output with a closure passed to setTimeout:

for (let i = 0; i < 5; i++) {
    setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}

... the output remains unchanged as long as we stick with let. In contrast, if we had used var i instead:

for (var i = 0; i < 5; i++) {
    setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}

... the loop unexpectedly outputs "i is 5" five times:

i is 5
i is 5
i is 5
i is 5
i is 5

Turning a Comma Separated string into individual rows

select t.OtherID,x.Kod
    from testData t
    cross apply (select Code from dbo.Split(t.Data,',') ) x

How does @synchronized lock/unlock in Objective-C?

Apple's implementation of @synchronized is open source and it can be found here. Mike ash wrote two really interesting post about this subject:

In a nutshell it has a table that maps object pointers (using their memory addresses as keys) to pthread_mutex_t locks, which are locked and unlocked as needed.

Escape regex special characters in a Python string

Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end.

>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\

Or maybe you just want to escape a phrase to paste into your program? If so, do this:

>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'

Downloading a picture via urllib and python

I have found this answer and I edit that in more reliable way

def download_photo(self, img_url, filename):
    try:
        image_on_web = urllib.urlopen(img_url)
        if image_on_web.headers.maintype == 'image':
            buf = image_on_web.read()
            path = os.getcwd() + DOWNLOADED_IMAGE_PATH
            file_path = "%s%s" % (path, filename)
            downloaded_image = file(file_path, "wb")
            downloaded_image.write(buf)
            downloaded_image.close()
            image_on_web.close()
        else:
            return False    
    except:
        return False
    return True

From this you never get any other resources or exceptions while downloading.

VSCode Change Default Terminal

If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `

//with this you can select what type of console you want
{
    "key": "ctrl+shift+t",
    "command": "shellLauncher.launch"
},

//and this will help you quickly change console
{ 
    "key": "ctrl+shift+j", 
    "command": "workbench.action.terminal.focusNext" 
},
{
    "key": "ctrl+shift+k", 
    "command": "workbench.action.terminal.focusPrevious" 
}`

CSS Auto hide elements after 5 seconds

based from the answer of @SW4, you could also add a little animation at the end.

_x000D_
_x000D_
body > div{_x000D_
    border:1px solid grey;_x000D_
}_x000D_
html, body, #container {_x000D_
    height:100%;_x000D_
    width:100%;_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
#container {_x000D_
    overflow:hidden;_x000D_
    position:relative;_x000D_
}_x000D_
#hideMe {_x000D_
    -webkit-animation: cssAnimation 5s forwards; _x000D_
    animation: cssAnimation 5s forwards;_x000D_
}_x000D_
@keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}_x000D_
@-webkit-keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}
_x000D_
<div>_x000D_
<div id='container'>_x000D_
    <div id='hideMe'>Wait for it...</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

sending tag <img src="c:\images\mypic.jpg"> would cause user browser to access image from his filesystem. if you have to store images in folder located in c:\images i would suggest to create an servlet like images.jsp, that as a parameter takes name of a file, then sets servlet response content to an image/jpg and then loads bytes of image from server location and put it to a response.

But what you use to create your application? is it pure servlet? Spring? JSF?

Here you can find some info about, how to do it.

How to redirect to action from JavaScript method?

Use the @Url.Action method. This will work and determines the correct route regardless of what IIS server you deploy to.

Example- window.location.href="@Url.Action("Action", "Controller")";

so in the case of the Index action on the Home controller - window.location.href="@Url.Action("Index", "Home")";

How do I create JavaScript array (JSON format) dynamically?

var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);

RedirectToAction with parameter

The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.

[Route("/to/{email?}")]
public IActionResult ToAction(string email)
{
    return View("To", email);
}
[Route("/from")]
public IActionResult FromAction()
{
    ControllerContext.RouteData.Values.Add("email", "[email protected]");
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/[email protected]
}
[Route("/FromAnother/{email?}")]`
public IActionResult FromAnotherAction(string email)
{
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/<whatever the email param says>
         // no need to specify the route part explicitly
}

Performing a Stress Test on Web Application?

I've used JMeter. Besides testing the web server you can also test your database backend, messaging services and email servers.

Command not found after npm install in zsh

In my case, i installed node with NVM and after installing z Shell, node and nvm command didn't worked. So what worked for me was installing nvm again with this command :

wget https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
sudo zsh install.sh

Above commands installed nvm again, since node was already installed, it added the node path automatically in .zshrc file and everything worked.

Excel formula to get ranking position

Try this in your forth column

=COUNTIF(B:B; ">" & B2) + 1

Replace B2 with B3 for next row and so on.

What this does is it counts how many records have more points then current one and then this adds current record position (+1 part).

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Get the index of the object inside an array, matching a condition

function findIndexByKeyValue(_array, key, value) {
    for (var i = 0; i < _array.length; i++) { 
        if (_array[i][key] == value) {
            return i;
        }
    }
    return -1;
}
var a = [
    {prop1:"abc",prop2:"qwe"},
    {prop1:"bnmb",prop2:"yutu"},
    {prop1:"zxvz",prop2:"qwrq"}];
var index = findIndexByKeyValue(a, 'prop2', 'yutu');
console.log(index);

How to strip all whitespace from string

For Python 3:

>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'

...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.

\s on its own always covers the ASCII whitespace:

  • (regular) space
  • tab
  • new line (\n)
  • carriage return (\r)
  • form feed
  • vertical tab

Additionally:

  • for Python 2 with re.UNICODE enabled,
  • for Python 3 without any extra actions,

...\s also covers the Unicode whitespace characters, for example:

  • non-breaking space,
  • em space,
  • ideographic space,

...etc. See the full list here, under "Unicode characters with White_Space property".

However \s DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:

  • zero-width joiner,
  • Mongolian vowel separator,
  • zero-width non-breaking space (a.k.a. byte order mark),

...etc. See the full list here, under "Related Unicode characters without White_Space property".

So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF.

Sources:

Selecting multiple items in ListView

I would advice to check the logic of ListActivity according to what is needed could be the best way not to lose much time

link

developer.android

Linux command for extracting war file?

A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping.

But you probably don't want to do that. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

I added this to my pom.xml below the project description and it worked:

<properties>
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
</properties>

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

Strangely enough, I wrote some code to do this back when 1.1 came out (what was that, seven years ago?) and tweaked it a little when 2.0 came out. I haven't looked at it in years as we no longer manage our servers.

It's not foolproof, but I'm posting it anyway because I find it humorous; in that it's easier to do in .NET and easier still in power shell.

bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart)
{
    DWORD dwHandle;
    DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle);
    if (dwLen) {
        LPBYTE lpData = new BYTE[dwLen];
        if (lpData) {
            if (GetFileVersionInfo(filename,0,dwLen,lpData)) {
                UINT uLen;  
                VS_FIXEDFILEINFO *lpBuffer;  
                VerQueryValue(lpData,_T("\\"),(LPVOID*)&lpBuffer,&uLen);  
                *majorPart = HIWORD(lpBuffer->dwFileVersionMS);
                *minorPart = LOWORD(lpBuffer->dwFileVersionMS);
                *buildPart = HIWORD(lpBuffer->dwFileVersionLS);
                *privatePart = LOWORD(lpBuffer->dwFileVersionLS);
                delete[] lpData;
                return true;
            }
        }
    }
    return false;
}

int _tmain(int argc,_TCHAR* argv[])
{
    _TCHAR filename[MAX_PATH];
    _TCHAR frameworkroot[MAX_PATH];
    if (!GetEnvironmentVariable(_T("systemroot"),frameworkroot,MAX_PATH))
        return 1;
    _tcscat_s(frameworkroot,_T("\\Microsoft.NET\\Framework\\*"));
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
        return 2;
    do {
        if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
            _tcslen(FindFileData.cAlternateFileName) != 0) {
            _tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1);
            filename[_tcslen(frameworkroot)] = 0;
            _tcscat_s(filename,FindFileData.cFileName);
            _tcscat_s(filename,_T("\\mscorlib.dll"));
            WORD majorPart,minorPart,buildPart,privatePart;
            if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) {
                _tprintf(_T("%d.%d.%d.%d\r\n"),majorPart,minorPart,buildPart,privatePart);
            }
        }
    } while (FindNextFile(hFind,&FindFileData) != 0);
    FindClose(hFind);
    return 0;
}

How to convert a hex string to hex number

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

print hex(new_int)[2:]

How to watch for form changes in Angular

For angular 5+ version. Putting version helps as angular makes lot of changes.

ngOnInit() {

 this.myForm = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}

formControlValueChanged(): void {       
        this.myForm.valueChanges.subscribe(value => {
            console.log('value changed', value)
        })
}

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

Easiest way to convert month name to month number in JS ? (Jan = 01)

function getMonthDays(MonthYear) {
  var months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ];

  var Value=MonthYear.split(" ");      
  var month = (months.indexOf(Value[0]) + 1);      
  return new Date(Value[1], month, 0).getDate();
}

console.log(getMonthDays("March 2011"));

Disable hover effects on mobile browsers

Iv'd found 2 solutions to the problem, which its implied that you detect touch with modernizr or something else and set a touch class on the html element.

This is good but not supported very well:

html.touch *:hover {
    all:unset!important;
}

But this has a very good support:

html.touch *:hover {
    pointer-events: none !important;
}

Works flawless for me, it makes all the hover effects be like when you have a touch on a button it will light up but not end up buggy as the initial hover effect for mouse events.

Detecting touch from no-touch devices i think modernizr has done the best job:

https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js

EDIT

I found a better and simpler solution to this issue

How to determine if the client is a touch device

Is not an enclosing class Java

What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class.

Example :

class Outer
{
    class Inner
    {
        //...
    }
}

So, in such case, you can do something like:

Outer o = new Outer();
Outer.Inner obj = o.new Inner();

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Are you sure you cloned it using the ssh url?

The url for origin says url = https://[email protected]/Nicolas_Raoul/therepo.git so if it is using https it will ask for password irrespective of your ssh keys.

So what you want to do is the following:

open your config file in your current repo ..

vim .git/config

and change the line with the url from

[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = https://[email protected]/Nicolas_Raoul/therepo.git

to

[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = [email protected]:Nicolas_Raoul/therepo.git

Set Page Title using PHP

What about using something like:

<?php 
    $page_title = "Your page tile";
    include("navigation.php");             // if required
    echo("<title>$page_title</title>");
?>

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Complete list of reasons why a css file might not be working

The URL http://fakedomain.com/smilemachine/html.css in your <link> Tag is wrong. File not Found.

Using jQuery to see if a div has a child with a certain class

There is a hasClass function

if($('#popup p').hasClass('filled-text'))

How to check if the given string is palindrome?

Using Java, using Apache Commons String Utils:

public boolean isPalindrome(String phrase) {
  phrase = phrase.toLowerCase().replaceAll("[^a-z]", "");
  return StringUtils.reverse(phrase).equals(phrase);
}

How to count the number of occurrences of an element in a List

To get the occurrences of the object from the list directly:

int noOfOccurs = Collections.frequency(animals, "bat");

To get the occurrence of the Object collection inside list, override the equals method in the Object class as:

@Override
public boolean equals(Object o){
    Animals e;
    if(!(o instanceof Animals)){
        return false;
    }else{
        e=(Animals)o;
        if(this.type==e.type()){
            return true;
        }
    }
    return false;
}

Animals(int type){
    this.type = type;
}

Call the Collections.frequency as:

int noOfOccurs = Collections.frequency(animals, new Animals(1));

Summing elements in a list

>>> l = raw_input()
1 2 3 4 5 6 7 8 9 10
>>> l = l.split()
>>> l.pop(0)
'1'
>>> sum(map(int, l)) #or simply sum(int(x) for x in l) , you've to convert the elements to integer first, before applying sum()
54

How to move a git repository into another directory and make that directory a git repository?

It's even simpler than that. Just did this (on Windows, but it should work on other OS):

  1. Create newrepo.
  2. Move gitrepo1 into newrepo.
  3. Move .git from gitrepo1 to newrepo (up one level).
  4. Commit changes (fix tracking as required).

Git just sees you added a directory and renamed a bunch of files. No biggie.

How to play or open *.mp3 or *.wav sound file in c++ program?

I would use FMOD to do this for your game. It has the ability to play any file mostly for sounds and is pretty simple to implement in C++. using FMOD and Dir3ect X together can be powerful and not that difficult. If you are familiar with Singleton classes I would create a Singleton class of a sound manager in your win main cpp and then have access to it whenever to load or play new music or sound effects. here's an audio manager example

    #pragma once

#ifndef H_AUDIOMANAGER
#define H_AUDIOMANAGER

#include <string>
#include <Windows.h>
#include "fmod.h"
#include "fmod.hpp"
#include "fmod_codec.h"
#include "fmod_dsp.h"
#include "fmod_errors.h"
#include "fmod_memoryinfo.h"
#include "fmod_output.h"

class AudioManager
{
public:
    // Destructor
    ~AudioManager(void);

    void Initialize(void);  // Initialize sound components
    void Shutdown(void);    // Shutdown sound components

    // Singleton instance manip methods
    static AudioManager* GetInstance(void);
    static void DestroyInstance(void);

    // Accessors
    FMOD::System* GetSystem(void)
        {return soundSystem;}

    // Sound playing
    void Play(FMOD::Sound* sound);  // Play a sound/music with default channel
    void PlaySFX(FMOD::Sound* sound);   // Play a sound effect with custom channel
    void PlayBGM(FMOD::Sound* sound);   // Play background music with custom channel

    // Volume adjustment methods
    void SetBGMVolume(float volume);
    void SetSFXVolume(float volume);

private:
    static AudioManager* instance;  // Singleton instance
    AudioManager(void);  // Constructor

    FMOD::System* soundSystem;  // Sound system object
    FMOD_RESULT result;
    FMOD::Channel* bgmChannel;  // Channel for background music
    static const int numSfxChannels = 4;
    FMOD::Channel* sfxChannels[numSfxChannels]; // Channel for sound effects
};

#endif

How do I float a div to the center?

There is no float: center; in css. Use margin: 0 auto; instead. So like this:

.mydivclass {
    margin: 0 auto;
 }

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

Create pandas Dataframe by appending one row at a time

You can use df.loc[i], where the row with index i will be what you specify it to be in the dataframe.

>>> import pandas as pd
>>> from numpy.random import randint

>>> df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
>>> for i in range(5):
>>>     df.loc[i] = ['name' + str(i)] + list(randint(10, size=2))

>>> df
     lib qty1 qty2
0  name0    3    3
1  name1    2    4
2  name2    2    8
3  name3    2    1
4  name4    9    6

Django: TemplateSyntaxError: Could not parse the remainder

For me it was using {{ }} instead of {% %}:

href="{{ static 'bootstrap.min.css' }}"  # wrong
href="{% static 'bootstrap.min.css' %}"  # right

How to create a Custom Dialog box in android?

Create custom alert layout custom_aler_update.xml

Then Copy this code to Activity :

AlertDialog basic_reg;
AlertDialog.Builder builder ;
builder = new AlertDialog.Builder(ct, R.style.AppCompatAlertDialogStyle);
LayoutInflater inflater = ((Activity) ct).getLayoutInflater();
View v = inflater.inflate(R.layout.custom_aler_update, null);
builder.setView(v);
builder.setCancelable(false);
builder.create();
basic_reg = builder.show();

Copy this code to style :

<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColorPrimary">@color/primaryTextColor</item>
    <item name="android:background">@color/white</item>
</style>

What is the difference between range and xrange functions in Python 2.X?

It is for optimization reasons.

range() will create a list of values from start to end (0 .. 20 in your example). This will become an expensive operation on very large ranges.

xrange() on the other hand is much more optimised. it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.

add item in array list of android

This will definitely work for you...

ArrayList<String> list = new ArrayList<String>();

list.add(textview.getText().toString());
list.add("B");
list.add("C");

How do I run all Python unit tests in a directory?

Based on the answer of Stephen Cagle I added support for nested test modules.

import fnmatch
import os
import unittest

def all_test_modules(root_dir, pattern):
    test_file_names = all_files_in(root_dir, pattern)
    return [path_to_module(str) for str in test_file_names]

def all_files_in(root_dir, pattern):
    matches = []

    for root, dirnames, filenames in os.walk(root_dir):
        for filename in fnmatch.filter(filenames, pattern):
            matches.append(os.path.join(root, filename))

    return matches

def path_to_module(py_file):
    return strip_leading_dots( \
        replace_slash_by_dot(  \
            strip_extension(py_file)))

def strip_extension(py_file):
    return py_file[0:len(py_file) - len('.py')]

def replace_slash_by_dot(str):
    return str.replace('\\', '.').replace('/', '.')

def strip_leading_dots(str):
    while str.startswith('.'):
       str = str[1:len(str)]
    return str

module_names = all_test_modules('.', '*Tests.py')
suites = [unittest.defaultTestLoader.loadTestsFromName(mname) for mname 
    in module_names]

testSuite = unittest.TestSuite(suites)
runner = unittest.TextTestRunner(verbosity=1)
runner.run(testSuite)

The code searches all subdirectories of . for *Tests.py files which are then loaded. It expects each *Tests.py to contain a single class *Tests(unittest.TestCase) which is loaded in turn and executed one after another.

This works with arbitrary deep nesting of directories/modules, but each directory in between needs to contain an empty __init__.py file at least. This allows the test to load the nested modules by replacing slashes (or backslashes) by dots (see replace_slash_by_dot).

Most efficient way to create a zero filled JavaScript array?

You can check if index exist or not exist, in order to append +1 to it.

this way you don't need a zeros filled array.

EXAMPLE:

var current_year = new Date().getFullYear();
var ages_array = new Array();

for (var i in data) {
    if(data[i]['BirthDate'] != null && data[i]['BirthDate'] != '0000-00-00'){

        var birth = new Date(data[i]['BirthDate']);
        var birth_year = birth.getFullYear();
        var age = current_year - birth_year;

        if(ages_array[age] == null){
            ages_array[age] = 1;
        }else{
            ages_array[age] += 1;
        }

    }
}

console.log(ages_array);

Checking for a null int value from a Java ResultSet

For convenience, you can create a wrapper class around ResultSet that returns null values when ResultSet ordinarily would not.

public final class ResultSetWrapper {

    private final ResultSet rs;

    public ResultSetWrapper(ResultSet rs) {
        this.rs = rs;
    }

    public ResultSet getResultSet() {
        return rs;
    }

    public Boolean getBoolean(String label) throws SQLException {
        final boolean b = rs.getBoolean(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    public Byte getByte(String label) throws SQLException {
        final byte b = rs.getByte(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    // ...

}

How to checkout a specific Subversion revision from the command line?

If you already have it checked out locally then you can cd to where it is checked out, then use this syntax:

$ svn up -rXXXX

ref: Checkout a specific revision from subversion from command line

Difference between \b and \B in regex

Let take a string like :

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-

Note: Underscore ( _ ) is not considered a special character in this case.

  1. /\bX\b/g Should begin and end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\bX/g Should begin with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /X\b/g Should end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\BX\B/g
    Should not begin and not end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\BX/g Should not begin with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /X\B/g Should not end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\bX\B/g Should begin and not end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\BX\b/g Should not begin and should end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-

How to load json into my angular.js ng-model?

As Kris mentions, you can use the $resource service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http service. In this case you can call its get method.

If you have the following JSON

[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

You can load it like this

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;                
        });
});

The get method returns a promise object which first argument is a success callback and the second an error callback.

When you add $http as a parameter of a function Angular does it magic and injects the $http resource into your controller.

I've put some examples here

google-services.json for different productFlavors

UPDATE: The following explanation is for one Android Studio project, with one Firebase Project and different Firebase Apps inside that project. If the aim is to have different JSON files for different Firebase Apps in different Firebase Projects inside the same Android Studio project, (or if you don't know what's the difference) look here..

You need one Firebase App per Android Application ID (usually package name). Is common to have one Application ID per Gradle build variant (This is gonna be likely if you use Gradle build types and Gradle build flavours)


As of Google Services 3.0 and using Firebase it's not necessary to create different files for different flavours. Creating different files for different flavours can be not clear or straightforward in case you have productFlavours and Build types which compose with each other.

In the same file you'll have the all the configurations you need for all your build types and flavours.

In the Firebase console you need to add one app per package name. Imagine that you have 2 flavours (dev and live) and 2 build types (debug and release). Depending on your config but it's likely that you have 4 different package names like:

  • com.stackoverflow.example (live - release)
  • com.stackoverflow.example.dev (live - dev)
  • com.stackoverflow.example.debug (debug - release)
  • com.stackoverflow.example.dev.debug (debug - dev)

You need 4 different Android Apps in the Firebase Console. (On each one you need to add the SHA-1 for debug and live for each computer you are using)

When you download the google-services.json file, actually it doesn't really matter from what app you download it, all of them contain the same info related to all your apps.

Now you need to locate this file in app level (app/).

enter image description here

If you open that file you'll see that if contains all the information for all your package names.

A pain point use to be the plugin. In order to get it working you need to locate the plugin at the bottom of your file. So this line..

apply plugin: 'com.google.gms.google-services'

...needs to be on the bottom of your app build.gradle file.

For most of the said here, it applies to previous versions as well. I've never had different files for different configs, but now with the Firebase console is easier because they provide one single file with everything you need for all you configs.

How to pass multiple checkboxes using jQuery ajax post

From the jquery docs for POST (3rd example):

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like

var data = { 'user_ids[]' : []};
$(":checked").each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

Call javascript from MVC controller action

<script>
    $(document).ready(function () {
        var msg = '@ViewBag.ErrorMessage'
        if (msg.length > 0)
            OnFailure('Register', msg);
    });

    function OnSuccess(header,Message) {
        $("#Message_Header").text(header);
        $("#Message_Text").text(Message);
        $('#MessageDialog').modal('show');
    }

    function OnFailure(header,error)
    {
        $("#Message_Header").text(header);
        $("#Message_Text").text(error);
        $('#MessageDialog').modal('show');
    }
</script>

How to delete a module in Android Studio

As I saw that in Android Studio 0.5.1, you have to close your project by doing simply File -> Close Project then move your mouse over the project which you want to delete then keep your mouse on the same project and press delete then click on "OK" button that would delete your project from Android Studio.

screenshot 1

enter image description here

Get UTC time and local time from NSDate object

The documentation says that the date method returns a new date set to the current date and time regardless of the language used.

The issue probably sits somewhere where you present the date using NSDateFormatter. NSDate is just a point on a time line. There is no time zones when talking about NSDate. I made a test.

Swift

print(NSDate())

Output: 2014-07-23 17:56:45 +0000

Objective-C

NSLog(@"%@", [NSDate date]);

Output: 2014-07-23 17:58:15 +0000

Result - No difference.

Angular 2 : No NgModule metadata found

I had the same problem but none of all those solutions worked for me. After further investigation, I found out that an undesired import was in one of my component.

I use setTimeout function in app.component but for any reason Visual Studio added import { setTimeout } from 'timer'; where it was not needed. Removing this line fixed the issue.

So remember to check your imports before going further. Hope it may help someone.

AttributeError: 'str' object has no attribute 'append'

This is simple program showing append('t') to the list.
n=['f','g','h','i','k']

for i in range(1):
    temp=[]
    temp.append(n[-2:])
    temp.append('t')
    print(temp)

Output: [['i', 'k'], 't']

How to send JSON instead of a query string with $.ajax?

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

After validation and before INSERT check if username already exists, using mysqli(procedural). This works:

//check if username already exists
       include 'phpscript/connect.php'; //connect to your database

       $sql = "SELECT username FROM users WHERE username = '$username'";
       $result = $conn->query($sql);

       if($result->num_rows > 0) {
           $usernameErr =  "username already taken"; //takes'em back to form
       } else { // go on to INSERT new record

How do I authenticate a WebClient request?

You need to give the WebClient object the credentials. Something like this...

 WebClient client = new WebClient();
 client.Credentials = new NetworkCredential("username", "password");

Is it possible to get a list of files under a directory of a website? How?

There are only two ways to find a web page: through a link or by listing the directory.

Usually, web servers disable directory listing, so if there is really no link to the page, then it cannot be found.

BUT: information about the page may get out in ways you don't expect. For example, if a user with Google Toolbar visits your page, then Google may know about the page, and it can appear in its index. That will be a link to your page.

findViewByID returns null

In my case, I was using ExpandableListView and I had set android:transcriptMode="normal". This was causing few children in expandable group to disappear and I used to get NULL exception when ever I used scroll the list.

SQL Server tables: what is the difference between @, # and ##?

CREATE TABLE #t

Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

CREATE TABLE ##t

Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

Importing JSON into an Eclipse project

Download the ZIP file from this URL and extract it to get the Jar. Add the Jar to your build path. To check the available classes in this Jar use this URL.

To Add this Jar to your build path Right click the Project > Build Path > Configure build path> Select Libraries tab > Click Add External Libraries > Select the Jar file Download

I hope this will solve your problem

Skip to next iteration in loop vba

The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.

What you want inside your for loop follows the pattern

If (your condition) Then
    'Do something
End If

In this case, your condition is Not(Return = 0 And Level = 0), so you would use

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If (Not(Return = 0 And Level = 0)) Then
        'Do something
    End If
Next i

PS: the condition is equivalent to (Return <> 0 Or Level <> 0)

PHP __get and __set magic methods

It's because $bar is a public property.

$foo->bar = 'test';

There is no need to call the magic method when running the above.

Deleting public $bar; from your class should correct this.

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

How to set selectedIndex of select element using display text?

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

HTML Image not displaying, while the src url works

In your angular.json folder structure should be like this

"assets": [             
  "src/assets",
  "src/favicon.ico"
],

not this

"assets": [     
  "src/favicon.ico",
  "src/assets",
],

This solved my problem.

How to make a whole 'div' clickable in html and css without JavaScript?

Well you could either add <a></a> tags and place the div inside it, adding an href if you want the div to act as a link. Or else just use Javascript and define an 'OnClick' function. But from the limited information provided, it's a bit hard to determine what the context of your problem is.

What is (x & 1) and (x >>= 1)?

x & 1 is equivalent to x % 2.

x >> 1 is equivalent to x / 2

So, these things are basically the result and remainder of divide by two.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.

How to align checkboxes and their labels consistently cross-browsers

try this code

input[type="checkbox"] {
    -moz-appearance: checkbox;
    -webkit-appearance: checkbox;
    margin-left:3px;
    border:0;
    vertical-align: middle;
    top: -1px;
    bottom: 1px;
    *overflow: hidden;
    box-sizing: border-box; /* 1 */
    *height: 13px; /* Removes excess padding in IE 7 */
    *width: 13px;
    background: #fff;
}

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

Bootstrap 3 Collapse show state with Chevron icon

I wanted a pure html approach as I wanted to collapse and expand html that was added on the fly via a template! I came up with this...

https://jsfiddle.net/3mguht2y/1/

var noJavascript = ":)";

Which might be of use to someone :)

ECMAScript 6 arrow function that returns an object

You may wonder, why the syntax is valid (but not working as expected):

var func = p => { foo: "bar" }

It's because of JavaScript's label syntax:

So if you transpile the above code to ES5, it should look like:

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}

If REST applications are supposed to be stateless, how do you manage sessions?

REST is very abstract. It helps to have some good, simple, real-world examples.

Take for example all major social media apps -- Tumblr, Instagram, Facebook, and Twitter. They all have a forever-scrolling view where the farther you scroll down, the more content you see, further and further back in time. However, we've all experienced that moment where you lose where you were scrolled to, and the app resets you back to the top. Like if you quit the app, then when you reopen it, you're back at the top again.

The reason why, is because the server did not store your session state. Sadly, your scroll position was just stored in RAM on the client.

Fortunately you don't have to log back in when you reconnect, but that's only because your client-side also stored login certificate has not expired. Delete and reinstall the app, and you're going to have to log back in, because the server did not associate your IP address with your session.

You don't have a login session on the server, because they abide by REST.


Now the above examples don't involve a web browser at all, but on the back end, the apps are communicating via HTTPS with their host servers. My point is that REST does not have to involve cookies and browsers etc. There are various means of storing client-side session state.

But lets talk about web browsers for a second, because that brings up another major advantage of REST that nobody here is talking about.

If the server tried to store session state, how is it supposed to identify each individual client?

It could not use their IP address, because many people could be using that same address on a shared router. So how, then?

It can't use MAC address for many reasons, not the least of which because you can be logged into multiple different Facebook accounts simultaneously on different browsers plus the app. One browser can easily pretend to be another one, and MAC addresses are just as easy to spoof.

If the server has to store some client-side state to identify you, it has to store it in RAM longer than just the time it takes to process your requests, or else it has to cache that data. Servers have limited amounts of RAM and cache, not to mention processor speed. Server-side state adds to all three, exponentially. Plus if the server is going to store any state about your sessions then it has to store it separately for each browser and app you're currently logged in with, and also for each different device you use.


So... I hope that you see now why REST is so important for scalability. I hope you can start to see why server-side session state is to server scalability what welded-on anvils are to car acceleration.


Where people get confused is by thinking that "state" refers to, like, information stored in a database. No, it refers to any information that needs to be in the RAM of the server when you're using it.

Android image caching

What actually worked for me was setting ResponseCache on my Main class:

try {
   File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
   long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
   HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { } 

and

connection.setUseCaches(true);

when downloading bitmap.

http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html

What is the 'realtime' process priority setting for?

Simply, the "Real Time" priority class is higher than "High" priority class. I don't think there's much more to it than that. Oh yeah - you have to have the SeIncreaseBasePriorityPrivilege to put a thread into the Real Time class.

Windows will sometimes boost the priority of a thread for various reasons, but it won't boost the priority of a thread into another priority class. It also won't boost the priority of threads in the real-time priority class. So a High priority thread won't get any automatic temporary boost into the Real Time priority class.

Russinovich's "Inside Windows" chapter on how Windows handles priorities is a great resource for learning how this works:

Note that there's absolutely no problem with a thread having a Real-time priority on a normal Windows system - they aren't necessarily for special processes running on dedicatd machines. I imagine that multimedia drivers and/or processes might need threads with a real-time priority. However, such a thread should not require much CPU - it should be blocking most of the time in order for normal system events to get processing.

Regarding C++ Include another class

What is the basic problem in your code?

Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like

ClassTwo obj;

This is because the compiler needs to reserve enough memory for object of type ClassTwo to do so it needs to see the definition of ClassTwo. The most common way to do this in C++ is to split your code in to header files and source files.
The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who's object they create.

Why can't I simply put all code in cpp files and include them in other files?

You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.

How to solve this particular problem?

Your code should be organized as follows:

//File1.h

Define ClassOne 

//File2.h

#include <iostream>
#include <string>


class ClassTwo
{
private:
   string myType;
public:
   void setType(string);
   std::string getType();
}; 

//File1.cpp

#include"File1.h"

Implementation of ClassOne 

//File2.cpp

#include"File2.h"

void ClassTwo::setType(std::string sType)
{
    myType = sType;
}

void ClassTwo::getType(float fVal)
{
    return myType;
} 

//main.cpp

#include <iostream>
#include <string>
#include "file1.h"
#include "file2.h"
using namespace std;

int main()
{

    ClassOne cone;
    ClassTwo ctwo;

    //some codes
}

Is there any alternative means rather than including header files?

If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.

Jquery Change Height based on Browser Size/Resize

Pay attention, there is a bug with Jquery 1.8.0, $(window).height() returns the all document height !

How do I auto-hide placeholder text upon focus using css or jquery?

HTML:

<input type="text" name="name" placeholder="enter your text" id="myInput" />

jQuery:

$('#myInput').focus(function(){
  $(this).attr('placeholder','');
});
$('#myInput').focusout(function(){
  $(this).attr('placeholder','enter your text');
});

How to open link in new tab on html?

target="_blank" attribute will do the job. Just don't forget to add rel="noopener noreferrer" to solve the potential vulnerability. More on that here: https://dev.to/ben/the-targetblank-vulnerability-by-example

<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">Searcher</a>

jQuery attr('onclick')

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

Javascript: Load an Image from url and display

Are you after something like this:

 <html>
 <head>
    <title>Z Test</title>
 </head>
 <body>

<div id="img_home"></div>

<button onclick="addimage()" type="button">Add an image</button>

<script>
function addimage() {
    var img = new Image();
    img.src = "https://www.google.com/images/srpr/logo4w.png"
    img_home.appendChild(img);
}
</script>
</body>

How to merge two arrays in JavaScript and de-duplicate items

Another approach for your review with reduce func:

function mergeDistinct(arResult, candidate){
  if (-1 == arResult.indexOf(candidate)) {
    arResult.push(candidate);
  }
  return arResult;
}

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var arMerge = [];
arMerge = array1.reduce(mergeDistinct, arMerge);
arMerge = array2.reduce(mergeDistinct, arMerge);//["Vijendra","Singh","Shakya"];

force line break in html table cell

It's hard to answer you without the HTML, but in general you can put:

style="width: 50%;"

On either the table cell, or place a div inside the table cell, and put the style on that.

But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.

Post a copy of your HTML and maybe you'll get a better answer.

How can I use pointers in Java?

Not really, no.

Java doesn't have pointers. If you really wanted you could try to emulate them by building around something like reflection, but it would have all of the complexity of pointers with none of the benefits.

Java doesn't have pointers because it doesn't need them. What kind of answers were you hoping for from this question, i.e. deep down did you hope you could use them for something or was this just curiousity?

Where do I find the definition of size_t?

size_t should be defined in your standard library's headers. In my experience, it usually is simply a typedef to unsigned int. The point, though, is that it doesn't have to be. Types like size_t allow the standard library vendor the freedom to change its underlying data types if appropriate for the platform. If you assume size_t is always unsigned int (via casting, etc), you could run into problems in the future if your vendor changes size_t to be e.g. a 64-bit type. It is dangerous to assume anything about this or any other library type for this reason.

Get the date (a day before current time) in Bash

if you have GNU date and i understood you correctly

$ date +%Y:%m:%d -d "yesterday"
2009:11:09

or

$ date +%Y:%m:%d -d "1 day ago"
2009:11:09

Oracle SQL escape character (for a '&')

add this before your request

set define off;

did you specify the right host or port? error on Kubernetes

I got the same trouble since nearly release, seem must use KUBECONFIG explicit

sudo cp /etc/kubernetes/admin.conf $HOME/

sudo chown $(id -u):$(id -g) $HOME/admin.conf

export KUBECONFIG=$HOME/admin.conf

How do I execute a PowerShell script automatically using Windows task scheduler?

After several hours of test and research over the Internet, I've finally found how to start my PowerShell script with task scheduler, thanks to the video Scheduling a PowerShell Script using Windows Task Scheduler by Jack Fruh @sharepointjack.

Program/script -> put full path through powershell.exe

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe

Add arguments -> Full path to the script, and the script, without any " ".

Start in (optional) -> The directory where your script resides, without any " ".

Difference between Git and GitHub

Git — The version control tool that GitHub is built on top of.

GitHub — Our company and the name of our software. We build software and websites to help you interact with Git repositories in a nice way.

GitHub.com — The website you log into to view repositories online.

GitHub Desktop — An application that you can install on your computer to help you synchronize local code with GitHub.com.

source: https://guides.github.com/introduction/getting-your-project-on-github/

querySelectorAll with multiple conditions

With pure JavaScript you can do this (such as SQL) and anything you need, basically:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input type='button' value='F3' class="c2" id="btn_1">_x000D_
<input type='button' value='F3' class="c3" id="btn_2">_x000D_
<input type='button' value='F1' class="c2" id="btn_3">_x000D_
_x000D_
<input type='submit' value='F2' class="c1" id="btn_4">_x000D_
<input type='submit' value='F1' class="c3" id="btn_5">_x000D_
<input type='submit' value='F2' class="c1" id="btn_6">_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<script>_x000D_
    function myFunction() _x000D_
    {_x000D_
        var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');_x000D_
_x000D_
            arrFiltered.forEach(function (el)_x000D_
            {                _x000D_
                var node = document.createElement("p");_x000D_
                _x000D_
                node.innerHTML = el.getAttribute('id');_x000D_
_x000D_
                window.document.body.appendChild(node);_x000D_
            });_x000D_
        }_x000D_
    </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to convert index of a pandas dataframe into a column?

If you want to use the reset_index method and also preserve your existing index you should use:

df.reset_index().set_index('index', drop=False)

or to change it in place:

df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)

For example:

print(df)
          gi  ptt_loc
0  384444683      593
4  384444684      594
9  384444686      596

print(df.reset_index())
   index         gi  ptt_loc
0      0  384444683      593
1      4  384444684      594
2      9  384444686      596

print(df.reset_index().set_index('index', drop=False))
       index         gi  ptt_loc
index
0          0  384444683      593
4          4  384444684      594
9          9  384444686      596

And if you want to get rid of the index label you can do:

df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
   index         gi  ptt_loc
0      0  384444683      593
4      4  384444684      594
9      9  384444686      596

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

Auto-refreshing div with jQuery - setTimeout or another method?

function update() {
  $("#notice_div").html('Loading..'); 
  $.ajax({
    type: 'GET',
    url: 'jbede.php',
    timeout: 2000,
    success: function(data) {
      $("#some_div").html(data);
      $("#notice_div").html(''); 
      window.setTimeout(update, 10000);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Timeout contacting server..');
      window.setTimeout(update, 60000);
    }
});
}
$(document).ready(function() {
    update();
});

This is Better Code

Substring in VBA

Test for ':' first, then take test string up to ':' or end, depending on if it was found

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

get basic SQL Server table structure information

For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"

For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"

Find out where MySQL is installed on Mac OS X

If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/

When you type ls you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.

Source: http://geeksww.com/tutorials/database_management_systems/mysql/installation/how_to_download_and_install_mysql_on_mac_os_x.php

How to add multiple jar files in classpath in linux

Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do

$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java

To run do

$java -cp .:a.jar:b.jar:c.jar HelloWorld

jQuery UI autocomplete with item and id

Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method

http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:

    {"list":[
     {"value": 1, "label": "abc"},
     {"value": 2, "label": "def"},
     {"value": 3, "label": "ghi"}
    ]}

Then on the source portion of the autocomplete method:

    source: function(request, response) {
        $.getJSON("listing.php", {
            term: request.term
        }, function(data) {                     
            var array = data.error ? [] : $.map(data.list, function(m) {
                return {
                    label: m.label,
                    value: m.value
                };
            });
            response(array);
        });
    },
    select: function (event, ui) {
        $("#autocomplete_field").val(ui.item.label); // display the selected text
        $("#field_id").val(ui.item.value); // save selected id to hidden input
        return false;
    }

Hope this helps... all the best!

Postgresql, update if row with some unique value exists, else insert

If INSERTS are rare, I would avoid doing a NOT EXISTS (...) since it emits a SELECT on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql

CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$ 
    DECLARE 
    BEGIN 
        UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2; 
        IF NOT FOUND THEN 
        INSERT INTO tableName values (value, arg1, arg2); 
        END IF; 
    END; 
    $$ LANGUAGE 'plpgsql'; 

This way Postgres will initially try to do a UPDATE. If no rows was affected, it will fall back to emitting an INSERT.

Please initialize the log4j system properly. While running web service

You have to create your own log4j.properties in the classpath folder.

Exit Shell Script Based on Process Exit Code

"set -e" is probably the easiest way to do this. Just put that before any commands in your program.

If statements for Checkboxes

I suggest

if (checkbox.IsChecked == true)
{
    //do something
}

Hope it's helpful ^^

Virtual Memory Usage from Java under Linux, too much memory used

Just a thought, but you may check the influence of a ulimit -v option.

That is not an actual solution since it would limit address space available for all process, but that would allow you to check the behavior of your application with a limited virtual memory.

Fastest method to replace all instances of a character in a string

@Gumbo adding extra answer - user.email.replace(/foo/gi,"bar");

/foo/g - Refers to the all string to replace matching the case sensitive

/foo/gi - Refers to the without case sensitive and replace all For Eg: (Foo, foo, FoO, fOO)

DEMO

Can dplyr package be used for conditional mutating?

Since you ask for other better ways to handle the problem, here's another way using data.table:

require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]

Note the order of conditional statements is reversed to get g correctly. There's no copy of g made, even during the second assignment - it's replaced in-place.

On larger data this would have better performance than using nested if-else, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.


Here's a benchmark on relatively bigger data:

# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT) 
# [1] 10000000        6
DF <- as.data.frame(DT)

DT_fun <- function(DT) {
    DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
    DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
    mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

BASE_fun <- function(DF) { # R v3.1.0
    transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

system.time(ans1 <- DT_fun(DT))
#   user  system elapsed 
#  2.659   0.420   3.107 

system.time(ans2 <- DPLYR_fun(DF))
#   user  system elapsed 
# 11.822   1.075  12.976 

system.time(ans3 <- BASE_fun(DF))
#   user  system elapsed 
# 11.676   1.530  13.319 

identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE

identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE

Not sure if this is an alternative you'd asked for, but I hope it helps.

Reordering arrays

Change 2 to 1 as the first parameter in the splice call when removing the element:

var tmp = playlist.splice(1, 1);
playlist.splice(2, 0, tmp[0]);

How to iterate object keys using *ngFor

If you are using a map() operator on your response,you could maybe chain a toArray() operator to it...then you should be able to iterate through newly created array...at least that worked for me :)

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Best XML parser for Java

I think you should not consider any specific parser implementation. Java API for XML Processing lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).

Basically there are three ways of handling XML in a standard way:

  • SAX This is the simplest API. You read the XML by defining a Handler class that receives the data inside elements/attributes when the XML gets processed in a serial way. It is faster and simpler if you only plan to read some attributes/elements and/or write some values back (your case).
  • DOM This method creates an object tree which lets you modify/access it randomly so it is better for complex XML manipulation and handling.
  • StAX This is in the middle of the path between SAX and DOM. You just write code to pull the data from the parser you are interested in when it is processed.

Forget about proprietary APIs such as JDOM or Apache ones (i.e. Apache Xerces XMLSerializer) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.

There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which.

SQL JOIN and different types of JOINs

What is SQL JOIN ?

SQL JOIN is a method to retrieve data from two or more database tables.

What are the different SQL JOINs ?

There are a total of five JOINs. They are :

  1. JOIN or INNER JOIN
  2. OUTER JOIN

     2.1 LEFT OUTER JOIN or LEFT JOIN
     2.2 RIGHT OUTER JOIN or RIGHT JOIN
     2.3 FULL OUTER JOIN or FULL JOIN

  3. NATURAL JOIN
  4. CROSS JOIN
  5. SELF JOIN

1. JOIN or INNER JOIN :

In this kind of a JOIN, we get all records that match the condition in both tables, and records in both tables that do not match are not reported.

In other words, INNER JOIN is based on the single fact that: ONLY the matching entries in BOTH the tables SHOULD be listed.

Note that a JOIN without any other JOIN keywords (like INNER, OUTER, LEFT, etc) is an INNER JOIN. In other words, JOIN is a Syntactic sugar for INNER JOIN (see: Difference between JOIN and INNER JOIN).

2. OUTER JOIN :

OUTER JOIN retrieves

Either, the matched rows from one table and all rows in the other table Or, all rows in all tables (it doesn't matter whether or not there is a match).

There are three kinds of Outer Join :

2.1 LEFT OUTER JOIN or LEFT JOIN

This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

2.2 RIGHT OUTER JOIN or RIGHT JOIN

This JOIN returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

2.3 FULL OUTER JOIN or FULL JOIN

This JOIN combines LEFT OUTER JOIN and RIGHT OUTER JOIN. It returns rows from either table when the conditions are met and returns NULL value when there is no match.

In other words, OUTER JOIN is based on the fact that: ONLY the matching entries in ONE OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.

Note that `OUTER JOIN` is a loosened form of `INNER JOIN`.

3. NATURAL JOIN :

It is based on the two conditions :

  1. the JOIN is made on all the columns with the same name for equality.
  2. Removes duplicate columns from the result.

This seems to be more of theoretical in nature and as a result (probably) most DBMS don't even bother supporting this.

4. CROSS JOIN :

It is the Cartesian product of the two tables involved. The result of a CROSS JOIN will not make sense in most of the situations. Moreover, we won't need this at all (or needs the least, to be precise).

5. SELF JOIN :

It is not a different form of JOIN, rather it is a JOIN (INNER, OUTER, etc) of a table to itself.

JOINs based on Operators

Depending on the operator used for a JOIN clause, there can be two types of JOINs. They are

  1. Equi JOIN
  2. Theta JOIN

1. Equi JOIN :

For whatever JOIN type (INNER, OUTER, etc), if we use ONLY the equality operator (=), then we say that the JOIN is an EQUI JOIN.

2. Theta JOIN :

This is same as EQUI JOIN but it allows all other operators like >, <, >= etc.

Many consider both EQUI JOIN and Theta JOIN similar to INNER, OUTER etc JOINs. But I strongly believe that its a mistake and makes the ideas vague. Because INNER JOIN, OUTER JOIN etc are all connected with the tables and their data whereas EQUI JOIN and THETA JOIN are only connected with the operators we use in the former.

Again, there are many who consider NATURAL JOIN as some sort of "peculiar" EQUI JOIN. In fact, it is true, because of the first condition I mentioned for NATURAL JOIN. However, we don't have to restrict that simply to NATURAL JOINs alone. INNER JOINs, OUTER JOINs etc could be an EQUI JOIN too.

How can I get a collection of keys in a JavaScript dictionary?

Simply use Object.keys():

_x000D_
_x000D_
var driversCounter = {_x000D_
                      "one": 1,_x000D_
                      "two": 2,_x000D_
                      "three": 3,_x000D_
                      "four": 4,_x000D_
                      "five": 5_x000D_
                     }_x000D_
console.log(Object.keys(driversCounter));
_x000D_
_x000D_
_x000D_

Disable and enable buttons in C#

Update 2019

This is now IsEnabled

 takePicturebutton.IsEnabled = false; // true

How to run sql script using SQL Server Management Studio?

This website has a concise tutorial on how to use SQL Server Management Studio. As you will see you can open a "Query Window", paste your script and run it. It does not allow you to execute scripts by using the file path. However, you can do this easily by using the command line (cmd.exe):

sqlcmd -S .\SQLExpress -i SqlScript.sql

Where SqlScript.sql is the script file name located at the current directory. See this Microsoft page for more examples

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

I am not able launch JNLP applications using "Java Web Start"?

Try Java Web Launcher, rather than Java Web Start Launcher. It worked for me.

Escape double quote in VB string

Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.

Option Explicit

Private Const SEE_MASK_DEFAULT = &H0

Public Enum EShellShowConstants
        essSW_HIDE = 0
        essSW_SHOWNORMAL = 1
        essSW_SHOWMINIMIZED = 2
        essSW_MAXIMIZE = 3
        essSW_SHOWMAXIMIZED = 3
        essSW_SHOWNOACTIVATE = 4
        essSW_SHOW = 5
        essSW_MINIMIZE = 6
        essSW_SHOWMINNOACTIVE = 7
        essSW_SHOWNA = 8
        essSW_RESTORE = 9
        essSW_SHOWDEFAULT = 10
End Enum

Private Type SHELLEXECUTEINFO
        cbSize        As Long
        fMask         As Long
        hwnd          As Long
        lpVerb        As String
        lpFile        As String
        lpParameters  As String
        lpDirectory   As String
        nShow         As Long
        hInstApp      As Long
        lpIDList      As Long     'Optional
        lpClass       As String   'Optional
        hkeyClass     As Long     'Optional
        dwHotKey      As Long     'Optional
        hIcon         As Long     'Optional
        hProcess      As Long     'Optional
End Type

Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long

Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
    Dim SEI As SHELLEXECUTEINFO

    On Error GoTo Err

    'Fill the SEI structure
    With SEI
        .cbSize = Len(SEI)                  ' Bytes of the structure
        .fMask = SEE_MASK_DEFAULT           ' Check MSDN for more info on Mask
        .lpFile = FilePath                  ' Program Path
        .nShow = ShellShowType              ' How the program will be displayed
        .lpDirectory = PathGetFolder(FilePath)
        .lpParameters = EXEParameters       ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
        .hwnd = hWndOwner                   ' Owner window handle

        ' Determine launch type (would recommend checking for Vista or greater here also)
        If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
            .lpVerb = "runas"
        Else
            .lpVerb = "Open"
        End If
    End With

     ExecuteProcess = ShellExecuteEx(SEI)   ' Execute the program, return success or failure

    Exit Function
Err:
    ' TODO: Log Error
    ExecuteProcess = False
End Function

Private Function PathGetFolder(psPath As String) As String
    On Error Resume Next
    Dim lPos As Long
    lPos = InStrRev(psPath, "\")
    PathGetFolder = Left$(psPath, lPos - 1)
End Function

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

"use database_name" command in PostgreSQL

When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.

Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.

Mismatched anonymous define() module

The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:

    <script>
        window.__define = window.define;
        window.__require = window.require;
        window.define = undefined;
        window.require = undefined;
    </script>
    <script src="your-script-file.js"></script>        
    <script>
        window.define = window.__define;
        window.require = window.__require;
        window.__define = undefined;
        window.__require = undefined;
    </script>

Not the neatest but seems to work and has saved a lot of refractoring.

iPhone - Grand Central Dispatch main thread

Async means asynchronous and you should use that most of the time. You should never call sync on main thread cause it will lock up your UI until the task is completed. You Here is a better way to do this in Swift:

runThisInMainThread { () -> Void in
    // Run your code like this:
    self.doStuff()
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

SQL Server: Get data for only the past year

Look up dateadd in BOL

dateadd(yy,-1,getdate())