Programs & Examples On #Sdlc

The Software Development Lifecycle (SDLC) is a process methodology for software development. It includes three main activies: Design, Construction and Deployment/Maintenance. Popular examples of models used during SDLC are waterfall, spiral and agile.

What is the difference between Scrum and Agile Development?

SCRUM :

SCRUM is a type of Agile approach. It is a Framework not a Methodology.

It does not provide detailed instructions to what needs to be done rather most of it is dependent on the team that is developing the software. Because the developing the project knows how the problem can be solved that is why much is left on them

Cross-functional and self-organizing teams are essential in case of scrum. There is no team leader in this case who will assign tasks to the team members rather the whole team addresses the issues or problems. It is cross-functional in a way that everyone is involved in the project right from the idea to the implementation of the project.

The advantage of scrum is that a project’s direction to be adjusted based on completed work, not on speculation or predictions.

Roles Involved : Product Owner, Scrum Master, Team Members

Agile Methodology :

Build Software applications that are unpredictable in nature

Iterative and incremental work cadences called sprints are used in this methodology.

Both Agile and SCRUM follows the system -- some of the features are developed as a part of the sprint and at the end of each sprint; the features are completed right from coding, testing and their integration into the product. A demonstration of the functionality is provided to the owner at the end of each sprint so that feedback can be taken which can be helpful for the next sprint.

Manifesto for Agile Development :

  1. Individuals and interactions over processes and tools
  2. Working software over comprehensive documentation
  3. Customer collaboration over contract negotiation
  4. Responding to change over following a plan

That is, while there is value in the items on the right, we value the items on the left more.

How do I disable directory browsing?

You can place an empty file called index.html into each directory that you don't want listed. This has several advantages:

  • It (usually) requires zero configuration on the server.
  • It will keep working, even if the server administrator decides to use "AllowOverride None" in the the server configuration. (If you use .htaccess files, this can lead to lots of "Error 500 - internal server error" messages for your users!).
  • It also allows you to move your files from one server to the next, again without having to mess with the apache configuration.

Theoretically, the autoindexing might be triggered by a different file (this is controlled by the DirectoryIndex option), but I have yet to encounter this in the real world.

Add a pipe separator after items in an unordered list unless that item is the last on a line

Slightly modified SCSS version which gives you control of the pipe | size and will eliminate padding from first and last list items while respects borders.


$pipe-list-height: 20px;
$pipe-list-padding: 15px;

.pipe-list {
    position: relative;
    overflow: hidden;
    height: $pipe-list-height;

    > ul {
        display: flex;
        flex-direction: row;

        > li {
            position: relative;
            padding: 0 $pipe-list-padding;

            &:after {
                content: " ";
                position: absolute;
                border-right: 1px solid gray;
                top: 10%;
                right: 0;
                height: 75%;
                margin-top: auto;
                margin-bottom: auto;
            }

            &:first-child {
                padding-left: 0;
            }

            &:last-child {
                padding-right: 0;

                &:after {
                    border-right: none;
                }
            }
        }
    }
}
<div class="pipe-list">
  <ul>
    <li>Link</li>
    <li>Link</li>
    <li>Link</li>
  </ul>
</div>

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

I found a workaround to download latest version of ChromeDriver via WebDriverManager You could try something like,

WebDriver driver = null ;
boolean oldVersion = true;
String chromeVersion = "";
try {
    try{
        FileReader reader = new FileReader("chromeVersion.txt") ;
        BufferedReader br = new BufferedReader(reader) ;
        
        String line;
        
        while ((line = br.readLine()) != null){
            chromeVersion = line.trim();
        }
        reader.close();
    } catch (IOException e ) {}
    
    WebDriverManager.chromedriver().version(chromeVersion).setup();
    driver = new ChromeDriver() ;
} catch (Exception e) {
    oldVersion = false;
    String err = e.getMessage() ;
    chromeVersion = err.split("version is")[1].split("with binary path")[0].trim();
    try{
        FileWriter writer = new FileWriter("chromeVersion.txt", true) ;
        writer.write(chromeVersion) ;
        writer.close();
    } catch (IOException er ) {}
}

if (!oldVersion){
    WebDriverManager.chromedriver().version(chromeVersion).setup();
    driver = new ChromeDriver() ;
}

driver.get("https://www.google.com") ;

CSS Background Image Not Displaying

You should use like this:


        body { 
            background: url("img/debut_dark.png") repeat 0 0;
        }

        body { 
            background: url("../img/debut_dark.png") repeat 0 0;
        }

        body { 
            background-image: url("../img/debut_dark.png") repeat 0 0;
        }

or try Inspecting CSS Rules using Firefox Firebug tool.

How can I check if a jQuery plugin is loaded?

To detect jQuery plugins I found more accurate to use the brackets:

if(jQuery().pluginName) {
    //run plugin dependent code
}

is there a function in lodash to replace matched item

If you're just trying to replace one property, lodash _.find and _.set should be enough:

var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];

_.set(_.find(arr, {id: 1}), 'name', 'New Person');

How does collections.defaultdict work?

Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.

It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations. A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key.

A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')

ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'

print(ice_cream['Sarah'])
>>>Chunky Monkey

print(ice_cream['Joe'])
>>>Vanilla

Here is another example on How using defaultdict, we can reduce complexity

from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
    ans = []
    for num in array:
        if ans.count(num) < n:
            ans.append(num)
    return ans

# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
    result = []
    counts = defaultdict(int)

    for i in array:
        if counts[i] < n:
            result.append(i)
            counts[i] += 1
    return result


x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))

In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.

Page redirect with successful Ajax request

You can just redirect in your success handler, like this:

window.location.href = "thankyou.php";

Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:

setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

How do I convert Int/Decimal to float in C#?

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

How can you find out which process is listening on a TCP or UDP port on Windows?

The -b switch mentioned in most answers requires you to have administrative privileges on the machine. You don't really need elevated rights to get the process name!

Find the pid of the process running in the port number (e.g., 8080)

netstat -ano | findStr "8080"

Find the process name by pid

tasklist /fi "pid eq 2216"

find process by TCP/IP port

Instantly detect client disconnection from server socket

Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.

This approach does not suffer the race condition that affects the Poll method in the accepted answer.

// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
    get
    {
        try
        {
            int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);

            if (bytesRead == 0)
                return true;
        }
        catch
        {
            // For a non-blocking socket, a SocketException with 
            // code 10035 (WSAEWOULDBLOCK) indicates no data available.
        }

        return false;
    }
}

The approach is based on the fact that the Socket.Receive method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it. From Socket.Receive documentation:

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.

The second point explains the need for the try-catch.

Use of the SocketFlags.Peek flag leaves any received data untouched for a separate receive mechanism to read.

The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException).

Database Diagram Support Objects cannot be Installed ... no valid owner

USE [ECMIS]
GO
EXEC dbo.sp_changedbowner @loginame = N'sa', @map = false
GO

It works.

Can I use a :before or :after pseudo-element on an input field?

According to a note in the CSS 2.1 spec, the specification “does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” Although input is not really a replaced element any more, the basic situation has not changed: the effect of :before and :after on it in unspecified and generally has no effect.

The solution is to find a different approach to the problem you are trying to address this way. Putting generated content into a text input control would be very misleading: to the user, it would appear to be part of the initial value in the control, but it cannot be modified – so it would appear to be something forced at the start of the control, but yet it would not be submitted as part of form data.

Finding the index of an item in a list

using dictionary , where process the list first and then add the index to it

from collections import defaultdict

index_dict = defaultdict(list)    
word_list =  ['foo','bar','baz','bar','any', 'foo', 'much']

for word_index in range(len(word_list)) :
    index_dict[word_list[word_index]].append(word_index)

word_index_to_find = 'foo'       
print(index_dict[word_index_to_find])

# output :  [0, 5]

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

How to run a stored procedure in oracle sql developer?

Consider you've created a procedure like below.

CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
  FIRST_NAME IN VARCHAR2, 
  LAST_NAME IN VARCHAR2,
  FULL_NAME OUT VARCHAR2 
) IS 
BEGIN
  FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;

In Oracle SQL Developer, you can run this procedure in two ways.

1. Using SQL Worksheet

Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5

DECLARE
  FULL_NAME Varchar2(50);
BEGIN
  GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
  Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;

2. Using GUI Controls

  • Expand Procedures

  • Right click on the procudure you've created and Click Run

  • In the pop-up window, Fill the parameters and Click OK.

Cheers!

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

How to stop C# console applications from closing automatically?

You can just compile (start debugging) your work with Ctrl+F5.

Try it. I always do it and the console shows me my results open on it. No additional code is needed.

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also

// 24 = 192 bits
    private const int SaltByteSize = 24;
    private const int HashByteSize = 24;
    private const int HasingIterationsCount = 10101;


    public static string HashPassword(string password)
    {
        // http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing

        byte[] salt;
        byte[] buffer2;
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
        {
            salt = bytes.Salt;
            buffer2 = bytes.GetBytes(HashByteSize);
        }
        byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
        Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
        Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
        return Convert.ToBase64String(dst);
    }

    public static bool VerifyHashedPassword(string hashedPassword, string password)
    {
        byte[] _passwordHashBytes;

        int _arrayLen = (SaltByteSize + HashByteSize) + 1;

        if (hashedPassword == null)
        {
            return false;
        }

        if (password == null)
        {
            throw new ArgumentNullException("password");
        }

        byte[] src = Convert.FromBase64String(hashedPassword);

        if ((src.Length != _arrayLen) || (src[0] != 0))
        {
            return false;
        }

        byte[] _currentSaltBytes = new byte[SaltByteSize];
        Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);

        byte[] _currentHashBytes = new byte[HashByteSize];
        Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);

        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
        {
            _passwordHashBytes = bytes.GetBytes(SaltByteSize);
        }

        return AreHashesEqual(_currentHashBytes, _passwordHashBytes);

    }

    private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
    {
        int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
        var xor = firstHash.Length ^ secondHash.Length;
        for (int i = 0; i < _minHashLength; i++)
            xor |= firstHash[i] ^ secondHash[i];
        return 0 == xor;
    }

In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.

Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.

For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.


Update 2015-07-27: In addition to the Express Editions, Microsoft now offers Community Editions. These are still free for individual developers, open source contributors, and small teams. There are no Web, Windows, and Windows Desktop releases anymore either; the Community Edition can be used to develop any app type. In addition, the Community Edition does support (3rd party) Add-ins. The Community Edition offers the same functionality as the commercial Professional Edition.

Docker: Container keeps on restarting again on again

First check the logs why the container failed. Because your restart policy might bring your container back to running status. Better to fix the issue, Then probably you can build a new image with/without fix. Later execute below command

docker system prune

https://forums.docker.com/t/docker-registry-in-restarting-1-status-forever/12717/3

What is the GAC in .NET?

Right, so basically it's a way to keep DLLs globally accessible without worrying about conflicts. No more DLL Hell. Each architecture and version gets it's own place to live.

It also gets it own way to browse it in Explorer, so if you go to

C:\Windows\assembly

In windows explorer it lists all the DLLs.

But if you fire up cmd, you can see how it's really structured:

C:\Users\tritter>cd C:\Windows\assembly

C:\Windows\assembly>dir

 Directory of C:\Windows\assembly

07/20/2009  02:18 PM    <DIR>          GAC
06/17/2009  04:22 PM    <DIR>          GAC_32
06/17/2009  04:22 PM    <DIR>          GAC_64
06/17/2009  04:22 PM    <DIR>          GAC_MSIL
 ...snip...
               0 File(s)              0 bytes
               9 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly>cd GAC_64

C:\Windows\assembly\GAC_64>dir

 Directory of C:\Windows\assembly\GAC_64

06/17/2009  04:22 PM    <DIR>          .
06/17/2009  04:22 PM    <DIR>          ..
01/19/2008  09:54 AM    <DIR>          blbproxy
 ...snip...
01/19/2008  09:54 AM    <DIR>          srmlib
01/19/2008  06:11 AM    <DIR>          System.Data
01/19/2008  06:11 AM    <DIR>          System.Data.OracleClient
 ...snip...
               0 File(s)              0 bytes
              34 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly\GAC_64>cd System.Data

C:\Windows\assembly\GAC_64\System.Data>dir
 Directory of C:\Windows\assembly\GAC_64\System.Data

01/19/2008  06:11 AM    <DIR>          .
01/19/2008  06:11 AM    <DIR>          ..
04/11/2009  12:20 PM    <DIR>          2.0.0.0__b77a5c561934e089
               0 File(s)              0 bytes
               3 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly\GAC_64\System.Data>cd 2.0.0.0__b77a5c561934e089

C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089>dir

 Directory of C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089

04/11/2009  12:20 PM    <DIR>          .
04/11/2009  12:20 PM    <DIR>          ..
04/11/2009  12:12 PM         3,008,512 System.Data.dll
               1 File(s)      3,008,512 bytes
               2 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089>

Here you can see version 2.0.0.0__b77a5c561934e089 of System.Data.

A DLL is identified by 5 parts:

  1. Name
  2. Version
  3. Architecture
  4. Culture
  5. Public Key

Although the first 3 are generally the big ones.

How can I plot a confusion matrix?

IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)

enter image description here

including the Heatmap and other options...

You should have fun with the module above, shared in the github ; )

https://github.com/wcipriano/pretty-print-confusion-matrix


This module can do your task easily and produces the output above with a lot of params to customize your CM: enter image description here

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

Downloading and unzipping a .zip file without writing to disk

I'd like to add my Python3 answer for completeness:

from io import BytesIO
from zipfile import ZipFile
import requests

def get_zip(file_url):
    url = requests.get(file_url)
    zipfile = ZipFile(BytesIO(url.content))
    zip_names = zipfile.namelist()
    if len(zip_names) == 1:
        file_name = zip_names.pop()
        extracted_file = zipfile.open(file_name)
        return extracted_file
    return [zipfile.open(file_name) for file_name in zip_names]

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

PHP Function with Optional Parameters

NOTE: This is an old answer, for PHP 5.5 and below. PHP 5.6+ supports default arguments

In PHP 5.5 and below, you can achieve this by using one of these 2 methods:

  • using the func_num_args() and func_get_arg() functions;
  • using NULL arguments;

How to use

function method_1()
{
  $arg1 = (func_num_args() >= 1)? func_get_arg(0): "default_value_for_arg1";
  $arg2 = (func_num_args() >= 2)? func_get_arg(1): "default_value_for_arg2";
}

function method_2($arg1 = null, $arg2 = null)
{
  $arg1 = $arg1? $arg1: "default_value_for_arg1";
  $arg2 = $arg2? $arg2: "default_value_for_arg2";
}

I prefer the second method because it's clean and easy to understand, but sometimes you may need the first method.

Update Git branches from master

You can merge, or you can apply individual commits across branches by using git cherry-pick.

Error: getaddrinfo ENOTFOUND in nodejs for get call

I also had same problem and I fixed it by using right proxy. Please double check your proxy settings if you are using proxy network.

Hope this will help you -

Using margin / padding to space <span> from the rest of the <p>

Try in html:

style="display: inline-block; margin-top: 50px;"

or in css:

display: inline-block;
margin-top: 50px;

CSS3 Transparency + Gradient

Here is my code:

background: #e8e3e3; /* Old browsers */
  background: -moz-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%, rgba(246, 242, 242, 0.95) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(232, 227, 227, 0.95)), color-stop(100%,rgba(246, 242, 242, 0.95))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* IE10+ */
  background: linear-gradient(to bottom,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='rgba(232, 227, 227, 0.95)', endColorstr='rgba(246, 242, 242, 0.95)',GradientType=0 ); /* IE6-9 */

HTML - how can I show tooltip ONLY when ellipsis is activated

If you want to do this solely using javascript, I would do the following. Give the span an id attribute (so that it can easily be retrieved from the DOM) and place all the content in an attribute named 'content':

<span id='myDataId' style='text-overflow: ellipsis; overflow : hidden;
 white-space: nowrap; width: 71;' content='{$myData}'>${myData}</span>

Then, in your javascript, you can do the following after the element has been inserted into the DOM.

var elemInnerText, elemContent;
elemInnerText = document.getElementById("myDataId").innerText;
elemContent = document.getElementById("myDataId").getAttribute('content')
if(elemInnerText.length <= elemContent.length)
{
   document.getElementById("myDataId").setAttribute('title', elemContent); 
}

Of course, if you're using javascript to insert the span into the DOM, you could just keep the content in a variable before inserting it. This way you don't need a content attribute on the span.

There are more elegant solutions than this if you want to use jQuery.

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

Add CSS box shadow around the whole DIV

Yes, don't offset vertically or horizontally, and use a relatively large blur radius: fiddle

Also, you can use multiple box-shadows if you separate them with a comma. This will allow you to fine-tune where they blur and how much they extend. The example I provide is indistinguishable from a large outline, but it can be fine-tuned significantly more: fiddle

You missed the last and most relevant property of box-shadow, which is spread-distance. You can specify a value for how much the shadow expands or contracts (makes my second example obsolete): fiddle

The full property list is:

box-shadow: [horizontal-offset] [vertical-offset] [blur-radius] [spread-distance] [color] inset?

But even better, read through the spec.

How to change an Eclipse default project into a Java project

I deleted the project without removing content. I then created a new Java project from an existing resource. Pointing at my SVN checkout root folder. This worked for me. Although, Chris' way would have been much quicker. That's good to note for future. Thanks!

How to get a jqGrid cell value when editing

My workaround is to attach an object containing orignal values to each tr element in the grid. I've used afterAddRecord callback to get my hands on the values before jqGrid throws them away and jQuery's "data" method to store them in the work.

Example:

afterInsertRow: function( rowid, rowdata, rowelem ) {
  var tr = $("#"+rowid);
  $(tr).data("jqgrid.record_data", rowelem);
},

“rowelem” is the array of cell values from our JSON data feed or [jsonReader] (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#jsonreader_as_function)

Then at any point I can fetch those attributes using:

$(tr).data(“jqgrid.record_data”).

More at: http://wojciech.oxos.pl/post/9423083837/fetching-original-record-values-in-jqgrid

What is the difference between GitHub and gist?

My Personal View of Gist and GitHub:

Gist: Gist is a simple way to share code snippets and pastes with others. It is used when you need to share a sample piece of code or technique with your co-workers or friends.

And

GitHub GitHub, on the other hand, provides a platform to share an entire project as a repo among a team(private repo) or to the whole world(public repo).

Both Will log version details.

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

Go into App/Kernel.php and comment \App\Http\Middleware\VerifyCsrfToken::class.

How to toggle (hide / show) sidebar div using jQuery

The following will work with new versions of jQuery.

$(window).on('load', function(){

    var toggle = false;

    $('button').click(function() {
        toggle = !toggle;

        if(toggle){
            $('#B').animate({left: 0});
        }
        else{
            $('#B').animate({left: 200});
        }

    });
});

Get output parameter value in ADO.NET

You can get your result by below code::

using (SqlConnection conn = new SqlConnection(...))
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add other parameters parameters

    //Add the output parameter to the command object
    SqlParameter outPutParameter = new SqlParameter();
    outPutParameter.ParameterName = "@Id";
    outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
    outPutParameter.Direction = System.Data.ParameterDirection.Output;
    cmd.Parameters.Add(outPutParameter);

    conn.Open();
    cmd.ExecuteNonQuery();

    //Retrieve the value of the output parameter
    string Id = outPutParameter.Value.ToString();

    // *** read output parameter here, how?
    conn.Close();
}

How to assign from a function which returns more than one value?

(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...] like this:

library(gsubfn)  # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()

If you only need the first or second component these all work too:

list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()

(Of course, if you only needed one value then functionReturningTwoValues()[[1]] or functionReturningTwoValues()[[2]] would be sufficient.)

See the cited r-help thread for more examples.

(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with :

myfun <- function() list(a = 1, b = 2)

list[a, b] <- myfun()
a + b

# same
with(myfun(), a + b)

(3) attach Another alternative is attach:

attach(myfun())
a + b

ADDED: with and attach

What is the proper way to comment functions in Python?

Use a docstring, as others have already written.

You can even go one step further and add a doctest to your docstring, making automated testing of your functions a snap.

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

i.e. , = %2C

like in my link suppose i want to order by two fields means in my link it will come like

order_by=id%2Cname which is equal to order_by=id,name .

Check if MySQL table exists or not

Taken from another post

$checktable = mysql_query("SHOW TABLES LIKE '$this_table'");
$table_exists = mysql_num_rows($checktable) > 0;

How to remove all event handlers from an event

This is not an answer to the OP, but I thought I'd post this here in case it can help others.

  /// <summary>
  /// Method to remove a (single) SocketAsyncEventArgs.Completed event handler. This is 
  /// partially based on information found here: http://stackoverflow.com/a/91853/253938
  /// 
  /// But note that this may not be a good idea, being very .Net implementation-dependent. Note 
  /// in particular use of "m_Completed" instead of "Completed".
  /// </summary>
  private static void RemoveCompletedEventHandler(SocketAsyncEventArgs eventArgs)
  {
     FieldInfo fieldInfo = typeof(SocketAsyncEventArgs).GetField("m_Completed", 
                                                BindingFlags.Instance | BindingFlags.NonPublic);
     eventArgs.Completed -= (EventHandler<SocketAsyncEventArgs>)fieldInfo.GetValue(eventArgs);
  }

How to remove all white space from the beginning or end of a string?

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

What does the C++ standard state the size of int, long type to be?

As you mentioned - it largely depends upon the compiler and the platform. For this, check the ANSI standard, http://home.att.net/~jackklein/c/inttypes.html

Here is the one for the Microsoft compiler: Data Type Ranges.

How do I convert an existing callback API to promises?

With plain old vanilla javaScript, here's a solution to promisify an api callback.

function get(url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url);
        xhr.addEventListener('readystatechange', function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log('successful ... should call callback ... ');
                    callback(null, JSON.parse(xhr.responseText));
                } else {
                    console.log('error ... callback with error data ... ');
                    callback(xhr, null);
                }
            }
        });
        xhr.send();
    }

/**
     * @function promisify: convert api based callbacks to promises
     * @description takes in a factory function and promisifies it
     * @params {function} input function to promisify
     * @params {array} an array of inputs to the function to be promisified
     * @return {function} promisified function
     * */
    function promisify(fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return new Promise(function(resolve, reject) {
                fn.apply(null, args.concat(function (err, result) {
                    if (err) reject(err);
                    else resolve(result);
                }));
            });
        }
    }

var get_promisified = promisify(get);
var promise = get_promisified('some_url');
promise.then(function (data) {
        // corresponds to the resolve function
        console.log('successful operation: ', data);
}, function (error) {
        console.log(error);
});

How to print a list with integers without the brackets, commas and no quotes?

If you're using Python 3, or appropriate Python 2.x version with from __future__ import print_function then:

data = [7, 7, 7, 7]
print(*data, sep='')

Otherwise, you'll need to convert to string and print:

print ''.join(map(str, data))

How to remove application from app listings on Android Developer Console

No, you can unpublish but once your application has been live on the market you cannot delete it. (Each package name is unique and Google remembers all package names anyway so you could use this a reminder)

The "Delete" button only works for unpublished version of your app. Once you published your app or a particular version of it, you cannot delete it from the Market. However, you can still "unpublish" it. The "Delete" button is only handy when you uploaded a new version, then you realized you goofed and want to remove that new version before publishing it.

A reference


Update, 2016

you can now filter out unpublished or draft apps from your listing.

enter image description here

Unpublish option can be found in the header area, beside PUBLISHED text. Unpublish link


UPDATE 2020

Due to changes in the new play console, the unpublish option was moved to a different location as follows.
Click All Apps in the left pane. Then click the app you want to remove.

Then under the Setup option in the left pane, Click Advanced Settings.

Then under App Availablity on the right, change the status to UnPublished and click Save Changes at the bottom.

Take a look at the image below:
New UnPublish screenshot

How to make HTML Text unselectable

You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.

If you're targeting decent browsers only, then just make use of CSS3:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
<label class="unselectable">Unselectable label</label>

If you'd like to cover older browsers as well, then consider this JavaScript fallback:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2310734</title>
        <script>
            window.onload = function() {
                var labels = document.getElementsByTagName('label');
                for (var i = 0; i < labels.length; i++) {
                    disableSelection(labels[i]);
                }
            };
            function disableSelection(element) {
                if (typeof element.onselectstart != 'undefined') {
                    element.onselectstart = function() { return false; };
                } else if (typeof element.style.MozUserSelect != 'undefined') {
                    element.style.MozUserSelect = 'none';
                } else {
                    element.onmousedown = function() { return false; };
                }
            }
        </script>
    </head>
    <body>
        <label>Try to select this</label>
    </body>
</html>

If you're already using jQuery, then here's another example which adds a new function disableSelection() to jQuery so that you can use it anywhere in your jQuery code:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2310734 with jQuery</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $.fn.extend({ 
                disableSelection: function() { 
                    this.each(function() { 
                        if (typeof this.onselectstart != 'undefined') {
                            this.onselectstart = function() { return false; };
                        } else if (typeof this.style.MozUserSelect != 'undefined') {
                            this.style.MozUserSelect = 'none';
                        } else {
                            this.onmousedown = function() { return false; };
                        }
                    }); 
                } 
            });

            $(document).ready(function() {
                $('label').disableSelection();            
            });
        </script>
    </head>
    <body>
        <label>Try to select this</label>
    </body>
</html>

How to increase the distance between table columns in HTML?

A better solution than selected answer would be to use border-size rather than border-spacing. The main problem with using border-spacing is that even the first column would have a spacing in the front.

For example,

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 80px 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
  padding: 10px 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First Column</td>_x000D_
    <td>Second Column</td>_x000D_
    <td>Third Column</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1</td>_x000D_
    <td>2</td>_x000D_
    <td>3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

To avoid this use: border-left: 100px solid #FFF; and set border:0px for the first column.

For example,

_x000D_
_x000D_
td,th{_x000D_
  border-left: 100px solid #FFF;_x000D_
}_x000D_
_x000D_
 tr>td:first-child {_x000D_
   border:0px;_x000D_
 }
_x000D_
<table id="t">_x000D_
  <tr>_x000D_
    <td>Column1</td>_x000D_
    <td>Column2</td>_x000D_
    <td>Column3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1000</td>_x000D_
    <td>2000</td>_x000D_
    <td>3000</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Converting json results to a date

You need to extract the number from the string, and pass it into the Date constructor:

var x = [{
    "id": 1,
    "start": "\/Date(1238540400000)\/"
}, {
    "id": 2,
    "start": "\/Date(1238626800000)\/"
}];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0]                - extract the numeric part
x[0].start.match(/\d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

'str' object does not support item assignment in Python

Another approach if you wanted to swap out a specific character for another character:

def swap(input_string):
   if len(input_string) == 0:
     return input_string
   if input_string[0] == "x":
     return "y" + swap(input_string[1:])
   else:
     return input_string[0] + swap(input_string[1:])

Counting Number of Letters in a string variable

If you don't need the leading and trailing spaces :

str.Trim().Length

Max parallel http connections in a browser?

Firefox stores that number in this setting (you find it in about:config): network.http.max-connections-per-server

For the max connections, Firefox stores that in this setting: network.http.max-connections

How to get the Mongo database specified in connection string in C#

With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:

const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");

jQuery SVG vs. Raphael

Oh Raphael has moved on significantly since June. There is a new charting library that can work with it and these are very eye catching. Raphael also supports full SVG path syntax and is incorporating really advanced path methods. Come see 1.2.8+ at my site (Shameless plug) and then bounce over to the Dmitry's site from there. http://www.irunmywebsite.com/raphael/raphaelsource.html

Where to find the complete definition of off_t type?

If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Cleanest version specially good if you just want to get the .value from the element.

document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

We had the same problems with IE11 and new Java. Try to add your site to compatibility view. You can find here how to do it.

How to enable compatibility view in Internet Explorer 11

You can try now if it works or not. After that you can remove site from compatibility view and it should also run.

Google Maps v3 - limit viewable area and zoom level

Better way to restrict zoom level might be to use the minZoom/maxZoom options rather than reacting to events?

var opt = { minZoom: 6, maxZoom: 9 };
map.setOptions(opt);

Or the options can be specified during map initialization, e.g.:

var map = new google.maps.Map(document.getElementById('map-canvas'), opt);

See: Google Maps JavaScript API V3 Reference

Using "label for" on radio buttons

Either structure is valid and accessible, but the for attribute should be equal to the id of the input element:

<input type="radio" ... id="r1" /><label for="r1">button text</label>

or

<label for="r1"><input type="radio" ... id="r1" />button text</label>

The for attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +:

input[type="radio"]:checked+label {font-weight:bold;}

Checking if a list is empty with LINQ

I just wrote up a quick test, try this:

 IEnumerable<Object> myList = new List<Object>();

 Stopwatch watch = new Stopwatch();

 int x;

 watch.Start();
 for (var i = 0; i <= 1000000; i++)
 {
    if (myList.Count() == 0) x = i; 
 }
 watch.Stop();

 Stopwatch watch2 = new Stopwatch();

 watch2.Start();
 for (var i = 0; i <= 1000000; i++)
 {
     if (!myList.Any()) x = i;
 }
 watch2.Stop();

 Console.WriteLine("myList.Count() = " + watch.ElapsedMilliseconds.ToString());
 Console.WriteLine("myList.Any() = " + watch2.ElapsedMilliseconds.ToString());
 Console.ReadLine();

The second is almost three times slower :)

Trying the stopwatch test again with a Stack or array or other scenarios it really depends on the type of list it seems - because they prove Count to be slower.

So I guess it depends on the type of list you're using!

(Just to point out, I put 2000+ objects in the List and count was still faster, opposite with other types)

Sequence contains no matching element

From the MSDN library:

The First<TSource>(IEnumerable<TSource>) method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the FirstOrDefault method.

Formatting PowerShell Get-Date inside string

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:

$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u") 

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

How to set a variable to be "Today's" date in Python/Pandas

You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use to_datetime

>>> pandas.to_datetime('today').normalize()
Timestamp('2015-10-14 00:00:00')

This will always return today's date at midnight, irrespective of the actual time, and can be directly used in pandas to do comparisons etc. Pandas always includes 00:00:00 in its datetimes.

Replacing today with now would give you the date in UTC instead of local time; note that in neither case is the tzinfo (timezone) added.

In pandas versions prior to 0.23.x, normalize may not have been necessary to remove the non-midnight timestamp.

Install GD library and freetype on Linux

For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

Less than or equal to

You can use:

EQU - equal

NEQ - not equal

LSS - less than

LEQ - less than or equal

GTR - greater than

GEQ - greater than or equal

AVOID USING:

() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=

importing a CSV into phpmyadmin

This is happen due to the id(auto increment filed missing). If you edit it in a text editor by adding a comma for the ID field this will be solved.

Making Maven run all tests, even when some fail

A quick answer:

mvn -fn test

Works with nested project builds.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

The best way to do that programmatically is using the next method:

public static DigitsKeyListener getInstance (boolean sign, boolean decimal) 

Returns a DigitsKeyListener that accepts the digits 0 through 9, plus the minus sign (only at the beginning) and/or decimal point (only one per field) if specified.

This solve the problem about the many '.' in EditText

editText.setKeyListener(DigitsKeyListener.getInstance(true,true)); // decimals and positive/negative numbers. 

editText.setKeyListener(DigitsKeyListener.getInstance(false,true)); // positive decimals numbers. 

editText.setKeyListener(DigitsKeyListener.getInstance(false,false)); // positive integer numbers.

editText.setKeyListener(DigitsKeyListener.getInstance(true,false)); // positive/negative integer numbers.

How do I analyze a .hprof file?

Just get the Eclipse Memory Analyzer. There's nothing better out there and it's free.

JHAT is only usable for "toy applications"

How do I get the current GPS location programmatically in Android?

I will recommend using Smart Location Library
Very simple to use and it wraps the location logic nicely.

For starting the location service:

SmartLocation.with(context).location()
    .start(new OnLocationUpdatedListener() { ... });

If you just want to get a single location (not periodic) you can just use the oneFix modifier. Example:

SmartLocation.with(context).location()
    .oneFix()
    .start(new OnLocationUpdatedListener() { ... });

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

Difference between adjustResize and adjustPan in android?

You can use android:windowSoftInputMode="stateAlwaysHidden|adjustResize" in AndroidManifest.xml for your current activity, and use android:fitsSystemWindows="true" in styles or rootLayout.

Does file_get_contents() have a timeout setting?

As @diyism mentioned, "default_socket_timeout, stream_set_timeout, and stream_context_create timeout are all the timeout of every line read/write, not the whole connection timeout." And the top answer by @stewe has failed me.

As an alternative to using file_get_contents, you can always use curl with a timeout.

So here's a working code that works for calling links.

$url='http://example.com/';
$ch=curl_init();
$timeout=5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$result=curl_exec($ch);
curl_close($ch);
echo $result;

Explanation of BASE terminology

ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.

BASE stands for -

  • Basic Availability - The database appears to work most of the time.
  • Soft-state - Stores don't have to be write-consistent, nor do different replicas have to be mutually consistent all the time.
  • Eventual consistency - Stores exhibit consistency at some later point (e.g., lazily at read time).

Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.

Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.

Auto submit form on page load

Try this On window load submit your form.

window.onload = function(){
  document.forms['member_signup'].submit();
}

Set language for syntax highlighting in Visual Studio Code

In the very right bottom corner, left to the smiley there was the icon saying "Plain Text". When you click it, the menu with all languages appears where you can choose your desired language.

VSCode

jQuery: Get height of hidden element in jQuery

I ran into the same problem with getting hidden element width, so I wrote this plugin call jQuery Actual to fix it. Instead of using

$('#some-element').height();

use

$('#some-element').actual('height');

will give you the right value for hidden element or element has a hidden parent.

Full documentation please see here. There is also a demo include in the page.

Hope this help :)

What is the most efficient way to store a list in the Django models?

Storing a list of strings in Django model:

class Bar(models.Model):
    foo = models.TextField(blank=True)

    def set_list(self, element):
        if self.foo:
            self.foo = self.foo + "," + element
        else:
            self.foo = element

    def get_list(self):
        if self.foo:
            return self.foo.split(",")
        else:
            None

and you can call it like this:

bars = Bar()
bars.set_list("str1")
bars.set_list("str2")
list = bars.get_list()
if list is not None:
    for bar in list:
        print bar
else:
    print "List is empty."      

What is the current directory in a batch file?

Just my 2 cents. The following command fails if called from batch file (Windows 7) placed on pendrive:

xcopy /s /e /i %cd%Ala C:\KS\Ala

But this does the job:

xcopy /s /e /i %~dp0Ala C:\KS\Ala

Simplest way to read json from a URL in java

Using the Maven artifact org.json:json I got the following code, which I think is quite short. Not as short as possible, but still usable.

package so4308554;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I know this question has already an answer that gives a solution. But I want to give you my two cents to help people to understand the problem. Getting same issue I've created a specific question. I got same problem, but only with PHPStorm. And exactly when I try to run test from the editor.

dyld is the dynamic linker

I sow that dyld was looking for /usr/local/lib/libpng15.15.dylib but inside my /usr/local/lib/ there was not. In that folder, I got libpng16.16.dylib.

Thanks to a comment, I undestand that my /usr/bin/php was a pointer to php 5.5.8. Instead, ... /usr/local/bin/php was 5.5.14. PHPStorm worked with /usr/bin/php that is default configuration. When I run php via console, I run /urs/local/bin/php.

So, ... If you get some dyld error, maybe you have some wrong php configuration. That's the reason because

$ brew update && brew upgrade
$ brew reinstall php55

But I dont know why this do not solve the problem to me. Maybe because I have

How to install latest version of git on CentOS 7.x/6.x

You can use WANDisco's CentOS repository to install Git 2.x: for CentOS 6, for CentOS 7

  1. Install WANDisco repo package:

    yum install http://opensource.wandisco.com/centos/6/git/x86_64/wandisco-git-release-6-1.noarch.rpm
    - or -
    yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-1.noarch.rpm
    - or -
    yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-2.noarch.rpm
    
  2. Install the latest version of Git 2.x:

    yum install git
    
  3. Verify the version of Git that was installed:

    git --version
    

As of 02 Mar. 2020, the latest available version from WANDisco is 2.22.0.

Hibernate Criteria for Dates

If the column is a timestamp you can do the following:

        if(fromDate!=null){
            criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')"));
        }
        if(toDate!=null){               
            criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')"));
        }

        resultDB = criteria.list();

MD5 is 128 bits but why is it 32 characters?

I wanted summerize some of the answers into one post.

First, don't think of the MD5 hash as a character string but as a hex number. Therefore, each digit is a hex digit (0-15 or 0-F) and represents four bits, not eight.

Taking that further, one byte or eight bits are represented by two hex digits, e.g. b'1111 1111' = 0xFF = 255.

MD5 hashes are 128 bits in length and generally represented by 32 hex digits.

SHA-1 hashes are 160 bits in length and generally represented by 40 hex digits.

For the SHA-2 family, I think the hash length can be one of a pre-determined set. So SHA-512 can be represented by 128 hex digits.

Again, this post is just based on previous answers.

Using the "start" command with parameters passed to the started program

You can use quotes by using the [/D"Path"] use /D only for specifying the path and not the path+program. It appears that all code on the same line that follows goes back to normal meaning you don't need to separate path and file.

    start  /D "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

or:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

will start IE with default web page.

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE www.bing.com

starts with Bing, but does not reset your home page.

/D stands for "directory" and using quotes is OK!

WRONG EXAMPLE:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\IEXPLORE.EXE"

gives:

ERROR "The current directory is invalid."

/D must only be followed by a directory path. Then space and the batchfile or program you wish to start/run

Tested and works under XP but windows Vista/7/8 may need some adjustments to UAC.

-Mrbios

How to center horizontally div inside parent div

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

Download the Android SDK components for offline install

You can download manually by parsing the XMLs that you see in Android SDK Manager log.
Currently the XMLs are addon_list and repository. These xmls can change over a course of time.

It has the location of the SDKs, you can browse to the link and download directly via browser. These files has to be placed under proper folder, example the files of google APIs has to be placed under add-ons, if you don't know where the files has to go.

Here is something to help you.
The blogpost from my blog to Install Android SDKs offline --> Offline Installation of Android SDK's

XPath OR operator for different nodes

It the element has two xpath. Then you can write two xpaths like below:

xpath1 | xpath2

Eg:

//input[@name="username"] | //input[@id="wm_login-username"]

What is unit testing and how do you do it?

I find the easiest way to illustrate it is to look at some code. This getting started page on the NUnit site is a good introduction to the what and the how

http://www.nunit.org/index.php?p=quickStart&r=2.5

Is everything testable? Generally if it calculates something then yes. UI code is a whole other problem to deal with though, as simulating users clicking on buttons is tricky.

What should you test? I tend to write tests around the things I know are going to be tricky. Complicated state transitions, business critical calculations, that sort of thing. Generally I'm not too worried about testing basic input/output stuff, although the purists will doubtless say I'm wrong on that front and everything should be tested. Like so many other things, there is no right answer!

Set background color of WPF Textbox in C# code

I take it you are creating the TextBox in XAML?

In that case, you need to give the text box a name. Then in the code-behind you can then set the Background property using a variety of brushes. The simplest of which is the SolidColorBrush:

myTextBox.Background = new SolidColorBrush(Colors.White);

How to use GROUP BY to concatenate strings in SQL Server?

An example would be

In Oracle you can use LISTAGG aggregate function.

Original records

name   type
------------
name1  type1
name2  type2
name2  type3

Sql

SELECT name, LISTAGG(type, '; ') WITHIN GROUP(ORDER BY name)
FROM table
GROUP BY name

Result in

name   type
------------
name1  type1
name2  type2; type3

Android offline documentation and sample codes

This thread is a little old, and I am brand new to this, but I think I found the preferred solution.

First, I assume that you are using Eclipse and the Android ADT plugin.

In Eclipse, choose Window/Android SDK Manager. In the display, expand the entry for the MOST RECENT PLATFORM, even if that is not the platform that your are developing for. As of Jan 2012, it is "Android 4.0.3 (API 15)". When expanded, the first entry is "Documentation for Android SDK" Click the checkbox next to it, and then click the "Install" button.

When done, you should have a new directory in your "android-sdks" called "doc". Look for "offline.html" in there. Since this is packaged with the most recent version, it will document the most recent platform, but it should also show the APIs for previous versions.

Should IBOutlets be strong or weak under ARC?

One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:

https://developer.apple.com/videos/play/wwdc2015/407/

Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.

This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8

As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4

As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57

As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6

As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5

As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23

All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)

Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.

I hope this clarifies the subject a bit better!

Take care.

How do I copy a version of a single file from one git branch to another?

1) Ensure you're in branch where you need a copy of the file. for eg: i want sub branch file in master so you need to checkout or should be in master git checkout master

2) Now checkout specific file alone you want from sub branch into master,

git checkout sub_branch file_path/my_file.ext

here sub_branch means where you have that file followed by filename you need to copy.

Why can't Python import Image from PIL?

do from PIL import Image, ImageTk

HTTP vs HTTPS performance

The current top answer is not fully correct.

As others have pointed out here, https requires handshaking and therefore does more TCP/IP roundtrips.

In a WAN environment typically then the latency becomes the limiting factor and not the increased CPU usage on the server.

Just keep in mind that the latency from Europe to the US can be around 200 ms (torundtrip time).

You can easily measure this (for the single user case) with HTTPWatch.

Unresponsive KeyListener for JFrame

If you don't want to register a listener on every component,
you could add your own KeyEventDispatcher to the KeyboardFocusManager:

public class MyFrame extends JFrame {    
    private class MyDispatcher implements KeyEventDispatcher {
        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_PRESSED) {
                System.out.println("tester");
            } else if (e.getID() == KeyEvent.KEY_RELEASED) {
                System.out.println("2test2");
            } else if (e.getID() == KeyEvent.KEY_TYPED) {
                System.out.println("3test3");
            }
            return false;
        }
    }
    public MyFrame() {
        add(new JTextField());
        System.out.println("test");
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.addKeyEventDispatcher(new MyDispatcher());
    }

    public static void main(String[] args) {
        MyFrame f = new MyFrame();
        f.pack();
        f.setVisible(true);
    }
}

SQL Server: Query fast, but slow from procedure

I found the problem, here's the script of the slow and fast versions of the stored procedure:

dbo.ViewOpener__RenamedForCruachan__Slow.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
    @SessionGUID uniqueidentifier
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

dbo.ViewOpener__RenamedForCruachan__Fast.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
    @SessionGUID uniqueidentifier 
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:

Slow: SET ANSI_NULLS OFF

Fast: SET ANSI_NULLS ON


This answer also could be made to make sense, since the view does have a join clause that says:

(table.column IS NOT NULL)

So there is some NULLs involved.


The explanation is further proved by returning to Query Analizer, and running

SET ANSI_NULLS OFF

.

DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'

.

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank

And the query is slow.


So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.

Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:

Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....

Multiple glibc libraries on a single host

If you look closely at the second output you can see that the new location for the libraries is used. Maybe there are still missing libraries that are part of the glibc.

I also think that all the libraries used by your program should be compiled against that version of glibc. If you have access to the source code of the program, a fresh compilation appears to be the best solution.

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

IntelliJ how to zoom in / out

Double click shift, type zoom and switch zoom to on

enter image description here

Fade Effect on Link Hover?

Try this in your css:

.a {
    transition: color 0.3s ease-in-out;
}
.a {
    color:turquoise;
}
.a:hover {
    color: #454545;
}

How can I list all of the files in a directory with Perl?

readdir() does that.

Check http://perldoc.perl.org/functions/readdir.html

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;

Creating a LinkedList class from scratch

class Node
{
  int data;
     Node link;

     public Node()
     {
         data=0;
         link=null;
        }

     Node ptr,start,temp;

    void create()throws  IOException
     {
         int n;
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
         System.out.println("Enter first data");
         this.data=Integer.parseInt(br.readLine());
         ptr=this;
         start=ptr;
         char ins ='y';
         do
         {
             System.out.println("Wanna Insert another node???");
             ins=(char)br.read();
             br.read();
             if(ins=='y')
             {
                 temp=new Node();
                 System.out.println("Enter next data");
                 temp.data=Integer.parseInt(br.readLine());
                 temp.link=null;
                 ptr.link=temp;
                 temp=null;
                 ptr=ptr.link;
                }
            }while(ins=='y');
        }

public static void main(String args[])throws IOException
     {
       Node first= new Node();
       first.create();
}
}

Setting width/height as percentage minus pixels

You can use calc:

height: calc(100% - 18px);

Note that some old browsers don't support the CSS3 calc() function, so implementing the vendor-specific versions of the function may be required:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);

How do you remove a Cookie in a Java Servlet

In my environment, following code works. Although looks redundant at first glance, cookies[i].setValue(""); and cookies[i].setPath("/"); are necessary to clear the cookie properly.

private void eraseCookie(HttpServletRequest req, HttpServletResponse resp) {
    Cookie[] cookies = req.getCookies();
    if (cookies != null)
        for (Cookie cookie : cookies) {
            cookie.setValue("");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }
}

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

The basic premise of the question and the answers are wrong. Every Select in a union can have a where clause. It's the ORDER BY in the first query that's giving yo the error.

Getting a list item by index

.NET List data structure is an Array in a "mutable shell".

So you can use indexes for accessing to it's elements like:

var firstElement = myList[0];
var secondElement = myList[1];

Starting with C# 8.0 you can use Index and Range classes for accessing elements. They provides accessing from the end of sequence or just access a specific part of sequence:

var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive

You can combine indexes and ranges together:

var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together

Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.

Combination of async function + await + setTimeout

Since Node 7.6, you can combine the functions promisify function from the utils module with setTimeout() .

Node.js

const sleep = require('util').promisify(setTimeout)

Javascript

const sleep = m => new Promise(r => setTimeout(r, m))

Usage

(async () => {
    console.time("Slept for")
    await sleep(3000)
    console.timeEnd("Slept for")
})()

How do I convert from BLOB to TEXT in MySQL?

You can do it very easily.

ALTER TABLE `table_name` CHANGE COLUMN `column_name` `column_name` LONGTEXT NULL DEFAULT NULL ;

The above query worked for me. I hope it helps you too.

C++ Structure Initialization

It's not implemented in C++. (also, char* strings? I hope not).

Usually if you have so many parameters it is a fairly serious code smell. But instead, why not simply value-initialize the struct and then assign each member?

How to use XMLReader in PHP?

For xml formatted with attributes...

data.xml:

<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>

php code:

$reader = new XMLReader();

if (!$reader->open("data.xml")) {
    die("Failed to open 'data.xml'");
}

while($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
    $address = $reader->getAttribute('address');
    $latitude = $reader->getAttribute('lat');
    $longitude = $reader->getAttribute('lng');
}

$reader->close();

JRE installation directory in Windows

Look the answer to my previous question here

c:\> for %i in (java.exe) do @echo.   %~$PATH:i
C:\WINDOWS\system32\java.exe

Can I change the fill color of an svg path with CSS?

Put in all your svg:

fill="var(--svgcolor)"

In Css:

:root {
  --svgcolor: tomato;
}

To use pseudo-classes:

span.github:hover {
  --svgcolor:aquamarine;
}

Explanation

root = html page.
--svgcolor = a variable.
span.github = selecting a span element with a class github, a svg icon inside and assigning pseudo-class hover.

Use "ENTER" key on softkeyboard instead of clicking button

this is a sample of one of my app how i handle

 //searching for the Edit Text in the view    
    final EditText myEditText =(EditText)view.findViewById(R.id.myEditText);
        myEditText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                 if (event.getAction() == KeyEvent.ACTION_DOWN)
                      if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
                             (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                //do something
                                //true because you handle the event
                                return true;
                               }
                       return false;
                       }
        });

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

Best way to create a simple python web service

Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.

It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging).

Find all paths between two graph nodes

You usually don't want to, because there is an exponential number of them in nontrivial graphs; if you really want to get all (simple) paths, or all (simple) cycles, you just find one (by walking the graph), then backtrack to another.

How to use Greek symbols in ggplot2?

Simplest solution: Use Unicode Characters

No expression or other packages needed.
Not sure if this is a newer feature for ggplot, but it works. It also makes it easy to mix Greek and regular text (like adding '*' to the ticks)

Just use unicode characters within the text string. seems to work well for all options I can think of. Edit: previously it did not work in facet labels. This has apparently been fixed at some point.

library(ggplot2)
ggplot(mtcars, 
       aes(mpg, disp, color=factor(gear))) + 
  geom_point() + 
  labs(title="Title (\u03b1 \u03a9)", # works fine
       x= "\u03b1 \u03a9 x-axis title",    # works fine
       y= "\u03b1 \u03a9 y-axis title",    # works fine
       color="\u03b1 \u03a9 Groups:") +  # works fine
  scale_x_continuous(breaks = seq(10, 35, 5), 
                     labels = paste0(seq(10, 35, 5), "\u03a9*")) + # works fine; to label the ticks
  ggrepel::geom_text_repel(aes(label = paste(rownames(mtcars), "\u03a9*")), size =3) + # works fine 
  facet_grid(~paste0(gear, " Gears \u03a9"))

Created on 2019-08-28 by the reprex package (v0.3.0)

How to display two digits after decimal point in SQL Server

select cast(your_float_column as decimal(10,2))
from your_table

decimal(10,2) means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99

Make absolute positioned div expand parent div height

There is a better way to do this now. You can use the bottom property.

    .my-element {
      position: absolute;
      bottom: 30px;
    }

How do I handle ImeOptions' done button click?

More details on how to set the OnKeyListener, and have it listen for the Done button.

First add OnKeyListener to the implements section of your class. Then add the function defined in the OnKeyListener interface:

/*
 * Respond to soft keyboard events, look for the DONE press on the password field.
 */
public boolean onKey(View v, int keyCode, KeyEvent event)
{
    if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
        (keyCode == KeyEvent.KEYCODE_ENTER))
    {
        // Done pressed!  Do something here.
    }
    // Returning false allows other listeners to react to the press.
    return false;
}

Given an EditText object:

EditText textField = (EditText)findViewById(R.id.MyEditText);
textField.setOnKeyListener(this);

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Short ES6 code

const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}
const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin http://github.com/group/project.git   # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

how to break the _.each function in underscore.js

It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.

http://underscorejs.org/#each

How to list all `env` properties within jenkins pipeline job?

According to Jenkins documentation for declarative pipeline:

sh 'printenv'

For Jenkins scripted pipeline:

echo sh(script: 'env|sort', returnStdout: true)

The above also sorts your env vars for convenience.

HashMap with multiple values under the same key

Try LinkedHashMap, sample:

Map<String,String> map = new LinkedHashMap<String,String>();    
map.put('1','linked');map.put('1','hash');    
map.put('2','map');map.put('3','java');.. 

output:

keys: 1,1,2,3

values: linked,hash, map, java

How do I programmatically force an onchange event on an input?

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

In Windows cmd, how do I prompt for user input and use the result in another command?

set /p choice= "Please Select one of the above options :" 
echo '%choice%'

The space after = is very important.

How to get a cookie from an AJAX response?

The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!

For this to work you need to:

1) login with the ajax request from which you expect cookies to be returned:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) Connect with xhrFields: { withCredentials: true } in the next ajax request(s) to use the credentials saved by the browser

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

The browser takes care of these cookies for you even though they are not readable from the headers nor the document.cookie

Where is NuGet.Config file located in Visual Studio project?

Visual Studio reads NuGet.Config files from the solution root. Try moving it there instead of placing it in the same folder as the project.

You can also place the file at %appdata%\NuGet\NuGet.Config and it will be used everywhere.

https://docs.microsoft.com/en-us/nuget/schema/nuget-config-file

How can I get the baseurl of site?

This is a much more fool proof method.

VirtualPathUtility.ToAbsolute("~/");

How do I determine whether my calculation of pi is accurate?

The Taylor series is one way to approximate pi. As noted it converges slowly.

The partial sums of the Taylor series can be shown to be within some multiplier of the next term away from the true value of pi.

Other means of approximating pi have similar ways to calculate the max error.

We know this because we can prove it mathematically.

How do I exit a WPF application programmatically?

As wuminqi said, Application.Current.Shutdown(); is irreversible, and I believe it is typically used to force an application to close at times such as when a user is logging off or shutting down Windows.

Instead, call this.close() in your main window. This is the same as pressing Alt + F4 or the close [x] button on the window. This will cause all other owned windows to close and will end up calling Application.Current.Shutdown(); so long as the close action wasn't cancelled. Please see the MSDN documentation on Closing a Window.

Also, because this.close() is cancellable you can put in a save changes confirmation dialog in the closing event handler. Simply make an event handler for <Window Closing="..."> and change e.Cancel accordingly. (See the MSDN documentation for more details on how to do this.)

How do I send an HTML Form in an Email .. not just MAILTO

You are making sense, but you seem to misunderstand the concept of sending emails.

HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.

Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST superglobal) and use the email sending function (mail()).

Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.

A simple example code:

form.html:

<form method="post" action="email.php">
    <input type="text" name="subject" /><br />
    <textarea name="message"></textarea>
</form>

email.php:

<?php
    mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>

Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).

Why aren't Xcode breakpoints functioning?

Solution for me with XCode 9.4.1 (did not stop at any breakpoint):

Under build Target -> Build Settings -> Optimization Level: Switched from "Optimize for speed" -> "No optimization" (now it's slower but works)

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

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

Declaring variables inside or outside of a loop

if you want to use str outside looop also; declare it outside. otherwise, 2nd version is fine.

How to implement a lock in JavaScript

Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.

I suspect you need to just set a semaphore (flagging system) between your buttons.

How to fix "Headers already sent" error in PHP

You do

printf ("Hi %s,</br />", $name);

before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.

Difference between ProcessBuilder and Runtime.exec()

There are no difference between ProcessBuilder.start() and Runtime.exec() because implementation of Runtime.exec() is:

public Process exec(String command) throws IOException {
    return exec(command, null, null);
}

public Process exec(String command, String[] envp, File dir)
    throws IOException {
    if (command.length() == 0)
        throw new IllegalArgumentException("Empty command");

    StringTokenizer st = new StringTokenizer(command);
    String[] cmdarray = new String[st.countTokens()];
    for (int i = 0; st.hasMoreTokens(); i++)
        cmdarray[i] = st.nextToken();
    return exec(cmdarray, envp, dir);
}

public Process exec(String[] cmdarray, String[] envp, File dir)
    throws IOException {
    return new ProcessBuilder(cmdarray)
        .environment(envp)
        .directory(dir)
        .start();
}

So code:

List<String> list = new ArrayList<>();
new StringTokenizer(command)
.asIterator()
.forEachRemaining(str -> list.add((String) str));
new ProcessBuilder(String[])list.toArray())
            .environment(envp)
            .directory(dir)
            .start();

should be the same as:

Runtime.exec(command)

Thanks dave_thompson_085 for comment

How to access data/data folder in Android device?

One of the simple way is to create your database on SD-Card. Because you cannot get access to your phone's data folder in internal memory, unless you root your phone. So why not simply create your database on SD-Card.

Moreover, if you want, you may write some file copying-code to copy your existing database file (from internal memory) to external memory without requiring any root.

What is a wrapper class?

A wrapper class is a class that is used to wrap another class to add a layer of indirection and abstraction between the client and the original class being wrapped.

Calling a Javascript Function from Console

I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:

function indirect(js) { return eval(js); }

With that function in each module, you can then execute any code in the context of it.

E.g. if you had this import in your module:

import { imported_fn } from "./import.js";

You could then get the results of calling imported_fn from the console by doing this:

indirect("imported_fn()");

Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

Switch: Multiple values in one case?

Separate the business rules for age from the actions e.g. (NB just typed, not checked)

enum eAgerange { eChild, eYouth, eAdult, eAncient};
eAgeRange ar;
if(age <= 8) ar = eChild;
else if(age <= 15) ar = eYouth;
else if(age <= 100) ar = eAdult;
else ar = eAncient;
switch(ar)
{
 case eChild: 
     // action
 case eYouth:
     // action
 case eAdult:
     // action
 case eAncient:
     // action
 default: throw new NotImplementedException($"Oops {ar.ToString()} not handled");
}   

`

Checking Bash exit status of several commands efficiently

Sorry that I can not make a comment to the first answer But you should use new instance to execute the command: cmd_output=$($@)

#!/bin/bash

function check_exit {
    cmd_output=$($@)
    local status=$?
    echo $status
    if [ $status -ne 0 ]; then
        echo "error with $1" >&2
    fi
    return $status
}

function run_command() {
    exit 1
}

check_exit run_command

ADB.exe is obsolete and has serious performance problems

Try factory reset to virtual device from Android Device Manager

enter image description here

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

<img>: Unsafe value used in a resource URL context

I'm using rc.4 and this method works for ES2015(ES6):

import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
  static get parameters() {
    return [NavController, App, MenuController, DomSanitizationService];
  }

  constructor(nav, app, menu, sanitizer) {

    this.app = app;
    this.nav = nav;
    this.menu = menu;
    this.sanitizer = sanitizer;    
  }

  photoURL() {
    return this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
  }
}

In the HTML:

<iframe [src]='photoURL()' width="640" height="360" frameborder="0"
    webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>

Using a function will ensure that the value doesn't change after you sanitize it. Also be aware that the sanitization function you use depends on the context.

For images, bypassSecurityTrustUrl will work but for other uses you need to refer to the documentation:

https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

laravel compact() and ->with()

I was able to use

return View::make('myviewfolder.myview', compact('view1','view2','view3'));

I don't know if it's because I am using PHP 5.5 it works great :)

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

I faced this issue deploying on Dokku, for some reason it was choosing JDK 1.7

Creating a system.properties file and setting java.runtime.version=1.8 solved the issue. Dokku now uses Java version 8. Choosing a JDK on Heroku

I Never had to do it before...

How to stop flask application without using ctrl-c

If you're working on the CLI and only have one flask app/process running (or rather, you just want want to kill any flask process running on your system), you can kill it with:

kill $(pgrep -f flask)

What is the difference between substr and substring?

substring(startIndex, endIndex(not included))

substr(startIndex, how many characters)

const string = 'JavaScript';

console.log('substring(1,2)', string.substring(1,2)); // a
console.log('substr(1,2)', string.substr(1,2)); // av

Using GregorianCalendar with SimpleDateFormat

tl;dr

LocalDate.parse(
    "23-Mar-2017" ,
    DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) 
)

Avoid legacy date-time classes

The Question and other Answers are now outdated, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

You seem to be dealing with date-only values. So do not use a date-time class. Instead use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Parse a string.

String input = "23-Mar-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f );

Generate a string.

String output = ld.format( f );

If you were given numbers rather than text for the year, month, and day-of-month, use LocalDate.of.

LocalDate ld = LocalDate.of( 2017 , 3 , 23 );  // ( year , month 1-12 , day-of-month )

See this code run live at IdeOne.com.

input: 23-Mar-2017

ld.toString(): 2017-03-23

output: 23-Mar-2017


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to handle floats and decimal separators with html5 input type number

When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

How to fix the "508 Resource Limit is reached" error in WordPress?

Actually it happens when the number of processes exceeds the limits set by the hosting provider.

To avoid either we need to enhance the capacity by hosting providers or we need to check in the code whether any process takes longer time (like background tasks).

Subversion stuck due to "previous operation has not finished"?

That has happened for me when using externals and one of them was corrupt. I had to go to that folder and perform a cleanup. Then the cleanup worked for the entire working copy.

Example: Using external ^/widgets/foo common/foo-widget, first perform cleanup on folder common/foo-widget.

Trigger change() event when setting <select>'s value with val() function

I separate it, and then use an identity comparison to dictate what is does next.

$("#selectField").change(function(){
  if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
  if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});

Chrome / Safari not filling 100% height of flex parent

Solution

Use nested flex containers.

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle demo


Explanation

My problem is that .item-inner { height: 100% } is not working in webkit (Chrome).

It's not working because you're using percentage height in a way that doesn't conform with the traditional implementation of the spec.

10.5 Content height: the height property

percentage
Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly and this element is not absolutely positioned, the value computes to auto.

auto
The height depends on the values of other properties.

In other words, for percentage height to work on an in-flow child, the parent must have a set height.

In your code, the top-level container has a defined height: .container { height: 20em; }

The third-level container has a defined height: .item-inner { height: 100%; }

But between them, the second-level container – .itemdoes not have a defined height. Webkit sees that as a missing link.

.item-inner is telling Chrome: give me height: 100%. Chrome looks to the parent (.item) for reference and responds: 100% of what? I don't see anything (ignoring the flex: 1 rule that is there). As a result, it applies height: auto (content height), in accordance with the spec.

Firefox, on the other hand, now accepts a parent's flex height as a reference for the child's percentage height. IE11 and Edge accept flex heights, as well.

Also, Chrome will accept flex-grow as an adequate parent reference if used in conjunction with flex-basis (any numerical value works (auto won't), including flex-basis: 0). As of this writing, however, this solution fails in Safari.

_x000D_
_x000D_
#outer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#middle {_x000D_
  flex-grow: 1;_x000D_
  flex-basis: 1px;_x000D_
  background-color: yellow;_x000D_
}_x000D_
#inner {_x000D_
  height: 100%;_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="middle">_x000D_
    <div id="inner">_x000D_
      INNER_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Four Solutions

1. Specify a height on all parent elements

A reliable cross-browser solution is to specify a height on all parent elements. This prevents missing links, which Webkit-based browsers consider a violation of the spec.

Note that min-height and max-height are not acceptable. It must be the height property.

More details here: Working with the CSS height property and percentage values

2. CSS Relative & Absolute Positioning

Apply position: relative to the parent and position: absolute to the child.

Size the child with height: 100% and width: 100%, or use the offset properties: top: 0, right: 0, bottom: 0, left: 0.

With absolute positioning, percentage height works without a specified height on the parent.

3. Remove unnecessary HTML containers (recommended)

Is there a need for two containers around button? Why not remove .item or .item-inner, or both? Although button elements sometimes fail as flex containers, they can be flex items. Consider making button a child of .container or .item, and removing gratuitous mark-up.

Here's an example:

_x000D_
_x000D_
.container {_x000D_
    height: 20em;_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
a {_x000D_
    flex: 1;_x000D_
    background: orange;_x000D_
    border-bottom: 1px solid white;_x000D_
    display: flex;                   /* nested flex container (for aligning text) */_x000D_
    align-items: center;             /* center text vertically */_x000D_
    justify-content: center;         /* center text horizontally */_x000D_
}
_x000D_
<div class="container">_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

4. Nested Flex Containers (recommended)

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

Adding placeholder attribute using Jquery

This line of code might not work in IE 8 because of native support problems.

$(".hidden").attr("placeholder", "Type here to search");

You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.

$('input, textarea').placeholder();

Stretch and scale a CSS image in the background - with CSS only

Thanks!

But then it was not working for the Google Chrome and Safari browsers (stretching worked, but the hight of the pictures was only 2 mm!), until someone told me what lacks:

Try to set height:auto;min-height:100%;

So change that for your height:100%; line, gives:

#### #background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    width:100%;
    height:auto;
    min-height:100%;
}

Just before that newly added code I have this in my Drupal Tendu themes style.css:

html, body{height:100%;}

#page{background:#ffffff; height:auto !important;height:100%;min-height:100%;position:relative;}

Then I have to make a new block within Drupal with the picture while adding class=stretch:

< img alt="" class="stretch" src="pic.url" />

Just copying a picture with the editor in that Drupal block doesn't work; one has to change the editor to non-formatted text.

How to call on a function found on another file?

You can use header files.

Good practice.

You can create a file called player.h declare all functions that are need by other cpp files in that header file and include it when needed.

player.h

#ifndef PLAYER_H    // To make sure you don't declare the function more than once by including the header multiple times.
#define PLAYER_H

#include "stdafx.h"
#include <SFML/Graphics.hpp>

int playerSprite();

#endif

player.cpp

#include "player.h"  // player.h must be in the current directory. or use relative or absolute path to it. e.g #include "include/player.h"

int playerSprite(){
    sf::Texture Texture;
    if(!Texture.loadFromFile("player.png")){
        return 1;
    }
    sf::Sprite Sprite;
    Sprite.setTexture(Texture);
    return 0;
}

main.cpp

#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.h"            //Here. Again player.h must be in the current directory. or use relative or absolute path to it.

int main()
{
    // ...
    int p = playerSprite();  
    //...

Not such a good practice but works for small projects. declare your function in main.cpp

#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"


int playerSprite();  // Here

int main()
{
    // ...   
    int p = playerSprite();  
    //...

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

JQuery Parsing JSON array

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});

How to get UTC timestamp in Ruby?

Time.utc(2010, 05, 17)

Polling the keyboard (detect a keypress) in python

If you combine time.sleep, threading.Thread, and sys.stdin.read you can easily wait for a specified amount of time for input and then continue, also this should be cross-platform compatible.

t = threading.Thread(target=sys.stdin.read(1) args=(1,))
t.start()
time.sleep(5)
t.join()

You could also place this into a function like so

def timed_getch(self, bytes=1, timeout=1):
    t = threading.Thread(target=sys.stdin.read, args=(bytes,))
    t.start()
    time.sleep(timeout)
    t.join()
    del t

Although this will not return anything so instead you should use the multiprocessing pool module you can find that here: how to get the return value from a thread in python?

loading json data from local file into React JS

You could add your JSON file as an external using webpack config. Then you can load up that json in any of your react modules.

Take a look at this answer

Where does git config --global get written to?

I had installed my Git in: C:\Users\_myuserfolder_\AppData\Local\Programs\Git

Split function equivalent in T-SQL?

This is another version which really does not have any restrictions (e.g.: special chars when using xml approach, number of records in CTE approach) and it runs much faster based on a test on 10M+ records with source string average length of 4000. Hope this could help.

Create function [dbo].[udf_split] (
    @ListString nvarchar(max),
    @Delimiter  nvarchar(1000),
    @IncludeEmpty bit) 
Returns @ListTable TABLE (ID int, ListValue nvarchar(1000))
AS
BEGIN
    Declare @CurrentPosition int, @NextPosition int, @Item nvarchar(max), @ID int, @L int
    Select @ID = 1,
   @L = len(replace(@Delimiter,' ','^')),
            @ListString = @ListString + @Delimiter,
            @CurrentPosition = 1 
    Select @NextPosition = Charindex(@Delimiter, @ListString, @CurrentPosition)
   While @NextPosition > 0 Begin
   Set  @Item = LTRIM(RTRIM(SUBSTRING(@ListString, @CurrentPosition, @NextPosition-@CurrentPosition)))
   If      @IncludeEmpty=1 or LEN(@Item)>0 Begin 
     Insert Into @ListTable (ID, ListValue) Values (@ID, @Item)
     Set @ID = @ID+1
   End
   Set  @CurrentPosition = @NextPosition+@L
   Set  @NextPosition = Charindex(@Delimiter, @ListString, @CurrentPosition)
  End
    RETURN
END

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

I got the same error for python 32 bit. After install 64bit, the problem was fixed.

connecting to phpMyAdmin database with PHP/MySQL

This (mysql_connect, mysql_...) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
(ref: http://php.net/manual/en/function.mysql-connect.php)

  • Object Oriented:

    $mysqli = new mysqli("host", "user", "password");
    $mysqli->select_db("db");
    
  • Procedural:

    $link = mysqli_connect("host","user","password") or die(mysqli_error($link)); 
    mysqli_select_db($link, "db");
    

Programmatically trigger "select file" dialog box

Natively the only way is by creating an <input type="file"> element and then simulating a click, unfortunately.

There's a tiny plugin (shameless plug) which will take the pain away of having to do this all the time: file-dialog

fileDialog()
    .then(file => {
        const data = new FormData()
        data.append('file', file[0])
        data.append('imageName', 'flower')

        // Post to server
        fetch('/uploadImage', {
            method: 'POST',
            body: data
        })
    })

Finding first blank row, then writing to it

Very old thread but a simpler take :)

Sub firstBlank(c) 'as letter
    MsgBox (c & Split(Range(c & ":" & c).Find("", LookIn:=xlValues).address, "$")(2))
End Sub
Sub firstBlank(c) 'as number
    cLet = Split(Cells(1, c).address, "$")(1)
    MsgBox (cLet & Split(Range(cLet & ":" & cLet).Find("", LookIn:=xlValues).address, "$")(2))
End Sub

Why Does OAuth v2 Have Both Access and Refresh Tokens?

The idea of refresh tokens is that if an access token is compromised, because it is short-lived, the attacker has a limited window in which to abuse it.

Refresh tokens, if compromised, are useless because the attacker requires the client id and secret in addition to the refresh token in order to gain an access token.

Having said that, because every call to both the authorization server and the resource server is done over SSL - including the original client id and secret when they request the access/refresh tokens - I am unsure as to how the access token is any more "compromisable" than the long-lived refresh token and clientid/secret combination.

This of course is different to implementations where you don't control both the authorization and resource servers.

Here is a good thread talking about uses of refresh tokens: OAuth Archives.

A quote from the above, talking about the security purposes of the refresh token:

Refresh tokens... mitigates the risk of a long-lived access_token leaking (query param in a log file on an insecure resource server, beta or poorly coded resource server app, JS SDK client on a non https site that puts the access_token in a cookie, etc)

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

How to count the number of true elements in a NumPy bool array

That question solved a quite similar question for me and I thought I should share :

In raw python you can use sum() to count True values in a list :

>>> sum([True,True,True,False,False])
3

But this won't work :

>>> sum([[False, False, True], [True, False, True]])
TypeError...

What are the proper permissions for an upload folder with PHP/Apache?

Based on the answer from @Ryan Ahearn, following is what I did on Ubuntu 16.04 to create a user front that only has permission for nginx's web dir /var/www/html.

Steps:

* pre-steps:
    * basic prepare of server,
    * create user 'dev'
        which will be the owner of "/var/www/html",
    * 
    * install nginx,
    * 
* 
* create user 'front'
    sudo useradd -d /home/front -s /bin/bash front
    sudo passwd front

    # create home folder, if not exists yet,
    sudo mkdir /home/front
    # set owner of new home folder,
    sudo chown -R front:front /home/front

    # switch to user,
    su - front

    # copy .bashrc, if not exists yet,
    cp /etc/skel/.bashrc ~front/
    cp /etc/skel/.profile ~front/

    # enable color,
    vi ~front/.bashrc
    # uncomment the line start with "force_color_prompt",

    # exit user
    exit
* 
* add to group 'dev',
    sudo usermod -a -G dev front
* change owner of web dir,
    sudo chown -R dev:dev /var/www
* change permission of web dir,
    chmod 775 $(find /var/www/html -type d)
    chmod 664 $(find /var/www/html -type f)
* 
* re-login as 'front'
    to make group take effect,
* 
* test
* 
* ok
* 

How to handle AccessViolationException

In .NET 4.0, the runtime handles certain exceptions raised as Windows Structured Error Handling (SEH) errors as indicators of Corrupted State. These Corrupted State Exceptions (CSE) are not allowed to be caught by your standard managed code. I won't get into the why's or how's here. Read this article about CSE's in the .NET 4.0 Framework:

http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035

But there is hope. There are a few ways to get around this:

  1. Recompile as a .NET 3.5 assembly and run it in .NET 4.0.

  2. Add a line to your application's config file under the configuration/runtime element: <legacyCorruptedStateExceptionsPolicy enabled="true|false"/>

  3. Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions attribute. See http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035 for details.


EDIT

Previously, I referenced a forum post for additional details. But since Microsoft Connect has been retired, here are the additional details in case you're interested:

From Gaurav Khanna, a developer from the Microsoft CLR Team

This behaviour is by design due to a feature of CLR 4.0 called Corrupted State Exceptions. Simply put, managed code shouldnt make an attempt to catch exceptions that indicate corrupted process state and AV is one of them.

He then goes on to reference the documentation on the HandleProcessCorruptedStateExceptionsAttribute and the above article. Suffice to say, it's definitely worth a read if you're considering catching these types of exceptions.

Converting BigDecimal to Integer

I found that the above did not work for me. I was pulling a cell value from a JTable but could not cast to double or int etc. My solution:

Object obj = getTable().getValueAt(row, 0);

where row 0 would always be a number. Hope this helps anyone still scrolling!

Open multiple Projects/Folders in Visual Studio Code

If you are using unix like OS, you can create a soft link to your target folder.

E.g. I want to see golang source while I am using VSCode. So, I create a soft link to go/src under my project folder.

ln -s /usr/local/go/src gosrc

Hope this helps!


Update: 11/28, 2017

Multi Root Workspaces[0] landed in the stable build, finally. https://code.visualstudio.com/updates/v1_18#_support-for-multi-root-workspaces

[0] https://github.com/Microsoft/vscode/issues/396

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

As per late 2020 this as easy as follows.

For the geometry key to be presented on a place selected from the places dropdown, the field geometry should be set on Autocomplete object instance with setFields() method.

The code should look like this.

Load the API library:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete"

Init the autocomplete and process the selected place data generally same as all answers above. But use autocomplete.setFields(['geometry']) to get coordinates back;

const autocomplete;

// Init the autocomplete object
function initAutocomplete() {
    autocomplete = new window.google.maps.places.Autocomplete(
        document.getElementById('current_location'), { types: ["geocode"] }
    );

    // !!! This is where you set `geometry` field to be returned with the place.
    autocomplete.setFields(['address_component', 'geometry']); // <--

    autocomplete.addListener("place_changed", fillInAddress);
}

// Process the address selected by user
function fillInAddress() {
    const place = autocomplete.getPlace();

    // Here you can get your coordinates like this
    console.log(place.geometry.location.lat());
    console.log(place.geometry.location.lng());
}

See the Google API docs on Autocomplete.setFields and geometry option.

Get PHP class property by string

Like this

<?php

$prop = 'Name';

echo $obj->$prop;

Or, if you have control over the class, implement the ArrayAccess interface and just do this

echo $obj['Name'];

How to use KeyListener

In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

@Override
public void setFocusable(boolean b) {
    super.setFocusable(b);
}

And by adding this to your constructor:

setFocusable(true);

Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();
childComponent.setFocusable(true);

And then doing all the KeyListener stuff mentioned by others.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

Try:

Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools from an elevated PowerShell (run as Administrator).

https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#environment-setup-and-configuration

Is it possible to style a select box?

this on uses the twitter-bootstrap styles to turn selectin dropdown menu https://github.com/silviomoreto/bootstrap-select

CREATE TABLE LIKE A1 as A2

Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

What about:

Create Table New_Users Select * from Old_Users Where 1=2;

and if that doesn't work, just select a row and truncate after creation:

Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;

EDIT:

I noticed your comment below about needing indexes, etc. Try:

show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;

That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:

#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);