Programs & Examples On #Pkcs#8

How to read .pem file to get private and public key

Java libs makes it almost a one liner to read the public cert, as generated by openssl:

val certificate: X509Certificate = ByteArrayInputStream(
        publicKeyCert.toByteArray(Charsets.US_ASCII))
        .use {
            CertificateFactory.getInstance("X.509")
                    .generateCertificate(it) as X509Certificate
        }

But, o hell, reading the private key was problematic:

  1. First had to remove the begin and end tags, which is not nessarry when reading the public key.
  2. Then I had to remove all the new lines, otherwise it croaks!
  3. Then I had to decode back to bytes using byte 64
  4. Then I was able to produce an RSAPrivateKey.

see this: Final solution in kotlin

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }

Generate Json schema from XML schema (XSD)

Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.

Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.

Let's take the Purchase Order schema for example. Here's a fragment:

  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>

You can compile this schema using the provided command-line tool:

java -jar jsonix-schema-compiler-full.jar
    -generateJsonSchema
    -p PO
    schemas/purchaseorder.xsd

The compiler generates Jsonix mappings as well the matching JSON Schema.

Here's what the result looks like (edited for brevity):

{
    "id":"PurchaseOrder.jsonschema#",
    "definitions":{
        "PurchaseOrderType":{
            "type":"object",
            "title":"PurchaseOrderType",
            "properties":{
                "shipTo":{
                    "title":"shipTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                },
                "billTo":{
                    "title":"billTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                }, ...
            }
        },
        "USAddress":{ ... }, ...
    },
    "anyOf":[
        {
            "type":"object",
            "properties":{
                "name":{
                    "$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
                },
                "value":{
                    "$ref":"#/definitions/PurchaseOrderType"
                }
            },
            "elementName":{
                "localPart":"purchaseOrder",
                "namespaceURI":""
            }
        }
    ]
}

Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.

The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).

Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.

Links:

Check if url contains string with JQuery

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf("?added-to-cart=555") > -1) {
    alert("found it");
}

Which language uses .pde extension?

Bad news I'm afraid (or maybe great news?) : it isn't C code, it's an example of "Processing" - an open source language aimed at programming images. Take a look here

Looks very cool.

How can I make visible an invisible control with jquery? (hide and show not work)

It's been more than 10 years and not sure if anyone still finding this question or answer relevant.

But a quick workaround is just to wrap the asp control within a html container

<div id="myElement" style="display: inline-block">
   <asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>

Whenever the Javascript Event is triggered, if it needs to be an event by the asp control, just wrap the asp control around the div container.

<div id="testG">  
   <asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>

The jQuery Code is below:

$(document).ready(function () {
    $("#testG").click(function () {
                $("#myElement").css("display", "none");
     });
});

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

Trigger a button click with JavaScript on the Enter key in a text box

Figured this out:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
        return false;
    }
    return true;
}
</script>

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

How to list all installed packages and their versions in Python?

yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )

with pip installed packages, you can do a

pip freeze

and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do

mkvirtualenv my_new_project

and then (inside that virtualenv), do

pip install all_your_stuff

This way, you can workon my_new_project and then pip freeze to see which packages are installed for that virtualenv/project.

for example:

?  ~  mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details

(yo_dude)?  ~  pip install django
Downloading/unpacking django
  Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
  Running setup.py egg_info for package django

Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...

(yo_dude)?  ~  pip freeze
Django==1.4.1
wsgiref==0.1.2

(yo_dude)?  ~  

or if you have a python package with a requirements.pip file,

mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze

will do the trick

Press TAB and then ENTER key in Selenium WebDriver

In python this work for me

self.set_your_value = "your value"

def your_method_name(self):      
    self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`

jQuery: keyPress Backspace won't fire?

According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (https://api.jquery.com/keypress/)

In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.

jQuery(el).keydown( function() { 
    var that = this; setTimeout( function(){ 
           /** Code that processes backspace, etc. **/ 
     }, 100 );  
 } );

File name without extension name VBA

The answers given here already may work in limited situations, but are certainly not the best way to go about it. Don't reinvent the wheel. The File System Object in the Microsoft Scripting Runtime library already has a method to do exactly this. It's called GetBaseName. It handles periods in the file name as is.

Public Sub Test()

    Dim fso As New Scripting.FileSystemObject
    Debug.Print fso.GetBaseName(ActiveWorkbook.Name)

End Sub

Public Sub Test2()

    Dim fso As New Scripting.FileSystemObject
    Debug.Print fso.GetBaseName("MyFile.something.txt")

End Sub

Instructions for adding a reference to the Scripting Library

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

On WebStorm 2016.3

  1. Press ALT+F12 (open terminal)

  2. Run this command:

    npm install require.js
    

HTML5 Video Stop onClose

For a JQM+PhoneGap app the following worked for me.

The following was the minimum I had to go to get this to work. I was actually experiencing a stall due to the buffering while spawning ajax requests when the user pressed the back button. Pausing the video in Chrome and the Android browser kept it buffering. The non-async ajax request would get stuck waiting for the buffering to finish, which it never would.

Binding this to the beforepagehide event fixed it.

 $("#SOME_JQM_PAGE").live("pagebeforehide", function(event)
 {
           $("video").each(function () 
           { 
               logger.debug("PAUSE VIDEO");
               this.pause();
               this.src = "";
           });
 });

This will clear every video tag on the page.

The important part is this.src = "";

Associating existing Eclipse project with existing SVN repository

I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)

subclipse not showing "share project" option on project context menu in eclipse

How to exit if a command failed?

Provided my_command is canonically designed, ie returns 0 when succeeds, then && is exactly the opposite of what you want. You want ||.

Also note that ( does not seem right to me in bash, but I cannot try from where I am. Tell me.

my_command || {
    echo 'my_command failed' ;
    exit 1; 
}

How to submit a form with JavaScript by clicking a link?

HTML & CSS - No Javascript Solution

Make your button appear like a Bootstrap link

HTML:

<form>
    <button class="btn-link">Submit</button>
</form>

CSS:

.btn-link {

    background: none;
    border: none;
    padding: 0px;
    color: #3097D1;
    font: inherit;

}

.btn-link:hover {

    color: #216a94;
    text-decoration: underline;

}

What does IFormatProvider do?

In adition to Ian Boyd's answer:

Also CultureInfo implements this interface and can be used in your case. So you could parse a French date string for example; you could use

var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);

Pushing an existing Git repository to SVN

Git -> SVN with complete commit history

I had a Git project and had to move it to SVN. This is how I made it, keeping the whole commit history. The only thing that gets lost is the original commit time since libSVN will set the local time when we do git svn dcommit.

Howto:

  1. Have a SVN repository where we want to import our stuff to and clone it with git-svn:

    git svn clone https://path.to/svn/repository repo.git-svn`
    
  2. Go there:

    cd repo.git-svn
    
  3. Add the remote of the Git repository (in this example I'm using C:/Projects/repo.git). You want to push to SVN and give it the name old-git:

    git remote add old-git file:///C/Projects/repo.git/
    
  4. Fetch the information from the master branch from the old-git repository to the current repository:

    git fetch old-git master
    
  5. Checkout the master branch of the old-git remote into a new branch called old in the current repository:

    git checkout -b old old-git/master`
    
  6. Rebase to put the HEAD on top of old-git/master. This will maintain all your commits. What this does basically is to take all of your work done in Git and put it on top of the work you are accessing from SVN.

    git rebase master
    
  7. Now go back to your master branch:

    git checkout master
    

    And you can see that you have a clean commit history. This is what you want to push to SVN.

  8. Push your work to SVN:

    git svn dcommit
    

That's all. It is very clean, no hacking, and everything works perfectly out of the box. Enjoy.

How to autowire RestTemplate using annotations

Add the @Configuration annotation in the RestTemplateSOMENAME which extends the RestTemplate class.

@Configuration         
public class RestTemplateClass extends RestTemplate {

}

Then in your controller class you can use the Autowired annotation as follows.

@Autowired   
RestTemplateClass restTemplate;

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

use Lodash to sort array of object by value

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

Your code could be like:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

i fixed this by running sudo apachectl stop - turns out apache was running in the background and prevented nginx from starting on the desired port.

On ubuntu run sudo /etc/init.d/apache2 stop

How do I make a placeholder for a 'select' box?

Something like this:

HTML:

<select id="choice">
    <option value="0" selected="selected">Choose...</option>
    <option value="1">Something</option>
    <option value="2">Something else</option>
    <option value="3">Another choice</option>
</select>

CSS:

#choice option { color: black; }
.empty { color: gray; }

JavaScript:

$("#choice").change(function () {
    if($(this).val() == "0") $(this).addClass("empty");
    else $(this).removeClass("empty")
});

$("#choice").change();

Working example: http://jsfiddle.net/Zmf6t/

Difference Between ViewResult() and ActionResult()

It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Commenting filters solved the issue.

How to make a class property?

As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.

I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title property with a setter. Here's what I wrote:

class TitleMeta(type):
    @property
    def title(self):
        return getattr(self, '_title', 'Default Title')

    @title.setter
    def title(self, title):
        self._title = title
        # Do whatever else you want when the title is set...

Now make the actual class you want as normal, except have it use the metaclass you created above.

# Python 2 style:
class ClassWithTitle(object):
    __metaclass__ = TitleMeta
    # The rest of your class definition...

# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
    # Your class definition...

It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.

What is the difference between a pandas Series and a single-column DataFrame?

from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:

import pandas as pd
ds = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.

import pandas as pd
df = pd.DataFrame(data, index=index)

In both of the above index is list

for example: I have a csv file with following data:

,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi

To read above data as series and data frame:

import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index =  file_data.index)

output:

>>> d
BR           Brazil
RU           Russia
IN            India

df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )

output:

>>> df
      area
BR   12015
RU     457
IN  457787

invalid byte sequence for encoding "UTF8"

It is also very possible with this error that the field is encrypted in place. Be sure you are looking at the right table, in some cases administrators will create an unencrypted view that you can use instead. I recently encountered a very similar issue.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Add these 2 lines

layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

So you have:

   // Do any additional setup after loading the view, typically from a nib.
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout

That will remove all the spaces and give you a grid layout:

enter image description here

If you want the first column to have a width equal to the screen width then add the following function:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if indexPath.row == 0
    {
        return CGSize(width: screenWidth, height: screenWidth/3)
    }
    return CGSize(width: screenWidth/3, height: screenWidth/3);

}

Grid layout will now look like (I've also added a blue background to first cell): enter image description here

Why do we have to specify FromBody and FromUri?

The default behavior is:

  1. If the parameter is a primitive type (int, bool, double, ...), Web API tries to get the value from the URI of the HTTP request.

  2. For complex types (your own object, for example: Person), Web API tries to read the value from the body of the HTTP request.

So, if you have:

  • a primitive type in the URI, or
  • a complex type in the body

...then you don't have to add any attributes (neither [FromBody] nor [FromUri]).

But, if you have a primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)

Or, if you have a complex type in your URI, then you must add [FromUri]. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)

Primitive types:

public class UsersController : ApiController
{
    // api/users
    public HttpResponseMessage Post([FromBody]int id)
    {

    }
    // api/users/id
    public HttpResponseMessage Post(int id)
    {

    }       
}

Complex types:

public class UsersController : ApiController
{       
    // api/users
    public HttpResponseMessage Post(User user)
    {

    }

    // api/users/user
    public HttpResponseMessage Post([FromUri]User user)
    {

    }       
}

This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:

public class MyModel
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
    // model.MyProperty;
    // model.MyProperty2;
}

From Microsoft's documentation for parameter binding in ASP.NET Web API:

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

This should work:

public HttpResponseMessage Post([FromBody] string name) { ... }

This will not work:

// Caution: This won't work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Count distinct values

You can do a distinct count as follows:

SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:

Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

  • 2 customers had 1 pets
  • 3 customers had 2 pets
  • 1 customers had 3 pets

Now you're probably going to want to use a subquery:

select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

How to compare two List<String> to each other?

You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:

IEnumerable<string> inFirstOnly = a1.Except(a2);
IEnumerable<string> inSecondOnly = a2.Except(a1);
bool allInBoth = !inFirstOnly.Any() && !inSecondOnly.Any();

So this is an efficient way if the order and if the number of duplicates does not matter(as opposed to the accepted answer's SequenceEqual). Demo: Ideone

If you want to compare in a case insentive way, just add StringComparer.OrdinalIgnoreCase:

a1.Except(a2, StringComparer.OrdinalIgnoreCase)

Disable pasting text into HTML form

You can use jquery

HTML file

<input id="email" name="email">

jquery code

$('#email').bind('copy paste', function (e) {
        e.preventDefault();
    });

Is it possible to have placeholders in strings.xml for runtime values?

You can use MessageFormat:

<string name="customer_address">Wellcome: {0} {1}</string>

In Java code :

String text = MessageFormat(R.string.customer_address).format("Name","Family");

API level 1:

https://developer.android.com/reference/java/text/MessageFormat.html

XML Document to String

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

WiX tricks and tips

Put Components which may be patched individually inside their own Fragments

It goes for both making product installers and patches that if you include any component in a fragment, you must include all of the components in that fragment. In the case of building an installer, if you miss any component references, you'll get a linking error from light.exe. However, when you make a patch, if you include a single component reference in a fragment, then all changed components from that fragment will show up in your patch.

like this:

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent1" Guid="{C28843DA-EF08-41CC-BA75-D2B99D8A1983}" DiskId="1">
            <File Id="SampleFile1" Source=".\$(var.Version)f\Sample1.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent2" Guid="{6CEA5599-E7B0-4D65-93AA-0F2F64402B22}" DiskId="1">
           <File Id="SampleFile2" Source=".\$(var.Version)f\Sample2.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent3" Guid="{4030BAC9-FAB3-426B-8D1E-DC1E2F72C2FC}" DiskId="1">
           <File Id="SampleFile3" Source=".\$(var.Version)f\Sample3.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

instead of this:

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent1" Guid="{C28843DA-EF08-41CC-BA75-D2B99D8A1983}" DiskId="1">
            <File Id="SampleFile1" Source=".\$(var.Version)\Sample1.txt" />
        </Component>

        <Component Id="SampleComponent2" Guid="{6CEA5599-E7B0-4D65-93AA-0F2F64402B22}" DiskId="1">
           <File Id="SampleFile2" Source=".\$(var.Version)\Sample2.txt" />
        </Component>

        <Component Id="SampleComponent3" Guid="{4030BAC9-FAB3-426B-8D1E-DC1E2F72C2FC}" DiskId="1">
           <File Id="SampleFile3" Source=".\$(var.Version)\Sample3.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

Also, when patching using the "Using Purely WiX" topic from the WiX.chm help file, using this procedure to generate the patch:

torch.exe -p -xi 1.0\product.wixpdb 1.1\product.wixpdb -out patch\diff.wixmst
candle.exe patch.wxs
light.exe patch.wixobj -out patch\patch.wixmsp
pyro.exe patch\patch.wixmsp -out patch\patch.msp -t RTM patch\diff.wixmst

it's not enough to just have the 1.1 version of the product.wixpdb built using the components in separate fragments. So be sure to correctly fragment your product before shipping.

What is a smart pointer and when should I use one?

Most kinds of smart pointers handle disposing of the pointer-to object for you. It's very handy because you don't have to think about disposing of objects manually anymore.

The most commonly-used smart pointers are std::tr1::shared_ptr (or boost::shared_ptr), and, less commonly, std::auto_ptr. I recommend regular use of shared_ptr.

shared_ptr is very versatile and deals with a large variety of disposal scenarios, including cases where objects need to be "passed across DLL boundaries" (the common nightmare case if different libcs are used between your code and the DLLs).

JavaScript + Unicode regexes

September 2018 (updated February 2019)

It seems that regexp /\p{L}/u for match letters (as unicode categories)

  • works on Chrome 68.0.3440.106 and Safari 11.1.2 (13605.3.8)
  • NOT working on Firefox 65.0 :(

Here is a working example

_x000D_
_x000D_
In below field you should be able to to type letters but not numbers<br>_x000D_
<input type="text" name="field" onkeydown="return /\p{L}/u.test(event.key)" >
_x000D_
_x000D_
_x000D_

I report this bug here.

Update

After over 2 years according to: 1500035 > 1361876 > 1634135 finally this bug is fixed and will be available in Firefox v.78+

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

You could also use it clean and simple (but wrong! because you should use format like Mark Byers said) by doing:

print 'This is my %s formatted with %d arguments' % ('string', 2)

TypeScript sorting an array

let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

let sortFn = (n1 , n2) => number { return n1 - n2; }

const sortedArray: number[] = numericArray.sort(sortFn);

Sort by some field:

let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];

let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }

const sortedArray2:{key:number}[] = arr.sort(sortFn2);

Specify path to node_modules in package.json

yes you can, just set the NODE_PATH env variable :

export NODE_PATH='yourdir'/node_modules

According to the doc :

If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)

Additionally, node will search in the following locations:

1: $HOME/.node_modules

2: $HOME/.node_libraries

3: $PREFIX/lib/node

Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.

These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.

Source

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

In order to use a CLR 2.0 mixed mode assembly, you need to modify your App.Config file to include:

<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

The key is the useLegacyV2RuntimeActivationPolicy flag. This causes the CLR to use the latest version (4.0) to load your mixed mode assembly. Without this, it will not work.

Note that this only matters for mixed mode (C++/CLI) assemblies. You can load all managed CLR 2 assemblies without specifying this in app.config.

Calculating the area under a curve given a set of coordinates, without knowing the function

You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.

Python script that calculates Simpsons rule:

def integrate(y_vals, h):
    i = 1
    total = y_vals[0] + y_vals[-1]
    for y in y_vals[1:-1]:
        if i % 2 == 0:
            total += 2 * y
        else:
            total += 4 * y
        i += 1
    return total * (h / 3.0)

h is the offset (or gap) between y values, and y_vals is an array of well, y values.

Example (In same file as above function):

y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)

The term "Add-Migration" is not recognized

I ran into the same issue. Most of my projects had the same thing in tools.

"tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
}

This worked fine on all but one project. I changed the entry in tools to

"tools": {
    "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview2-final",
    "type": "build"
  }
}

And then ran dotnet restore. After the restore completed, Add-Migration worked normally.

Max value of Xmx and Xms in Eclipse?

Why do you need -Xms768 (small heap must be at least 768...)?

That means any java process (search in eclipse) will start with 768m memory allocated, doesn't that? That is why your eclipse isn't able to start properly.

Try -Xms16 -Xmx2048m, for instance.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I have installed Oracle 11g XE on Windows 10 OS. It's installed successfully on my PC but it's showing error which is :
Error:
"windows cannot find 'http //127.0.0.1:%httpport%/apex/f?p4950"

Just follow some steps

In SQL command prompt just type

sql> net start OracleServiceXe after start the Oracle server.

Type SQL> Connect SYS / System as SYSDBA / SYSOPERA

Then type your password which is given by you at the time of installation of Oracle 11g XE. (Press enter).

but You can get login on oracle through this

Note: ( My suggestion to you just type port after http://127.0.0.1:[PortNumber]/apex/f?p=4950 )

http://127.0.0.1:8080/apex/f?p=4950

I got loged in successfully.

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

Solution is very simple.

1 Add Internet permission in Androidmanifest.xml file

<uses-permission android:name="android.permission.INTERNET" />

[2] Change your httpd.config file

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

TO

Order Deny,Allow
Allow from all
Allow from 127.0.0.1

And restart your server.

[3] And most impotent step. MAKE YOUR NETWORK AS YOUR HOME NETWORK

Go to Control Panel > Network and Internet > Network and Sharing Center

Click on your Network and select HOME NETWORK

enter image description here

difference between iframe, embed and object elements

iframe have "sandbox" attribute that may block pop up etc

How to echo shell commands as they are executed

For csh and tcsh, you can set verbose or set echo (or you can even set both, but it may result in some duplication most of the time).

The verbose option prints pretty much the exact shell expression that you type.

The echo option is more indicative of what will be executed through spawning.


http://www.tcsh.org/tcsh.html/Special_shell_variables.html#verbose

http://www.tcsh.org/tcsh.html/Special_shell_variables.html#echo


Special shell variables

verbose If set, causes the words of each command to be printed, after history substitution (if any). Set by the -v command line option.

echo If set, each command with its arguments is echoed just before it is executed. For non-builtin commands all expansions occur before echoing. Builtin commands are echoed before command and filename substitution, because these substitutions are then done selectively. Set by the -x command line option.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

C#: How do you edit items and subitems in a listview?

If you're looking for "in-place" editing of a ListView's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.

By default, the best you can achieve with a "standard" ListView is to set it's LabelEdit property to true to allow the user to edit the text of the first column of the ListView (assuming you want to allow a free-format text edit).

Some examples (including full source-code) of customized ListView's that allow "in-place" editing of sub-items are:

C# Editable ListView
In-place editing of ListView subitems

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

In my case, I was linking to a third-party library that was a bit old (developed for iOS 6, on XCode 5 / iOS 7). Therefore, I had to update the third-party library, do a Clean and Build, and it now builds successfully.

Get user info via Google API

If you're in a client-side web environment, the new auth2 javascript API contains a much-needed getBasicProfile() function, which returns the user's name, email, and image URL.

https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile

Difference between string and char[] types in C++

I personally do not see any reason why one would like to use char* or char[] except for compatibility with old code. std::string's no slower than using a c-string, except that it will handle re-allocation for you. You can set it's size when you create it, and thus avoid re-allocation if you want. It's indexing operator ([]) provides constant time access (and is in every sense of the word the exact same thing as using a c-string indexer). Using the at method gives you bounds checked safety as well, something you don't get with c-strings, unless you write it. Your compiler will most often optimize out the indexer use in release mode. It is easy to mess around with c-strings; things such as delete vs delete[], exception safety, even how to reallocate a c-string.

And when you have to deal with advanced concepts like having COW strings, and non-COW for MT etc, you will need std::string.

If you are worried about copies, as long as you use references, and const references wherever you can, you will not have any overhead due to copies, and it's the same thing as you would be doing with the c-string.

How to change the Text color of Menu item in Android?

Adding this into my styles.xml worked for me

<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

wait also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in background. Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID.

# run processes and store pids in array
for i in $n_procs; do
    ./procs[${i}] &
    pids[${i}]=$!
done

# wait for all pids
for pid in ${pids[*]}; do
    wait $pid
done

Get Country of IP Address with PHP

Here is another free API for geolocation requests: http://geoip.nekudo.com

Responses are in JSON format. Additionally the API sourcecode is available on github in case you need to setup your own API.

How do I pass a command line argument while starting up GDB in Linux?

Once gdb starts, you can run the program using "r args".

So if you are running your code by:

$ executablefile arg1 arg2 arg3 

Debug it on gdb by:

$ gdb executablefile  
(gdb) r arg1 arg2 arg3

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Print array to a file

You could try:

$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

How to find a value in an excel column by vba code Cells.Find

Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range

Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)

Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
  strFirstAddress = rngFindValue.Address
  Do
    Set rngFindValue = search.FindNext(rngFindValue)
  Loop Until rngFindValue.Address = strFirstAddress

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Android scale animation on view

Resize using helper methods and start-repeat-end handlers like this:

resize(
    view1,
    1.0f,
    0.0f,
    1.0f,
    0.0f,
    0.0f,
    0.0f,
    150,
    null,
    null,
    null);

  return null;
}

Helper methods:

/**
 * Resize a view.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration) {

  resize(
    view,
    fromX,
    toX,
    fromY,
    toY,
    pivotX,
    pivotY,
    duration,
    null,
    null,
    null);
}

/**
 * Resize a view with handlers.
 *
 * @param view     A view to resize.
 * @param fromX    X scale at start.
 * @param toX      X scale at end.
 * @param fromY    Y scale at start.
 * @param toY      Y scale at end.
 * @param pivotX   Rotate angle at start.
 * @param pivotY   Rotate angle at end.
 * @param duration Animation duration.
 * @param start    Actions on animation start. Otherwise NULL.
 * @param repeat   Actions on animation repeat. Otherwise NULL.
 * @param end      Actions on animation end. Otherwise NULL.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration,
  Callable start,
  Callable repeat,
  Callable end) {

  Animation animation;

  animation =
    new ScaleAnimation(
      fromX,
      toX,
      fromY,
      toY,
      Animation.RELATIVE_TO_SELF,
      pivotX,
      Animation.RELATIVE_TO_SELF,
      pivotY);

  animation.setDuration(
    duration);

  animation.setInterpolator(
    new AccelerateDecelerateInterpolator());

  animation.setFillAfter(true);

  view.startAnimation(
    animation);

  animation.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) {

      if (start != null) {
        try {

          start.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    }

    @Override
    public void onAnimationEnd(Animation animation) {

      if (end != null) {
        try {

          end.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    @Override
    public void onAnimationRepeat(
      Animation animation) {

      if (repeat != null) {
        try {

          repeat.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }  
    }
  });
}

Daylight saving time and time zone best practices

I recently had a problem in a web application where on an Ajax post-back the datetime coming back to my server-side code was different from the datetime served out.

It most likely had to do with my JavaScript code on the client that built up the date for posting back to the client as string, because JavaScript was adjusting for time zone and daylight savings, and in some browsers the calculation for when to apply daylight savings seemed to be different than in others.

In the end I opted to remove date and time calculations on the client entirely, and posted back to my server on an integer key which then got translated to date time on the server, to allow for consistent transformations.

My learning from this: Do not use JavaScript date and time calculations in web applications unless you ABSOLUTELY have to.

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

PHP not displaying errors even though display_errors = On

I had the same problem with Apache and PHP 5.5. In php.ini, I had the following lines:

error_reporting E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors Off

instead of the following:

error_reporting=E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors=Off

(the =sign was missing)

Why do abstract classes in Java have constructors?

Because abstract classes have state (fields) and somethimes they need to be initialized somehow.

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

jQuery - simple input validation - "empty" and "not empty"

You could do this

$("#input").blur(function(){
    if($(this).val() == ''){
        alert('empty'); 
    }
});

http://jsfiddle.net/jasongennaro/Y5P9k/1/

When the input has lost focus that is .blur(), then check the value of the #input.

If it is empty == '' then trigger the alert.

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

You need to fix your include_path system variable to point to the correct location.

To fix it edit the php.ini file. In that file you will find a line that says, "include_path = ...". (You can find out what the location of php.ini by running phpinfo() on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR" to read "C:\xampplite\php\pear". Make sure to leave the semi-colons before and/or after the line in place.

Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.

SQL Server: Get data for only the past year

Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1

Then if you want to restrict this query, you can add some other filter, but always searching in the last year.

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'

SelectSingleNode returning null for known good xml node path using XPath

Sorry, you forgot the namespace. You need:

XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDoc.NameTable);
ns.AddNamespace("hl7","urn:hl7-org:v3");
XmlNode idNode = myXmlDoc.SelectSingleNode("/My_RootNode/hl7:id", ns);

In fact, whether here or in web services, getting null back from an XPath operation or anything that depends on XPath usually indicates a problem with XML namespaces.

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

How to find and turn on USB debugging mode on Nexus 4

In case you enabled debugging mode on your phone and adb devices is not listing your device, it seems there is a problem with phone driver. You might not install the usb-driver of your phone or driver might be installed with problems (in windows check in system --> device manager).

In my case, I had the same problem with My HTC android usb device which installing drivers again, fixed my problems.

Creating SVG graphics using Javascript?

Have a look at this list on Wikipedia about which browsers support SVG. It also provides links to more details in the footnotes. Firefox for example supports basic SVG, but at the moment lacks most animation features.

A tutorial about how to create SVG objects using Javascript can be found here:

var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r",  20);
shape.setAttributeNS(null, "fill", "green"); 

java.io.IOException: Invalid Keystore format

I think the keystore file you want to use has a different or unsupported format in respect to your Java version. Could you post some more info of your task?

In general, to solve this issue you might need to recreate the whole keystore (using some other JDK version for example). In export-import the keys between the old and the new one - if you manage to open the old one somewhere else.

If it is simply an unsupported version, try the BouncyCastle crypto provider for example (although I'm not sure If it adds support to Java for more keystore types?).

Edit: I looked at the feature spec of BC.

How to set default value for HTML select?

you can define attribute selected="selected" in Ex a

How to add parameters to HttpURLConnection using POST using NameValuePair

If you don't need the ArrayList<NameValuePair> for parameters, this is a shorter solution that builds the query string using the Uri.Builder class:

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();

conn.connect();

In Java, remove empty elements from a list of Strings

   private List cleanInputs(String[] inputArray) {
        List<String> result = new ArrayList<String>(inputArray.length);
        for (String input : inputArray) {
            if (input != null) {
                String str = input.trim();
                if (!str.isEmpty()) {
                    result.add(str);
                }
            }
        }
        return result;
    }

Spring Boot @Value Properties

Make sure your application.properties file is under src/main/resources/application.properties. Is one way to go. Then add @PostConstruct as follows

Sample Application.properties

file.directory = somePlaceOverHere

Sample Java Class

@ComponentScan
public class PrintProperty {

  @Value("${file.directory}")
  private String fileDirectory;

  @PostConstruct
  public void print() {
    System.out.println(fileDirectory);
  }
}

Code above will print out "somePlaceOverhere"

VIM Disable Automatic Newline At End Of File

Try to add in .vimrc

set binary

How to initialize a list of strings (List<string>) with many string values

Just remove () at the end.

List<string> optionList = new List<string>
            { "AdditionalCardPersonAdressType", /* rest of elements */ };

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Send email by using codeigniter library via localhost

Please check my working code.

function sendMail()
{
    $config = Array(
  'protocol' => 'smtp',
  'smtp_host' => 'ssl://smtp.googlemail.com',
  'smtp_port' => 465,
  'smtp_user' => '[email protected]', // change it to yours
  'smtp_pass' => 'xxx', // change it to yours
  'mailtype' => 'html',
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);

        $message = '';
        $this->load->library('email', $config);
      $this->email->set_newline("\r\n");
      $this->email->from('[email protected]'); // change it to yours
      $this->email->to('[email protected]');// change it to yours
      $this->email->subject('Resume from JobsBuddy for your Job posting');
      $this->email->message($message);
      if($this->email->send())
     {
      echo 'Email sent.';
     }
     else
    {
     show_error($this->email->print_debugger());
    }

}

How to detect if CMD is running as Administrator/has elevated privileges?

Works for Win7 Enterprise and Win10 Enterprise

@if DEFINED SESSIONNAME (
    @echo.
    @echo You must right click to "Run as administrator"
    @echo Try again
    @echo.
    @pause
    @goto :EOF
)

how to change namespace of entire project?

You can use ReSharper for namespace refactoring. It will give 30 days free trial. It will change namespace as per folder structure.

Steps:

  1. Right click on the project/folder/files you want to refactor.

  2. If you have installed ReSharper then you will get an option Refactor->Adjust Namespaces.... So click on this.

enter image description here

It will automatically change the name spaces of all the selected files.

How to append a char to a std::string?

str.append(10u,'d'); //appends character d 10 times

Notice I have written 10u and not 10 for the number of times I'd like to append the character; replace 10 with whatever number.

Add custom header in HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
    {
        const string WEBSERVICE_URL = "<<Web service URL>>";
        try
        {
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");

                using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                    {
                        var jsonResponse = sr.ReadToEnd();
                        Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

Reshaping data.frame from wide to long format

Here is another example showing the use of gather from tidyr. You can select the columns to gather either by removing them individually (as I do here), or by including the years you want explicitly.

Note that, to handle the commas (and X's added if check.names = FALSE is not set), I am also using dplyr's mutate with parse_number from readr to convert the text values back to numbers. These are all part of the tidyverse and so can be loaded together with library(tidyverse)

wide %>%
  gather(Year, Value, -Code, -Country) %>%
  mutate(Year = parse_number(Year)
         , Value = parse_number(Value))

Returns:

   Code     Country Year Value
1   AFG Afghanistan 1950 20249
2   ALB     Albania 1950  8097
3   AFG Afghanistan 1951 21352
4   ALB     Albania 1951  8986
5   AFG Afghanistan 1952 22532
6   ALB     Albania 1952 10058
7   AFG Afghanistan 1953 23557
8   ALB     Albania 1953 11123
9   AFG Afghanistan 1954 24555
10  ALB     Albania 1954 12246

Android Layout Right Align

You can do all that by using just one RelativeLayout (which, btw, don't need android:orientation parameter). So, instead of having a LinearLayout, containing a bunch of stuff, you can do something like:

<RelativeLayout>
    <ImageButton
        android:layout_width="wrap_content"
        android:id="@+id/the_first_one"
        android:layout_alignParentLeft="true"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_toRightOf="@+id/the_first_one"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

As you noticed, there are some XML parameters missing. I was just showing the basic parameters you had to put. You can complete the rest.

What is the difference between ELF files and bin files?

A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....

ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

How can I open Windows Explorer to a certain directory from within a WPF app?

Process.Start("explorer.exe" , @"C:\Users");

I had to use this, the other way of just specifying the tgt dir would shut the explorer window when my application terminated.

Casting variables in Java

Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:

Object o = "str";
String str = (String)o;

The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.

There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:

String o = "str";
Integer str = (Integer)o; //Compilation fails here

Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException will be thrown at runtime:

Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here

This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.

Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer inherits from Number, so if you want to store an Integer as a Number then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double, Float, Byte, Long, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!

Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)

How to force C# .net app to run only one instance in Windows?

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}

How can I create database tables from XSD files?

Might take a look at the XSD tool in visual studio 2k8... I have created a relational dataset from an xsd and it might help your out somehow.

What is the difference between Left, Right, Outer and Inner Joins?

Inner join: Only show rows, when has it data from both of the tables.

Outer join: (left/right): Show the all result from the left / right table with the paired row(s), if it exists or not.

how to add key value pair in the JSON object already declared

Object assign copies one or more source objects to the target object. So we could use Object.assign here.

Syntax: Object.assign(target, ...sources)

_x000D_
_x000D_
var obj  = {};_x000D_
_x000D_
Object.assign(obj, {"1":"aa", "2":"bb"})_x000D_
_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Swift Open Link in Safari

IOS 11.2 Swift 3.1- 4

let webView = WKWebView()

override func viewDidLoad() {
    super.viewDidLoad()
    guard let url = URL(string: "https://www.google.com") else { return }
    webView.frame = view.bounds
    webView.navigationDelegate = self
    webView.load(URLRequest(url: url))
    webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
    view.addSubview(webView)
}

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .linkActivated  {
        if let url = navigationAction.request.url,
            let host = url.host, !host.hasPrefix("www.google.com"),
            UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
            print(url)
            print("Redirected to browser. No need to open it locally")
            decisionHandler(.cancel)
        } else {
            print("Open it locally")
            decisionHandler(.allow)
        }
    } else {
        print("not a user click")
        decisionHandler(.allow)
    }
}

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Locating child nodes of WebElements in selenium

For Finding All the ChildNodes you can use the below Snippet

List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));

        for (WebElement e  : childs)
        {
            System.out.println(e.getTagName());
        }

Note that this will give all the Child Nodes at same level -> Like if you have structure like this :

<Html> 
<body> 
 <div> ---suppose this is current WebElement 
   <a>
   <a>
      <img>
          <a>
      <img>
   <a>

It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));

Hope That Helps !!

How to send a POST request from node.js Express?

I use superagent, which is simliar to jQuery.

Here is the docs

And the demo like:

var sa = require('superagent');
sa.post('url')
  .send({key: value})
  .end(function(err, res) {
    //TODO
  });

postgresql return 0 if returned value is null

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).


There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);
CREATE TABLE

$ select avg(bar) from foo;
 avg 
-----

(1 row)

$ select coalesce(avg(bar), 0) from foo;
 coalesce 
----------
        0
(1 row)

$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
      coalesce      
--------------------
 6.0000000000000000
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
      coalesce      
--------------------
 4.0000000000000000
(1 row)

What's a quick way to comment/uncomment lines in Vim?

Yes, there are 33 (mostly repetitive) answers already to this question.

Here is another approach to how to comment lines out in Vim: motions. The basic idea is to comment or uncomment lines out using the same method as yanking a paragraph by typing yip or deleting 2 lines by typing dj.

This approach will let you do things like:

  • ccj to comment the next 2 lines out, and cuk to uncomment them;

  • cci{ to comment a block out, and cui{ to uncomment it;

  • ccip to comment a whole paragraph out, and cuip to uncomment it.

  • ccG to comment everything out down to the last line, and cugg to uncomment everything up to the first line.

All you need are 2 functions that operate over motions, and 2 mappings for each function. First, the mappings:

nnoremap <silent> cc  :set opfunc=CommentOut<cr>g@
vnoremap <silent> cc  :<c-u>call  CommentOut(visualmode(), 1)<cr>
nnoremap <silent> cu  :set opfunc=Uncomment<cr>g@
vnoremap <silent> cu  :<c-u>call  Uncomment(visualmode(), 1)<cr>

(See the manual about the g@ operator and the operatorfunc variable.)

And now the functions:

function! CommentOut(type, ...)
  if a:0
    silent exe "normal!  :'<,'>s/^/#/\<cr>`<"
  else
    silent exe "normal!  :'[,']s/^/#/\<cr>'["
  endif
endfunction

function! Uncomment(type, ...)
  if a:0
    silent exe "normal!  :'<,'>s/^\\(\\s*\\)#/\\1/\<cr>`<"
  else
    silent exe "normal!  :'[,']s/^\\(\\s*\\)#/\\1/\<cr>`["
  endif
endfunction

Modify the regular expressions above to suit your taste as to where the # should be:

Eclipse: How do you change the highlight color of the currently selected method/expression?

After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:

General -> Editors -> Text Editors -> Annotations

Look for Occurences from the Annotation types list.

Then, be sure that Text as highlighted is selected, then choose the desired color.


And, a picture is worth a thousand words...

Preferences dialog
(source: coobird.net)

Image showing occurences highlighted in orange.
(source: coobird.net)

Could not reliably determine the server's fully qualified domain name

Another option is to ensure that the full qualified host name (FQDN) is listed in /etc/hosts. This worked for me on Ubuntu v11.10 without having to change the default Apache configuration.

Find and replace words/lines in a file

public static void replaceFileString(String old, String new) throws IOException {
    String fileName = Settings.getValue("fileDirectory");
    FileInputStream fis = new FileInputStream(fileName);
    String content = IOUtils.toString(fis, Charset.defaultCharset());
    content = content.replaceAll(old, new);
    FileOutputStream fos = new FileOutputStream(fileName);
    IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
    fis.close();
    fos.close();
}

above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.

Difference between agile and iterative and incremental development

Agile is mostly used technique in project development.In agile technology peoples are switches from one technology to other ..Main purpose is to remove dependancy. Like Peoples shifted from production to development,and development to testing. Thats why dependancy will remove on a single team or person..

Pandas: Subtracting two date columns and the result being an integer

Create a vectorized method

def calc_xb_minus_xa(df):
    time_dict = {
        '<Minute>': 'm',
        '<Hour>': 'h',
        '<Day>': 'D',
        '<Week>': 'W',
        '<Month>': 'M',
        '<Year>': 'Y'
    }

    time_delta = df.at[df.index[0], 'end_time'] - df.at[df.index[0], 'open_time']
    offset_base_name = str(to_offset(time_delta).base)
    time_term = time_dict.get(offset_base_name)

    result = (df.end_time - df.open_time) / np.timedelta64(1, time_term)
    return result

Then in your df do:

df['x'] = calc_xb_minus_xa(df)

This will work for minutes, hours, days, weeks, month and Year. open_time and end_time need to change according your df

How can I trigger an onchange event manually?

There's a couple of ways you can do this. If the onchange listener is a function set via the element.onchange property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:

element.onchange();

If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
}
else
    element.fireEvent("onchange");

Is it possible to use Visual Studio on macOS?

While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.

How do I speed up the gwt compiler?

  • Split your application into multiple modules or entry points and re-compile then only when needed.
  • Analyse your application using the trunk version - which provides the Story of your compile. This may or may not be relevant to the 1.6 compiler but it can indicate what's going on.

Showing empty view when ListView is empty

When you extend FragmentActivity or Activity and not ListActivity, you'll want to take a look at:

ListView.setEmptyView()

Bootstrap Element 100% Width

In bootstrap 4, you can use 'w-100' class (w as width, and 100 as 100%)

You can find documentation here: https://getbootstrap.com/docs/4.0/utilities/sizing/

PowerShell: Store Entire Text File Contents in Variable

On a side note, in PowerShell 3.0 you can use the Get-Content cmdlet with the new Raw switch:

$text = Get-Content .\file.txt -Raw 

How to get the URL without any parameters in JavaScript?

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

As @Sean said, fcntl() is largely standardized, and therefore available across platforms. The ioctl() function predates fcntl() in Unix, but is not standardized at all. That the ioctl() worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl() calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I got the same error when an imported library was trying to create a directory at path "./logs/".

It turns out that the library was trying to create it at the wrong location, i.e. inside the folder of my python interpreter instead of the base project directory. I solved the issue by setting the "Working directory" path to my project folder inside the "Run Configurations" menu of PyCharm. If instead you're using the terminal to run your code, maybe you just need to move inside the project folder before running it.

Login credentials not working with Gmail SMTP

I had same issue. And I fix it with creating an app-password for Email application on Mac. You can find it at my account -> Security -> Signing in to Google -> App passwords. below is the link for it. https://myaccount.google.com/apppasswords?utm_source=google-account&utm_medium=web

Twitter Bootstrap: div in container with 100% height

It is very simple. You can use

.fill .map 
{
  min-height: 100vh;
}

You can change height according to your requirement.

Recover unsaved SQL query scripts

I know this is an old thread but for anyone looking to retrieve a script after ssms crashes do the following

  1. Open Local Disk (C):
  2. Open users Folder
  3. Find the folder relevant for your username and open it
  4. Click the Documents file
  5. Click the Visual Studio folder or click Backup Files Folder if visible
  6. Click the Backup Files Folder
  7. Open Solution1 Folder
  8. Any recovered temporary files will be here. The files will end with vs followed by a number such as vs9E61
  9. Open the files and check for your lost code. Hope that helps. Those exact steps have just worked for me. im using Sql server Express 2017

Bigger Glyphicons

You can just give the glyphicon a font-size to your liking:

span.glyphicon-link {
    font-size: 1.2em;
}

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Bash function to find newest file matching pattern

The combination of find and ls works well for

  • filenames without newlines
  • not very large amount of files
  • not very long filenames

The solution:

find . -name "my-pattern" -print0 |
    xargs -r -0 ls -1 -t |
    head -1

Let's break it down:

With find we can match all interesting files like this:

find . -name "my-pattern" ...

then using -print0 we can pass all filenames safely to the ls like this:

find . -name "my-pattern" -print0 | xargs -r -0 ls -1 -t

additional find search parameters and patterns can be added here

find . -name "my-pattern" ... -print0 | xargs -r -0 ls -1 -t

ls -t will sort files by modification time (newest first) and print it one at a line. You can use -c to sort by creation time. Note: this will break with filenames containing newlines.

Finally head -1 gets us the first file in the sorted list.

Note: xargs use system limits to the size of the argument list. If this size exceeds, xargs will call ls multiple times. This will break the sorting and probably also the final output. Run

xargs  --show-limits

to check the limits on you system.

Note 2: use find . -maxdepth 1 -name "my-pattern" -print0 if you don't want to search files through subfolders.

Note 3: As pointed out by @starfry - -r argument for xargs is preventing the call of ls -1 -t, if no files were matched by the find. Thank you for the suggesion.

How to use ADB to send touch events to device using sendevent command?

You don't need to use

adb shell getevent -l

command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.

Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/

Is there a label/goto in Python?

No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.

how much memory can be accessed by a 32 bit machine?

Going back to a really basic idea, we have 32 bits for our memory addresses. That works out to 2^32 unique combinations of addresses. By convention, each address points to 1 byte of data. Therefore, we can access up to a total 2^32 bytes of data.

In a 32 bit OS, each register stores 32 bits or 4 bytes. 32 bits (1 word) of information are processed per clock cycle. If you want to access a particular 1 byte, conceptually, we can "extract" the individual bytes (e.g. byte 0, byte 1, byte 2, byte 3 etc.) by doing bitwise logical operations.

E.g. to get "dddddddd", take "aaaaaaaabbbbbbbbccccccccdddddddd" and logical AND with "00000000000000000000000011111111".

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

For entity Framework Core 2.0 or above, the correct way to do this is:

var firstName = "John";
var id = 12;
ctx.Database.ExecuteSqlCommand($"Update [User] SET FirstName = {firstName} WHERE Id = {id}";

Note that Entity Framework will produce the two parameters for you, so you are protected from Sql Injection.

Also note that it is NOT:

var firstName = "John";
var id = 12;
var sql = $"Update [User] SET FirstName = {firstName} WHERE Id = {id}";
ctx.Database.ExecuteSqlCommand(sql);

because this does NOT protect you from Sql Injection, and no parameters are produced.

See this for more.

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

This solved my problem: Kotlin Code:

val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)
fragmentTransaction.commitAllowingStateLoss()

How is commitAllowingStateLoss() is different than commit() ?

As per documentation:

Like commit() but allows the commit to be executed after an activity's state is saved. https://developer.android.com/reference/android/app/FragmentTransaction#commitAllowingStateLoss()

P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

Node.js global variables

I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:

// Some global/configuration file that gets called in initialisation

global.MyError = [Function of MyError];

Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:

  1. Define the Error class in the first place
  2. In the script where you're throwing it
  3. In the script where you're catching it

Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.

Convert Pandas DataFrame to JSON format

I think what the OP is looking for is:

with open('temp.json', 'w') as f:
    f.write(df.to_json(orient='records', lines=True))

This should do the trick.

Warning about SSL connection when connecting to MySQL database

Your connection URL should look like the below,

jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false

This will disable SSL and also suppress the SSL errors.

How can I increment a date by one day in Java?

In java 8 you can use java.time.LocalDate

LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1);   //Add one to the day field

You can convert in into java.util.Date object as follows.

Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

You can formate LocalDate into a String as follows.

String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

How to get longitude and latitude of any address?

Use the following code for getting lat and long using php. Here are two methods:

Type-1:

    <?php
     // Get lat and long by address         
        $address = $dlocation; // Google HQ
        $prepAddr = str_replace(' ','+',$address);
        $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
        $output= json_decode($geocode);
        $latitude = $output->results[0]->geometry->location->lat;
        $longitude = $output->results[0]->geometry->location->lng;

?>

edit - Google Maps requests must be over https

Type-2:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
     <script>
      var geocoder;
      var map;
      function initialize() {
        geocoder = new google.maps.Geocoder();
         var latlng = new google.maps.LatLng(50.804400, -1.147250);
        var mapOptions = {
         zoom: 6,
         center: latlng
        }
         map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
        }

       function codeAddress(address,tutorname,url,distance,prise,postcode) {
       var address = address;

        geocoder.geocode( { 'address': address}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
           var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });

      var infowindow = new google.maps.InfoWindow({
         content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
       });
        infowindow.open(map,marker);

          } /*else {
          alert('Geocode was not successful for the following reason: ' + status);
        }*/
       });
     }


      google.maps.event.addDomListener(window, 'load', initialize);

     window.onload = function(){
      initialize();
      // your code here
      <?php foreach($addr as $add) { 

      ?>
      codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
      <?php } ?>
    };
      </script>

     <div id="map-canvas12"></div>

How to display count of notifications in app launcher icon

I have figured out how this is done for Sony devices.

I've blogged about it here. I've also posted a seperate SO question about this here.


Sony devices use a class named BadgeReciever.

  1. Declare the com.sonyericsson.home.permission.BROADCAST_BADGE permission in your manifest file:

  2. Broadcast an Intent to the BadgeReceiver:

    Intent intent = new Intent();
    
    intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.yourdomain.yourapp.MainActivity");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", "99");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.yourdomain.yourapp");
    
    sendBroadcast(intent);
    
  3. Done. Once this Intent is broadcast the launcher should show a badge on your application icon.

  4. To remove the badge again, simply send a new broadcast, this time with SHOW_MESSAGE set to false:

    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
    

I've excluded details on how I found this to keep the answer short, but it's all available in the blog. Might be an interesting read for someone.

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

AngularJS ng-click to go to another page (with Ionic framework)

One think you should change is the call $state.go(). As described here:

The param passed should be the state name

$scope.create = function() {
  // instead of this
  //$state.go("/tab/newpost"); 

  // we should use this
  $state.go("tab.newpost"); 
};

Some cite from doc (the first parameter to of the [$state.go(to \[, toParams\] \[, options\]):

to

String Absolute State Name or Relative State Path

The name of the state that will be transitioned to or a relative state path. If the path starts with ^ or . then it is relative, otherwise it is absolute.

Some examples:

$state.go('contact.detail') will go to the 'contact.detail' state
$state.go('^') will go to a parent state.
$state.go('^.sibling') will go to a sibling state.
$state.go('.child.grandchild') will go to a grandchild state.

python catch exception and continue try block

No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.

What about a for-loop though?

funcs = do_smth1, do_smth2

for func in funcs:
    try:
        func()
    except Exception:
        pass  # or you could use 'continue'

Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.

Gitignore not working

I solved my problem doing the following:

First of all, I am a windows user, but i have faced similar issue. So, I am posting my solution here.

There is one simple reason why sometimes the .gitignore doesn`t work like it is supposed to. It is due to the EOL conversion behavior.

Here is a quick fix for that

Edit > EOL Conversion > Windows Format > Save

You can blame your text editor settings for that.

For example:

As i am a windows developer, I typically use Notepad++ for editing my text unlike Vim users.

So what happens is, when i open my .gitignore file using Notepad++, it looks something like this:

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore


# See https://help.github.com/ignore-files/ for more about ignoring files.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.dll
*.force
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

If i open the same file using the default Notepad, this is what i get

## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from  https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # See https://help.github.com/ignore-files/ for more about ignoring files. # User-specific files *.suo *.user *.userosscache 

So, you might have already guessed by looking at the output. Everything in the .gitignore has become a one liner, and since there is a ## in the start, it acts as if everything is commented.

The way to fix this is simple: Just open your .gitignore file with Notepad++ , then do the following

Edit > EOL Conversion > Windows Format > Save

The next time you open the same file with the windows default notepad, everything should be properly formatted. Try it and see if this works for you.

ipynb import another ipynb file

You can use import nbimporter then import notebookName

android: changing option menu items programmatically

To disable certain items:

MenuItem item = menu.findItem(R.id.ID_ASSING_TO_THE_ITEM_IN_MENU_XML);
item.setEnabled(false);

SQL Server : error converting data type varchar to numeric

thanks, try this instead

Select 
  STR(account_code) as account_code_Numeric,
  descr 
from account 
where  STR(account_code) = 1

I'm happy to help you

Converting JSON to XML in Java

If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.

Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.

How do I initialize a dictionary of empty lists in Python?

Use defaultdict instead:

from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')

This way you don't have to initialize all the keys you want to use to lists beforehand.

What is happening in your example is that you use one (mutable) list:

alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data

would output {0: [1, 2], 1: [1, 2]}.

how to convert binary string to decimal?

I gathered all what others have suggested and created following function which has 3 arguments, the number and the base which that number has come from and the base which that number is going to be on:

changeBase(1101000, 2, 10) => 104

Run Code Snippet to try it yourself:

_x000D_
_x000D_
function changeBase(number, fromBase, toBase) {_x000D_
                        if (fromBase == 10)_x000D_
                            return (parseInt(number)).toString(toBase)_x000D_
                        else if (toBase == 10)_x000D_
                            return parseInt(number, fromBase);_x000D_
                        else{_x000D_
                            var numberInDecimal = parseInt(number, fromBase);_x000D_
                            return (parseInt(numberInDecimal)).toString(toBase);_x000D_
                    }_x000D_
}_x000D_
_x000D_
$("#btnConvert").click(function(){_x000D_
  var number = $("#txtNumber").val(),_x000D_
  fromBase = $("#txtFromBase").val(),_x000D_
  toBase = $("#txtToBase").val();_x000D_
  $("#lblResult").text(changeBase(number, fromBase, toBase));_x000D_
});
_x000D_
#lblResult{_x000D_
  padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="txtNumber" type="text" placeholder="Number" />_x000D_
<input id="txtFromBase" type="text" placeholder="From Base" />_x000D_
<input id="txtToBase" type="text" placeholder="To Base" />_x000D_
<input id="btnConvert" type="button" value="Convert" />_x000D_
<span id="lblResult"></span>_x000D_
_x000D_
<p>Hint: <br />_x000D_
Try 110, 2, 10 and it will return 6; (110)<sub>2</sub> = 6<br />_x000D_
_x000D_
or 2d, 16, 10 => 45 meaning: (2d)<sub>16</sub> = 45<br />_x000D_
or 45, 10, 16 => 2d meaning: 45 = (2d)<sub>16</sub><br />_x000D_
or 2d, 2, 16 => 2d meaning: (101101)<sub>2</sub> = (2d)<sub>16</sub><br />_x000D_
</p>
_x000D_
_x000D_
_x000D_

FYI: If you want to pass 2d as hex number, you need to send it as a string so it goes like this: changeBase('2d', 16, 10)

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

Find OpenCV Version Installed on Ubuntu

1) Direct Answer: Try this:

   sudo updatedb
   locate OpenCVConfig.cmake

For me, I get:

   /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

To see the version, you can try:

   cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

giving

    ....
   SET(OpenCV_VERSION 2.3.1)
    ....

2) Better Answer:

"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).

Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.

How to dismiss ViewController in Swift?

@IBAction func back(_ sender: Any) {
        self.dismiss(animated: false, completion: nil)
    }

Angular EXCEPTION: No provider for Http

I faced this issue in my code. I only put this code in my app.module.ts.

import { HttpModule } from '@angular/http';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Modify the legend of pandas bar plot

If you need to call plot multiply times, you can also use the "label" argument:

ax = df1.plot(label='df1', y='y_var')
ax = df2.plot(label='df2', y='y_var')

While this is not the case in the OP question, this can be helpful if the DataFrame is in long format and you use groupby before plotting.

What is the intended use-case for git stash?

The main idea is

Stash the changes in a dirty working directory away

So Basicallly Stash command keep your some changes that you don't need them or want them at the moment; but you may need them.

Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

I had the error when using gpg-agent as my ssh-agent and using a gpg subkey as my ssh key https://wiki.archlinux.org/index.php/GnuPG#gpg-agent.

I suspect that the problem was caused by having an invalid pin entry tty for gpg caused by my sleep+lock command used in my sway config

bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock'"

or just the sleep/suspend

Reset the pin entry tty to fix the problem

gpg-connect-agent updatestartuptty /bye > /dev/null

and the fix for my sway sleep+lock command:

bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock; gpg-connect-agent updatestartuptty /bye > /dev/null'"

PHP cURL, extract an XML response

Just add header('Content-type: application/xml'); before your echo of the XML response and you will see an XML page.

How To: Best way to draw table in console app (C#)

This is an improvement to a previous answer. It adds support for values with varying lengths and rows with a varying number of cells. For example:

+------------------------------------------------------------------------------+
¦Identifier¦     Type¦               Description¦  CPU Credit Use¦Hours¦Balance¦
+----------+---------+--------------------------+----------------+-----+-------+
¦ i-1234154¦ t2.small¦       This is an example.¦         3263.75¦  360¦
+----------+---------+--------------------------+----------------+-----+
¦ i-1231412¦ t2.small¦  This is another example.¦         3089.93¦
+----------------------------------------------------------------+

Here is the code:

public class ArrayPrinter
{
    const string TOP_LEFT_JOINT = "+";
    const string TOP_RIGHT_JOINT = "+";
    const string BOTTOM_LEFT_JOINT = "+";
    const string BOTTOM_RIGHT_JOINT = "+";
    const string TOP_JOINT = "-";
    const string BOTTOM_JOINT = "-";
    const string LEFT_JOINT = "+";
    const string JOINT = "+";
    const string RIGHT_JOINT = "¦";
    const char HORIZONTAL_LINE = '-';
    const char PADDING = ' ';
    const string VERTICAL_LINE = "¦";

    private static int[] GetMaxCellWidths(List<string[]> table)
    {
        int maximumCells = 0;
        foreach (Array row in table)
        {
            if (row.Length > maximumCells)
                maximumCells = row.Length;
        }

        int[] maximumCellWidths = new int[maximumCells];
        for (int i = 0; i < maximumCellWidths.Length; i++)
            maximumCellWidths[i] = 0;

        foreach (Array row in table)
        {
            for (int i = 0; i < row.Length; i++)
            {
                if (row.GetValue(i).ToString().Length > maximumCellWidths[i])
                    maximumCellWidths[i] = row.GetValue(i).ToString().Length;
            }
        }

        return maximumCellWidths;
    }

    public static string GetDataInTableFormat(List<string[]> table)
    {
        StringBuilder formattedTable = new StringBuilder();
        Array nextRow = table.FirstOrDefault();
        Array previousRow = table.FirstOrDefault();

        if (table == null || nextRow == null)
            return String.Empty;

        // FIRST LINE:
        int[] maximumCellWidths = GetMaxCellWidths(table);
        for (int i = 0; i < nextRow.Length; i++)
        {
            if (i == 0 && i == nextRow.Length - 1)
                formattedTable.Append(String.Format("{0}{1}{2}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
            else if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == nextRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
            else
                formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
        }

        int rowIndex = 0;
        int lastRowIndex = table.Count - 1;
        foreach (Array thisRow in table)
        {
            // LINE WITH VALUES:
            int cellIndex = 0;
            int lastCellIndex = thisRow.Length - 1;
            foreach (object thisCell in thisRow)
            {
                string thisValue = thisCell.ToString().PadLeft(maximumCellWidths[cellIndex], PADDING);

                if (cellIndex == 0 && cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                else if (cellIndex == 0)
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
                else if (cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                else
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));

                cellIndex++;
            }

            previousRow = thisRow;

            // SEPARATING LINE:
            if (rowIndex != lastRowIndex)
            {
                nextRow = table[rowIndex + 1];

                int maximumCells = Math.Max(previousRow.Length, nextRow.Length);
                for (int i = 0; i < maximumCells; i++)
                {
                    if (i == 0 && i == maximumCells - 1)
                    {
                        formattedTable.Append(String.Format("{0}{1}{2}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                    }
                    else if (i == 0)
                    {
                        formattedTable.Append(String.Format("{0}{1}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                    }
                    else if (i == maximumCells - 1)
                    {
                        if (i > previousRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                        else if (i > previousRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                        else
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                    }
                    else
                    {
                        if (i > previousRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                        else if (i > nextRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                        else
                            formattedTable.Append(String.Format("{0}{1}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                    }
                }
            }

            rowIndex++;
        }

        // LAST LINE:
        for (int i = 0; i < previousRow.Length; i++)
        {
            if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == previousRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
            else
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
        }

        return formattedTable.ToString();
    }
}

How to check if a "lateinit" variable has been initialized?

You can easily do this by:

::variableName.isInitialized

or

this::variableName.isInitialized

But if you are inside a listener or inner class, do this:

this@OuterClassName::variableName.isInitialized

Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:

class Test {
    lateinit var str:String
}

And to check if str is initialized:

enter image description here

What we are doing here: checking isInitialized for field str of Test class in Test2 class. And we get an error backing field of var is not accessible at this point. Check a question already raised about this.

Check string for nil & empty

In my opinion, the best way to check the nil and empty string is to take the string count.

var nilString : String?
print(nilString.count) // count is nil

var emptyString = ""
print(emptyString.count) // count is 0

// combine both conditions for optional string variable
if string?.count == nil || string?.count == 0 {
   print("Your string is either empty or nil")
}

Selected tab's color in Bottom Navigation View

I am using a com.google.android.material.bottomnavigation.BottomNavigationView (not the same as OP's) and I tried a variety of the suggested solutions above, but the only thing that worked was setting app:itemBackground and app:itemIconTint to my selector color worked for me.

        <com.google.android.material.bottomnavigation.BottomNavigationView
            style="@style/BottomNavigationView"
            android:foreground="?attr/selectableItemBackground"
            android:theme="@style/BottomNavigationView"
            app:itemBackground="@color/tab_color"
            app:itemIconTint="@color/tab_color"
            app:itemTextColor="@color/bottom_navigation_text_color"
            app:labelVisibilityMode="labeled"
            app:menu="@menu/bottom_navigation" />

My color/tab_color.xml uses android:state_checked

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

and I am also using a selected state color for color/bottom_navigation_text_color.xml

enter image description here

Not totally relevant here but for full transparency, my BottomNavigationView style is as follows:

    <style name="BottomNavigationView" parent="Widget.Design.BottomNavigationView">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">@dimen/bottom_navigation_height</item>
        <item name="android:layout_gravity">bottom</item>
        <item name="android:textSize">@dimen/bottom_navigation_text_size</item>
    </style>

How to convert an XML file to nice pandas dataframe?

You can also convert by creating a dictionary of elements and then directly converting to a data frame:

import xml.etree.ElementTree as ET
import pandas as pd

# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags>   <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" />   <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" />   <row Id="3" TagName="elicitation" Count="10" />   <row Id="5" TagName="open-source" Count="16" /> </tags>

root = ET.parse('test.xml').getroot()

tags = {"tags":[]}
for elem in root:
    tag = {}
    tag["Id"] = elem.attrib['Id']
    tag["TagName"] = elem.attrib['TagName']
    tag["Count"] = elem.attrib['Count']
    tags["tags"]. append(tag)

df_users = pd.DataFrame(tags["tags"])
df_users.head()

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

Create two-dimensional arrays and access sub-arrays in Ruby

x.transpose[6][3..8] or x[3..8].map {|r| r [6]} would give what you want.

Example:

a = [ [1,  2,  3,  4,  5],
      [6,  7,  8,  9,  10],
      [11, 12, 13, 14, 15],
      [21, 22, 23, 24, 25]
    ]

#a[1..2][2]  -> [8,13]
puts a.transpose[2][1..2].inspect   # [8,13]
puts a[1..2].map {|r| r[2]}.inspect  # [8,13]

Confirm button before running deleting routine from website

_x000D_
_x000D_
<?php _x000D_
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));_x000D_
 if(isset($_POST[add]))_x000D_
 {_x000D_
 $sno = mysqli_real_escape_string($con,$_POST[sno]);_x000D_
   $name = mysqli_real_escape_string($con,$_POST[sname]);_x000D_
   $course = mysqli_real_escape_string($con,$_POST[course]);_x000D_
 _x000D_
   $query = "insert into students(sno,name,course) values($sno,'$name','$course')";_x000D_
   //echo $query;_x000D_
   $result = mysqli_query($con,$query);_x000D_
   printf ("New Record has id %d.\n", mysqli_insert_id($con));_x000D_
  mysqli_close($con);_x000D_
   _x000D_
 }  _x000D_
?>_x000D_
  
_x000D_
<html>_x000D_
<head>_x000D_
<title>mysql_insert_id Example</title>_x000D_
</head>_x000D_
<body>_x000D_
<form action="" method="POST">_x000D_
Enter S.NO: <input type="text" name="sno"/><br/>_x000D_
Enter Student Name: <input type="text" name="sname"/><br/>_x000D_
Enter Course: <input type="text" name="course"/><br/>_x000D_
<input type="submit" name="add" value="Add Student"/>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Renaming column names of a DataFrame in Spark Scala

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Ruby Array find_first object?

Do you need the object itself or do you just need to know if there is an object that satisfies. If the former then yes: use find:

found_object = my_array.find { |e| e.satisfies_condition? }

otherwise you can use any?

found_it = my_array.any?  { |e| e.satisfies_condition? }

The latter will bail with "true" when it finds one that satisfies the condition. The former will do the same, but return the object.

How to Allow Remote Access to PostgreSQL database

In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files:

postgresql.conf
pg_hba.conf

Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the parameters and their meanings)

First of all configure PostgreSQL service to listen on port 5432 on all network interfaces in Windows 7 machine:
open the file postgresql.conf (usually located in C:\Program Files\PostgreSQL\9.2\data) and sets the parameter

listen_addresses = '*'

Check the network address of WindowsXP virtual machine, and sets parameters in pg_hba.conf file (located in the same directory of postgresql.conf) so that postgresql can accept connections from virtual machine hosts.
For example, if the machine with Windows XP have 192.168.56.2 IP address, add in the pg_hba.conf file:

host all all 192.168.56.1/24 md5

this way, PostgreSQL will accept connections from all hosts on the network 192.168.1.XXX.

Restart the PostgreSQL service in Windows 7 (Services-> PosgreSQL 9.2: right click and restart sevice). Install pgAdmin on windows XP machine and try to connect to PostgreSQL.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

In Eclipse,

When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.

Solving "adb server version doesn't match this client" error

In my case the solution was this on an Ubuntu based OS:

adb kill-server
sudo cp ~/Android/Sdk/platform-tools/adb /usr/bin/adb
sudo chmod +x /usr/bin/adb
adb start-server

kudos: https://stackoverflow.com/a/38166059/3765109

Convert timestamp to readable date/time PHP

Try it.

<?php
 $timestamp=1333342365;
 echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
 ?>

jQuery - how to write 'if not equal to' (opposite of ==)

The opposite of the == compare operator is !=.

Python SQLite: database is locked

In Linux you can do something similar, for example, if your locked file is development.db:

$ fuser development.db This command will show what process is locking the file:

development.db: 5430 Just kill the process...

kill -9 5430 ...And your database will be unlocked.

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

How to set ssh timeout?

Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.

nohup ./my-script-that-may-take-long-to-finish.sh &
./check-if-previous-script-ran-or-exit.sh

echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt

So in the second one you just check if the file exists.

How can I detect if a selector returns null?

You may want to do this all the time by default. I've been struggling to wrap the jquery function or jquery.fn.init method to do this without error, but you can make a simple change to the jquery source to do this. Included are some surrounding lines you can search for. I recommend searching jquery source for The jQuery object is actually just the init constructor 'enhanced'

var
  version = "3.3.1",

  // Define a local copy of jQuery
  jQuery = function( selector, context ) {

    // The jQuery object is actually just the init constructor 'enhanced'
    // Need init if jQuery is called (just allow error to be thrown if not included)
    var result = new jQuery.fn.init( selector, context );
    if ( result.length === 0 ) {
      if (window.console && console.warn && context !== 'failsafe') {
        if (selector != null) {
          console.warn(
            new Error('$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:'+context)
          );
        }
      }
    }
    return result;
  },

  // Support: Android <=4.0 only
  // Make sure we trim BOM and NBSP
  rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

jQuery.fn = jQuery.prototype = {

Last but not least, you can get the uncompressed jquery source code here: http://code.jquery.com/

Is there an alternative sleep function in C to milliseconds?

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

Converting cv::Mat to IplImage*

 (you have cv::Mat old)
 IplImage copy = old;
 IplImage* new_image = &copy;

you work with new as an originally declared IplImage*.

git diff file against its last change

One of the ways to use git diff is:

git diff <commit> <path>

And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...

So the answer to your question is:

git diff HEAD^^ myfile

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

What is default color for text in textview?

There are some default colors defined in android.R.color

int c = getResources().getColor(android.R.color.primary_text_dark);

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You are missing the dot on the selector, and you can use toggleClass method on jquery:

$(".result").hover(
  function () {
    $(this).toggleClass("result_hover")      
  }
);

Check if a value is within a range of numbers

Here is an option with only a single comparison.

// return true if in range, otherwise false
function inRange(x, min, max) {
    return ((x-min)*(x-max) <= 0);
}

console.log(inRange(5, 1, 10));     // true
console.log(inRange(-5, 1, 10));    // false
console.log(inRange(20, 1, 10));    // false

How to read files from resources folder in Scala?

The required file can be accessed as below from resource folder in scala

val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString

Set CFLAGS and CXXFLAGS options using CMake

On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")

It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.

Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS

How to run 'sudo' command in windows

I am glad to help you.

To make a sudo command follow the steps :-

  1. Make a folder env in C:\ Drive.
  2. Make a folder inside the env folder named as bin.
  3. Now add C:\env\bin to your PATH.
  4. Create a file sudo.bat in C:\env\bin.
  5. Edit it with notepad and write this code :-
    https://gist.github.com/coder-examples/5ca6c141d6d356ddba4e356d63fb2c13

Hope this will help you

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

Read and overwrite a file in Python

I find it easier to remember to just read it and then write it.

For example:

with open('file') as f:
    data = f.read()
with open('file', 'w') as f:
    f.write('hello')

Angular2 Routing with Hashtag to page anchor

After reading all of the solutions, I looked for a component and I found one which does exactly what the original question asked for: scrolling to anchor links. https://www.npmjs.com/package/ng2-scroll-to

When you install it, you use syntax like:

// app.awesome.component.ts
@Component({
   ...
   template: `...
        <a scrollTo href="#main-section">Scroll to main section</a>
        <button scrollTo scrollTargetSelector="#test-section">Scroll to test section</a>
        <button scrollTo scrollableElementSelector="#container" scrollYTarget="0">Go top</a>
        <!-- Further content here -->
        <div id="container">
            <section id="main-section">Bla bla bla</section>
            <section id="test-section">Bla bla bla</section>
        <div>
   ...`,
})
export class AwesomeComponent {
}

It has worked really well for me.

After MySQL install via Brew, I get the error - The server quit without updating PID file

I had the similar issue. But the following commands saved me.

cd /usr/local/Cellar
sudo chown _mysql mysql

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.