Programs & Examples On #Adjacency list

An adjacency list is a representation of a graph, a collection of unordered lists, one for each vertex in the graph.

What is better, adjacency lists or adjacency matrices for graph problems in C++?

This answer is not just for C++ since everything mentioned is about the data structures themselves, regardless of language. And, my answer is assuming that you know the basic structure of adjacency lists and matrices.

Memory

If memory is your primary concern you can follow this formula for a simple graph that allows loops:

An adjacency matrix occupies n2/8 byte space (one bit per entry).

An adjacency list occupies 8e space, where e is the number of edges (32bit computer).

If we define the density of the graph as d = e/n2 (number of edges divided by the maximum number of edges), we can find the "breakpoint" where a list takes up more memory than a matrix:

8e > n2/8 when d > 1/64

So with these numbers (still 32-bit specific) the breakpoint lands at 1/64. If the density (e/n2) is bigger than 1/64, then a matrix is preferable if you want to save memory.

You can read about this at wikipedia (article on adjacency matrices) and a lot of other sites.

Side note: One can improve the space-efficiency of the adjacency matrix by using a hash table where the keys are pairs of vertices (undirected only).

Iteration and lookup

Adjacency lists are a compact way of representing only existing edges. However, this comes at the cost of possibly slow lookup of specific edges. Since each list is as long as the degree of a vertex the worst case lookup time of checking for a specific edge can become O(n), if the list is unordered. However, looking up the neighbours of a vertex becomes trivial, and for a sparse or small graph the cost of iterating through the adjacency lists might be negligible.

Adjacency matrices on the other hand use more space in order to provide constant lookup time. Since every possible entry exists you can check for the existence of an edge in constant time using indexes. However, neighbour lookup takes O(n) since you need to check all possible neighbours. The obvious space drawback is that for sparse graphs a lot of padding is added. See the memory discussion above for more information on this.

If you're still unsure what to use: Most real-world problems produce sparse and/or large graphs, which are better suited for adjacency list representations. They might seem harder to implement but I assure you they aren't, and when you write a BFS or DFS and want to fetch all neighbours of a node they're just one line of code away. However, note that I'm not promoting adjacency lists in general.

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

I've just seen this problem myself, Jboss AS7 with jdk1.5.0_09. Update System Property JAVA_HOME to jdk1.7+ to fix (I'm using jdk1.7.0_67).

Vue.js data-bind style backgroundImage not working

Binding background image style using a dynamic value from v-for loop could be done like this.

<div v-for="i in items" :key="n" 
  :style="{backgroundImage: 'url('+require('./assets/cars/'+i.src+'.jpg')+')'}">
</div>

How to fix symbol lookup error: undefined symbol errors in a cluster environment

yum update

helped me out. After I had

wget: symbol lookup error: wget: undefined symbol: psl_latest

How do you create a temporary table in an Oracle database?

Yep, Oracle has temporary tables. Here is a link to an AskTom article describing them and here is the official oracle CREATE TABLE documentation.

However, in Oracle, only the data in a temporary table is temporary. The table is a regular object visible to other sessions. It is a bad practice to frequently create and drop temporary tables in Oracle.

CREATE GLOBAL TEMPORARY TABLE today_sales(order_id NUMBER)
ON COMMIT PRESERVE ROWS;

Oracle 18c added private temporary tables, which are single-session in-memory objects. See the documentation for more details. Private temporary tables can be dynamically created and dropped.

CREATE PRIVATE TEMPORARY TABLE ora$ptt_today_sales AS
SELECT * FROM orders WHERE order_date = SYSDATE;

Temporary tables can be useful but they are commonly abused in Oracle. They can often be avoided by combining multiple steps into a single SQL statement using inline views.

Sending JWT token in the headers with Postman

If you wish to use postman the right way is to use the headers as such

key: Authorization

value: jwt {token}

as simple as that.

How to get http headers in flask?

from flask import request
request.headers.get('your-header-name')

request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:

request.headers['your-header-name']

What is the default username and password in Tomcat?

In Tomcat 7 you have to add this to tomcat-users.xml (On windows 7 it is located by default installation here: c:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\ )

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <role rolename="admin-gui"/>
  <role rolename="admin-script"/>
  <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/>
</tomcat-users>

NOTE that there shouldn't be ANY spaces between roles for admin, as this list should be comma separated.

So, instead of this (as suggested in some answers:

<user username="admin" password="admin" roles="manager-gui, manager-script, manager-jmx, manager-status, admin-gui, admin-script"/>

it MUST be like this:

  <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/>

How do I get Maven to use the correct repositories?

Basically, all Maven is telling you is that certain dependencies in your project are not available in the central maven repository. The default is to look in your local .m2 folder (local repository), and then any configured repositories in your POM, and then the central maven repository. Look at the repositories section of the Maven reference.

The problem is that the project that was checked in didn't configure the POM in such a way that all the dependencies could be found and the project could be built from scratch.

Test file upload using HTTP PUT method

curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"

Checking if type == list in python

Python 3.7.7

import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
    print("It is a list")

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

How do you use math.random to generate random ints?

double  i = 2+Math.random()*100;
int j = (int)i;
System.out.print(j);

Cannot add a project to a Tomcat server in Eclipse

In my case:

Project properties ? Project Facets. Make sure "Dynamic Web Module" is checked. Finally, I enter the version number "2.3" instead of "3.0". After that, the Apache Tomcat 5.5 runtime is listed in the "Runtimes" tab.

Python: CSV write by column rather than row

The reason csv doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call zip() on them to transpose them after.

>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]
>>> zip(*l)
[('Result_1', 1, 5), ('Result_2', 2, 6), ('Result_3', 3, 7), ('Result_4', 4, 8)]

Set the layout weight of a TextView programmatically

This work for me, and I hope it will work for you also

Set the LayoutParams for the parent view first:

myTableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
                TableLayout.LayoutParams.FILL_PARENT));

then set for the TextView (child):

 TableLayout.LayoutParams textViewParam = new TableLayout.LayoutParams
     (TableLayout.LayoutParams.WRAP_CONTENT,
     TableLayout.LayoutParams.WRAP_CONTENT,1f);
     //-- set components margins
     textViewParam.setMargins(5, 0, 5,0);
     myTextView.setLayoutParams(textViewParam); 

Regex for remove everything after | (with | )

The pipe, |, is a special-character in regex (meaning "or") and you'll have to escape it with a \.

Using your current regex:

\|.*$

I've tried this in Notepad++, as you've mentioned, and it appears to work well.

How to unit test abstract classes: extend with stubs?

If your abstract class contains concrete functionality that has business value, then I will usually test it directly by creating a test double that stubs out the abstract data, or by using a mocking framework to do this for me. Which one I choose depends a lot on whether I need to write test-specific implementations of the abstract methods or not.

The most common scenario in which I need to do this is when I'm using the Template Method pattern, such as when I'm building some sort of extensible framework that will be used by a 3rd party. In this case, the abstract class is what defines the algorithm that I want to test, so it makes more sense to test the abstract base than a specific implementation.

However, I think it's important that these tests should focus on the concrete implementations of real business logic only; you shouldn't unit test implementation details of the abstract class because you'll end up with brittle tests.

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
    {
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
        {
            strValue = _tags["101"];
            Console.WriteLine(strValue);
        }

        if (_tags.TryGetValue("101", out strValue))
        {
            Console.WriteLine(strValue);
        }
    }
}

Is there a function to split a string in PL/SQL?

I needed a function that splits a clob and makes sure the function is usable in sql.

create or replace type vchar_tab is table of varchar2(4000)
/
create or replace function split(
    p_list in clob,
    p_separator in varchar2 default '|'
) return vchar_tab pipelined is
    C_SQL_VCHAR_MAX constant integer:=4000;
    C_MAX_AMOUNT    constant integer:=28000;
    C_SEPARATOR_LEN constant integer:=length(p_separator);
    l_amount        integer:=C_MAX_AMOUNT;
    l_offset        integer:=1;
    l_buffer        varchar2(C_MAX_AMOUNT);
    l_list          varchar2(32767);
    l_index         integer;
begin
    if p_list is not null then
        loop
            l_index:=instr(l_list, p_separator);
            if l_index > C_SQL_VCHAR_MAX+1 then
                raise_application_error(-20000, 'item is too large for sql varchar2: len='||(l_index-1));
            elsif l_index > 0 then -- found an item, pipe it
                pipe row (substr(l_list, 1, l_index-1));
                l_list:=substr(l_list, l_index+C_SEPARATOR_LEN);
            elsif length(l_list) > C_SQL_VCHAR_MAX then
                raise_application_error(-20001, 'item is too large for sql varchar2: length exceeds '||length(l_list));
            elsif l_amount = C_MAX_AMOUNT then -- more to read from the clob
                dbms_lob.read(p_list, l_amount, l_offset, l_buffer);
                l_list:=l_list||l_buffer;
            else -- read through the whole clob
                if length(l_list) > 0 then
                    pipe row (l_list);
                end if;
                exit;
            end if;
        end loop;
    end if;

    return;
exception
    when no_data_needed then -- this happens when you don't fetch all records
        null;
end;
/

Test:

select *
from table(split('ASDF|IUYT|KJHG|ASYD'));

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Just one sentence to say Instruct Internet Explorer to use its latest rendering engine

<meta http-equiv="x-ua-compatible" content="ie=edge">

How do I delete specific characters from a particular String in Java?

You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.

In some cases a StringBuffer might help you instead.

Normal arguments vs. keyword arguments

I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args and **kwargs (from this site):

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.

How to hide keyboard in swift on pressing return key?

I hate to add the same function to every UIViewController. By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".

extension UIViewController: UITextFieldDelegate{
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true;
    }
}

When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
}

You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)

Excel doesn't update value unless I hit Enter

I have the same problem with that guy here: mrexcel.com/forum/excel-questions/318115-enablecalculation.html Application.CalculateFull sold my problem. However I am afraid if this will happen again. I will try not to use EnableCalculation again.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Steps:

  1. Add platform runner in build.gralde
    => testCompile group: 'org.junit.platform', name: 'junit-platform-runner', version: '1.7.0'
  2. Anotate test class with @RunWith => @RunWith(JunitPlatform.class)

What exactly is \r in C language?

'\r' is the carriage return character. The main times it would be useful are:

  1. When reading text in binary mode, or which may come from a foreign OS, you'll find (and probably want to discard) it due to CR/LF line-endings from Windows-format text files.

  2. When writing to an interactive terminal on stdout or stderr, '\r' can be used to move the cursor back to the beginning of the line, to overwrite it with new contents. This makes a nice primitive progress indicator.

The example code in your post is definitely a wrong way to use '\r'. It assumes a carriage return will precede the newline character at the end of a line entered, which is non-portable and only true on Windows. Instead the code should look for '\n' (newline), and discard any carriage return it finds before the newline. Or, it could use text mode and have the C library handle the translation (but text mode is ugly and probably should not be used).

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Can I change the height of an image in CSS :before/:after pseudo-elements?

Note that the :after pseudo-element is a box, which in turn contains the generated image. There is no way to style the image, but you can style the box.

The following is just an idea, and the solution above is more practical.

.pdflink:after {
    content: url('/images/pdf.png');
    transform: scale(.5);
}

http://jsfiddle.net/Nwupm/

Drawbacks: you need to know the intrinsic dimensions of the image, and it leaves you with some whitespace, which I can't get rid of ATM.

Getting Current time to display in Label. VB.net

try

total.Text = DateTime.Now.ToString()

or

Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()

You declare Start as an Integer, while you are trying to put a DateTime in it, which is not possible.

Should I use int or Int32

In my experience it's been a convention thing. I'm not aware of any technical reason to use int over Int32, but it's:

  1. Quicker to type.
  2. More familiar to the typical C# developer.
  3. A different color in the default visual studio syntax highlighting.

I'm especially fond of that last one. :)

google-services.json for different productFlavors

Hey Friends also looks for name use only lowercase then u don't get this error

Fast and simple String encrypt/decrypt in JAVA

Update

the library already have Java/Kotlin support, see github.


Original

To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:

Add the gradle library:

compile 'se.simbio.encryption:library:2.0.0'

and use it:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here

Encryption.java

package se.simbio.encryption;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

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

/**
 * A class to make more easy and simple the encrypt routines, this is the core of Encryption library
 */
public class Encryption {

    /**
     * The Builder used to create the Encryption instance and that contains the information about
     * encryption specifications, this instance need to be private and careful managed
     */
    private final Builder mBuilder;

    /**
     * The private and unique constructor, you should use the Encryption.Builder to build your own
     * instance or get the default proving just the sensible information about encryption
     */
    private Encryption(Builder builder) {
        mBuilder = builder;
    }

    /**
     * @return an default encryption instance or {@code null} if occur some Exception, you can
     * create yur own Encryption instance using the Encryption.Builder
     */
    public static Encryption getDefault(String key, String salt, byte[] iv) {
        try {
            return Builder.getDefaultBuilder(key, salt, iv).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Encrypt a String
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
    }

    /**
     * This is a sugar method that calls encrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     */
    public String encryptOrNull(String data) {
        try {
            return encrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls encrypt method in background, it is a good idea to use this
     * one instead the default method because encryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be encrypted
     * @param callback the Callback to handle the results
     */
    public void encryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String encrypt = encrypt(data);
                    if (encrypt == null) {
                        callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(encrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * Decrypt a String
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        return new String(dataBytesDecrypted);
    }

    /**
     * This is a sugar method that calls decrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     */
    public String decryptOrNull(String data) {
        try {
            return decrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls decrypt method in background, it is a good idea to use this
     * one instead the default method because decryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be decrypted
     * @param callback the Callback to handle the results
     */
    public void decryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String decrypt = decrypt(data);
                    if (decrypt == null) {
                        callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(decrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * creates a 128bit salted aes key
     *
     * @param key encoded input key
     *
     * @return aes 128 bit salted key
     *
     * @throws NoSuchAlgorithmException     if no installed provider that can provide the requested
     *                                      by the Builder secret key type
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws InvalidKeySpecException      if the specified key specification cannot be used to
     *                                      generate a secret key
     * @throws NullPointerException         if the specified Builder secret key type is {@code null}
     */
    private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
        KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
    }

    /**
     * takes in a simple string and performs an sha1 hash
     * that is 128 bits long...we then base64 encode it
     * and return the char array
     *
     * @param key simple inputted string
     *
     * @return sha1 base64 encoded representation
     *
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws NoSuchAlgorithmException     if the Builder digest algorithm is not available
     * @throws NullPointerException         if the Builder digest algorithm is {@code null}
     */
    private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
        messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
        return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
    }

    /**
     * When you encrypt or decrypt in callback mode you get noticed of result using this interface
     */
    public interface Callback {

        /**
         * Called when encrypt or decrypt job ends and the process was a success
         *
         * @param result the encrypted or decrypted String
         */
        void onSuccess(String result);

        /**
         * Called when encrypt or decrypt job ends and has occurred an error in the process
         *
         * @param exception the Exception related to the error
         */
        void onError(Exception exception);

    }

    /**
     * This class is used to create an Encryption instance, you should provide ALL data or start
     * with the Default Builder provided by the getDefaultBuilder method
     */
    public static class Builder {

        private byte[] mIv;
        private int mKeyLength;
        private int mBase64Mode;
        private int mIterationCount;
        private String mSalt;
        private String mKey;
        private String mAlgorithm;
        private String mKeyAlgorithm;
        private String mCharsetName;
        private String mSecretKeyType;
        private String mDigestAlgorithm;
        private String mSecureRandomAlgorithm;
        private SecureRandom mSecureRandom;
        private IvParameterSpec mIvParameterSpec;

        /**
         * @return an default builder with the follow defaults:
         * the default char set is UTF-8
         * the default base mode is Base64
         * the Secret Key Type is the PBKDF2WithHmacSHA1
         * the default salt is "some_salt" but can be anything
         * the default length of key is 128
         * the default iteration count is 65536
         * the default algorithm is AES in CBC mode and PKCS 5 Padding
         * the default secure random algorithm is SHA1PRNG
         * the default message digest algorithm SHA1
         */
        public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
            return new Builder()
                    .setIv(iv)
                    .setKey(key)
                    .setSalt(salt)
                    .setKeyLength(128)
                    .setKeyAlgorithm("AES")
                    .setCharsetName("UTF8")
                    .setIterationCount(1)
                    .setDigestAlgorithm("SHA1")
                    .setBase64Mode(Base64.DEFAULT)
                    .setAlgorithm("AES/CBC/PKCS5Padding")
                    .setSecureRandomAlgorithm("SHA1PRNG")
                    .setSecretKeyType("PBKDF2WithHmacSHA1");
        }

        /**
         * Build the Encryption with the provided information
         *
         * @return a new Encryption instance with provided information
         *
         * @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
         * @throws NullPointerException     if the SecureRandomAlgorithm is {@code null} or if the
         *                                  IV byte array is null
         */
        public Encryption build() throws NoSuchAlgorithmException {
            setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
            setIvParameterSpec(new IvParameterSpec(getIv()));
            return new Encryption(this);
        }

        /**
         * @return the charset name
         */
        private String getCharsetName() {
            return mCharsetName;
        }

        /**
         * @param charsetName the new charset name
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setCharsetName(String charsetName) {
            mCharsetName = charsetName;
            return this;
        }

        /**
         * @return the algorithm
         */
        private String getAlgorithm() {
            return mAlgorithm;
        }

        /**
         * @param algorithm the algorithm to be used
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setAlgorithm(String algorithm) {
            mAlgorithm = algorithm;
            return this;
        }

        /**
         * @return the key algorithm
         */
        private String getKeyAlgorithm() {
            return mKeyAlgorithm;
        }

        /**
         * @param keyAlgorithm the keyAlgorithm to be used in keys
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyAlgorithm(String keyAlgorithm) {
            mKeyAlgorithm = keyAlgorithm;
            return this;
        }

        /**
         * @return the Base 64 mode
         */
        private int getBase64Mode() {
            return mBase64Mode;
        }

        /**
         * @param base64Mode set the base 64 mode
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setBase64Mode(int base64Mode) {
            mBase64Mode = base64Mode;
            return this;
        }

        /**
         * @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
         * are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         */
        private String getSecretKeyType() {
            return mSecretKeyType;
        }

        /**
         * @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
         *                      changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecretKeyType(String secretKeyType) {
            mSecretKeyType = secretKeyType;
            return this;
        }

        /**
         * @return the value used for salting
         */
        private String getSalt() {
            return mSalt;
        }

        /**
         * @param salt the value used for salting
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSalt(String salt) {
            mSalt = salt;
            return this;
        }

        /**
         * @return the key
         */
        private String getKey() {
            return mKey;
        }

        /**
         * @param key the key.
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKey(String key) {
            mKey = key;
            return this;
        }

        /**
         * @return the length of key
         */
        private int getKeyLength() {
            return mKeyLength;
        }

        /**
         * @param keyLength the length of key
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyLength(int keyLength) {
            mKeyLength = keyLength;
            return this;
        }

        /**
         * @return the number of times the password is hashed
         */
        private int getIterationCount() {
            return mIterationCount;
        }

        /**
         * @param iterationCount the number of times the password is hashed
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIterationCount(int iterationCount) {
            mIterationCount = iterationCount;
            return this;
        }

        /**
         * @return the algorithm used to generate the secure random
         */
        private String getSecureRandomAlgorithm() {
            return mSecureRandomAlgorithm;
        }

        /**
         * @param secureRandomAlgorithm the algorithm to generate the secure random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
            mSecureRandomAlgorithm = secureRandomAlgorithm;
            return this;
        }

        /**
         * @return the IvParameterSpec bytes array
         */
        private byte[] getIv() {
            return mIv;
        }

        /**
         * @param iv the byte array to create a new IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIv(byte[] iv) {
            mIv = iv;
            return this;
        }

        /**
         * @return the SecureRandom
         */
        private SecureRandom getSecureRandom() {
            return mSecureRandom;
        }

        /**
         * @param secureRandom the Secure Random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandom(SecureRandom secureRandom) {
            mSecureRandom = secureRandom;
            return this;
        }

        /**
         * @return the IvParameterSpec
         */
        private IvParameterSpec getIvParameterSpec() {
            return mIvParameterSpec;
        }

        /**
         * @param ivParameterSpec the IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
            mIvParameterSpec = ivParameterSpec;
            return this;
        }

        /**
         * @return the message digest algorithm
         */
        private String getDigestAlgorithm() {
            return mDigestAlgorithm;
        }

        /**
         * @param digestAlgorithm the algorithm to be used to get message digest instance
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setDigestAlgorithm(String digestAlgorithm) {
            mDigestAlgorithm = digestAlgorithm;
            return this;
        }

    }

}    

Move view with keyboard using Swift

I see all answers are moving the view itself by the value of the keyboard height. Well, I have an elaborate answer, which could be useful if you are using constraints i.e autolayout, that moves a view by changing its constraint value (bottom or top constraints for example) by a predefined value or you can use keyboard size value.

In this example, I use bottom constraint from the textfield to Bottom Layout View with initial value of 175.

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()        
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}

func keyboardWillShow(notification: NSNotification) {
    //To retrieve keyboard size, uncomment following line
    //let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
    bottomConstraint.constant = 260
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

func keyboardWillHide(notification: NSNotification) {
    //To retrieve keyboard size, uncomment following line
    //let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
    bottomConstraint.constant = 175
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

How to fetch all Git branches

You can fetch all branches from all remotes like this:

git fetch --all

It's basically a power move.

fetch updates local copies of remote branches so this is always safe for your local branches BUT:

  1. fetch will not update local branches (which track remote branches); if you want to update your local branches you still need to pull every branch.

  2. fetch will not create local branches (which track remote branches), you have to do this manually. If you want to list all remote branches: git branch -a

To update local branches which track remote branches:

git pull --all

However, this can be still insufficient. It will work only for your local branches which track remote branches. To track all remote branches execute this oneliner BEFORE git pull --all:

git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done

TL;DR version

git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all

(It seems that pull fetches all branches from all remotes, but I always fetch first just to be sure.)

Run the first command only if there are remote branches on the server that aren't tracked by your local branches.

P.S. AFAIK git fetch --all and git remote update are equivalent.



Kamil Szot's comment, which folks have found useful.

I had to use:

for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done

because your code created local branches named origin/branchname and I was getting "refname 'origin/branchname' is ambiguous whenever I referred to it.

How to send objects through bundle

One More way to send objects through bundle is by using bundle.putByteArray
Sample code

public class DataBean implements Serializable {
private Date currentTime;

public setDate() {
    currentTime = Calendar.getInstance().getTime();
 }

public Date getCurrentTime() {
    return currentTime;
 }
}

put Object of DataBean in to Bundle:

class FirstClass{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//When you want to start new Activity...
Intent dataIntent =new Intent(FirstClass.this, SecondClass.class);
            Bundle dataBundle=new Bundle();
            DataBean dataObj=new DataBean();
            dataObj.setDate();
            try {
                dataBundle.putByteArray("Obj_byte_array", object2Bytes(dataObj));

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }

            dataIntent.putExtras(dataBundle);

            startActivity(dataIntent);
}

Converting objects to byte arrays

/**
 * Converting objects to byte arrays
 */
static public byte[] object2Bytes( Object o ) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream( baos );
      oos.writeObject( o );
      return baos.toByteArray();
    }

Get Object back from Bundle:

class SecondClass{
DataBean dataBean;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//Get Info from Bundle...
    Bundle infoBundle=getIntent().getExtras();
    try {
        dataBean = (DataBean)bytes2Object(infoBundle.getByteArray("Obj_byte_array"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Method to get objects from byte arrays:

/**
 * Converting byte arrays to objects
 */
static public Object bytes2Object( byte raw[] )
        throws IOException, ClassNotFoundException {
      ByteArrayInputStream bais = new ByteArrayInputStream( raw );
      ObjectInputStream ois = new ObjectInputStream( bais );
      Object o = ois.readObject();
      return o;
    }

Hope this will help to other buddies.

How to print variables without spaces between values

>>> value=42

>>> print "Value is %s"%('"'+str(value)+'"') 

Value is "42"

the MySQL service on local computer started and then stopped

  1. Open Service
  2. Right click on MYSQL service
  3. select Log on
  4. check local system account
  5. start service

Create a folder inside documents folder in iOS apps

Swift 1.2 and iOS 8

Create custom directory (name = "MyCustomData") inside the documents directory but only if the directory does not exist.

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String

// create the custom folder path
let myCustomDataDirectoryPath = documentDirectoryPath.stringByAppendingPathComponent("/MyCustomData")

// check if directory does not exist
if NSFileManager.defaultManager().fileExistsAtPath(myCustomDataDirectoryPath) == false {

    // create the directory
    var createDirectoryError: NSError? = nil
    NSFileManager.defaultManager().createDirectoryAtPath(myCustomDataDirectoryPath, withIntermediateDirectories: false, attributes: nil, error: &createDirectoryError)

    // handle the error, you may call an exception
    if createDirectoryError != nil {
        println("Handle directory creation error...")
    }

}

What is the purpose of willSet and didSet in Swift?

The willSet and didSet observers for the properties whenever the property is assigned a new value. This is true even if the new value is the same as the current value.

And note that willSet needs a parameter name to work around, on the other hand, didSet does not.

The didSet observer is called after the value of property is updated. It compares against the old value. If the total number of steps has increased, a message is printed to indicate how many new steps have been taken. The didSet observer does not provide a custom parameter name for the old value, and the default name of oldValue is used instead.

Convert a String representation of a Dictionary to a dictionary?

string = "{'server1':'value','server2':'value'}"

#Now removing { and }
s = string.replace("{" ,"")
finalstring = s.replace("}" , "")

#Splitting the string based on , we get key value pairs
list = finalstring.split(",")

dictionary ={}
for i in list:
    #Get Key Value pairs separately to store in dictionary
    keyvalue = i.split(":")

    #Replacing the single quotes in the leading.
    m= keyvalue[0].strip('\'')
    m = m.replace("\"", "")
    dictionary[m] = keyvalue[1].strip('"\'')

print dictionary

MySQL equivalent of DECODE function in Oracle

Another MySQL option that may look more like Oracle's DECODE is a combination of FIELD and ELT. In the code that follows, FIELD() returns the argument list position of the string that matches Age. ELT() returns the string from ELTs argument list at the position provided by FIELD(). For example, if Age is 14, FIELD(Age, ...) returns 2 because 14 is the 2nd argument of FIELD (not counting Age). Then, ELT(2, ...) returns 'Fourteen', which is the 2nd argument of ELT (not counting the FIELD() argument). IFNULL returns the default AgeBracket if no match to Age is found in the list.

Select Name, IFNULL(ELT(FIELD(Age,
       13, 14, 15, 16, 17, 18, 19),'Thirteen','Fourteen','Fifteen','Sixteen',
       'Seventeen','Eighteen','Nineteen'),
       'Adult') AS AgeBracket
FROM Person

While I don't think this is the best solution to the question either in terms of performance or readability it is interesting as an exploration of MySQL's string functions. Keep in mind that FIELD's output does not seem to be case sensitive. I.e., FIELD('A','A') and FIELD('a','A') both return 1.

How to stop C# console applications from closing automatically?

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

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

How can I show and hide elements based on selected option with jQuery?

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value

NameError: uninitialized constant (rails)

I had the same error. Turns out in my hasty scaffolding I left out the model.rb file.

gcc/g++: "No such file or directory"

this works for me, sudo apt-get install libx11-dev

How do I raise the same Exception with a custom message in Python?

It seems all the answers are adding info to e.args[0], thereby altering the existing error message. Is there a downside to extending the args tuple instead? I think the possible upside is, you can leave the original error message alone for cases where parsing that string is needed; and you could add multiple elements to the tuple if your custom error handling produced several messages or error codes, for cases where the traceback would be parsed programmatically (like via a system monitoring tool).

## Approach #1, if the exception may not be derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args = (e.args if e.args else tuple()) + ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

or

## Approach #2, if the exception is always derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args += ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

Can you see a downside to this approach?

Mockito How to mock and assert a thrown exception?

I think this should do it for you.

assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..));

Accessing MVC's model property from Javascript

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

Get a file name from a path

Function:

#include <string>

std::string
basename(const std::string &filename)
{
    if (filename.empty()) {
        return {};
    }

    auto len = filename.length();
    auto index = filename.find_last_of("/\\");

    if (index == std::string::npos) {
        return filename;
    }

    if (index + 1 >= len) {

        len--;
        index = filename.substr(0, len).find_last_of("/\\");

        if (len == 0) {
            return filename;
        }

        if (index == 0) {
            return filename.substr(1, len - 1);
        }

        if (index == std::string::npos) {
            return filename.substr(0, len);
        }

        return filename.substr(index + 1, len - index - 1);
    }

    return filename.substr(index + 1, len - index);
}

Tests:

#define CATCH_CONFIG_MAIN
#include <catch/catch.hpp>

TEST_CASE("basename")
{
    CHECK(basename("") == "");
    CHECK(basename("no_path") == "no_path");
    CHECK(basename("with.ext") == "with.ext");
    CHECK(basename("/no_filename/") == "no_filename");
    CHECK(basename("no_filename/") == "no_filename");
    CHECK(basename("/no/filename/") == "filename");
    CHECK(basename("/absolute/file.ext") == "file.ext");
    CHECK(basename("../relative/file.ext") == "file.ext");
    CHECK(basename("/") == "/");
    CHECK(basename("c:\\windows\\path.ext") == "path.ext");
    CHECK(basename("c:\\windows\\no_filename\\") == "no_filename");
}

How to get the indexpath.row when an element is activated?

My approach to this sort of problem is to use a delegate protocol between the cell and the tableview. This allows you to keep the button handler in the cell subclass, which enables you to assign the touch up action handler to the prototype cell in Interface Builder, while still keeping the button handler logic in the view controller.

It also avoids the potentially fragile approach of navigating the view hierarchy or the use of the tag property, which has issues when cells indexes change (as a result of insertion, deletion or reordering)

CellSubclass.swift

protocol CellSubclassDelegate: class {
    func buttonTapped(cell: CellSubclass)
}

class CellSubclass: UITableViewCell {

@IBOutlet var someButton: UIButton!

weak var delegate: CellSubclassDelegate?

override func prepareForReuse() {
    super.prepareForReuse()
    self.delegate = nil
}

@IBAction func someButtonTapped(sender: UIButton) {
    self.delegate?.buttonTapped(self)
}

ViewController.swift

class MyViewController: UIViewController, CellSubclassDelegate {

    @IBOutlet var tableview: UITableView!

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellSubclass

        cell.delegate = self

        // Other cell setup

    } 

    //  MARK: CellSubclassDelegate

    func buttonTapped(cell: CellSubclass) {
        guard let indexPath = self.tableView.indexPathForCell(cell) else {
            // Note, this shouldn't happen - how did the user tap on a button that wasn't on screen?
            return
        }

        //  Do whatever you need to do with the indexPath

        print("Button tapped on row \(indexPath.row)")
    }
} 

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

laravel 5.4 upload image

public function store()
{
    $this->validate(request(), [
        'title' => 'required',
        'slug' => 'required',
        'file' => 'required|image|mimes:jpg,jpeg,png,gif'
    ]);

    $fileName = null;
    if (request()->hasFile('file')) {
        $file = request()->file('file');
        $fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
        $file->move('./uploads/categories/', $fileName);    
    }

    Category::create([
        'title' => request()->get('title'),
        'slug' => str_slug(request()->get('slug')),
        'description' => request()->get('description'),
        'category_img' => $fileName,
        'category_status' => 'DEACTIVE'
    ]);

    return redirect()->to('/admin/category');
}

Python loop to run for certain amount of seconds

Try this:

import time

t_end = time.time() + 60 * 15
while time.time() < t_end:
    # do whatever you do

This will run for 15 min x 60 s = 900 seconds.

Function time.time returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precision. In the beginning the value t_end is calculated to be "now" + 15 minutes. The loop will run until the current time exceeds this preset ending time.

Can I use a binary literal in C or C++?

Just use the standard library in C++:

#include <bitset>

You need a variable of type std::bitset:

std::bitset<8ul> x;
x = std::bitset<8>(10);
for (int i = x.size() - 1; i >= 0; i--) {
      std::cout << x[i];
}

In this example, I stored the binary form of 10 in x.

8ul defines the size of your bits, so 7ul means seven bits and so on.

How do I automatically update a timestamp in PostgreSQL

You'll need to write an insert trigger, and possible an update trigger if you want it to change when the record is changed. This article explains it quite nicely:

http://www.revsys.com/blog/2006/aug/04/automatically-updating-a-timestamp-column-in-postgresql/

CREATE OR REPLACE FUNCTION update_modified_column()   
RETURNS TRIGGER AS $$
BEGIN
    NEW.modified = now();
    RETURN NEW;   
END;
$$ language 'plpgsql';

Apply the trigger like this:

CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON customer FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

How does Tomcat find the HOME PAGE of my Web App?

In any web application, there will be a web.xml in the WEB-INF/ folder.

If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml is under TOMCAT_HOME/conf/web.xml

Either way, the relevant lines of the web.xml are

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

so any file matching this pattern when found will be shown as the home page.

In Tomcat, a web.xml setting within your web app will override the default, if present.

Further Reading

How do I override the default home page loaded by Tomcat?

What does mvn install in maven exactly do

At any stage of maven build life cycle, all the previous goals are performed.

Ex: mvn install will invoke mvn validate, mvn compile, mvn test, mvn package etc.

vertical-align: middle with Bootstrap 2

As well as the previous answers are you could always use the Pull attrib as well:


    <ol class="row" id="possibilities">
       <li class="span6">
         <div class="row">
           <div class="span3">
             <p>some text here</p>
             <p>Text Here too</p>
           </div>
         <figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
        </div>
 </li>
 <li class="span6">
     <div class="row">
         <figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
         <div class="span3">
             <p>Some text</p>
             <p>Some text here too.</p>
         </div>
     </div>
 </li>

How to query a CLOB column in Oracle

Another option is to create a function and call that function everytime you need to select clob column.

create or replace function clob_to_char_func
(clob_column in CLOB,
 for_how_many_bytes in NUMBER,
 from_which_byte in NUMBER)
return VARCHAR2
is
begin
Return substrb(dbms_lob.substr(clob_column
                            ,for_how_many_bytes
                            ,from_which_byte)
            ,1
            ,for_how_many_bytes);
end;

and call that function as;

SELECT tocharvalue, clob_to_char_func(tocharvalue, 1, 9999)
FROM (SELECT clob_column AS tocharvalue FROM table_name);

How to install CocoaPods?

1.First open your terminal

2.Then update your gem file with command

sudo gem install -n /usr/local/bin cocoapods

3.Then give your project path

cd /your project path 

4.Touch the podifle

touch podfile

5.Open your podfile

open -e podfile

6.It will open a podfile like a text edit. Then set your target. For example if you want to set up Google maps then your podfile should be like

use_frameworks!
target 'yourProjectName' do
    pod 'GoogleMaps'
end

7.Then install the pod

pod install

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

This is probably not a solution to your problem, but a suggestion just in case (I know I ran into a similar problem before but not with a .NET application).

If you are on a 64-bit machine, there are 2 regsvr32.exe files; One is in \Windows\System32 and the other one is in \Windows\SysWOW64.

You cannot register 64-bit COM-objects with the 32-bit version, but you can do it vice versa. I'd try registering your DLL with both regsvr32.exe files explicitly (i.e. typing "C:\Windows\System32\regsvr32.exe /i mydll.dll" and then "C:\Windows\SysWOW64\regsvr32.exe /i mydll.dll") and seeing if that helps...

Examples for string find in Python

find( sub[, start[, end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

From the docs.

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

It usually happens because one of the following reasons:

  • Entity Set is mapped from Database view
  • A custom Database query
  • Database table doesn't have a primary key

After doing so, you may still need to update in the Entity Framework designer (or alternatively delete the entity and then add it) before you stop getting the error.

Angular.js How to change an elements css class on click and to remove all others

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

How do I copy the contents of one stream to another?

From .NET 4.5 on, there is the Stream.CopyToAsync method

input.CopyToAsync(output);

This will return a Task that can be continued on when completed, like so:

await input.CopyToAsync(output)

// Code from here on will be run in a continuation.

Note that depending on where the call to CopyToAsync is made, the code that follows may or may not continue on the same thread that called it.

The SynchronizationContext that was captured when calling await will determine what thread the continuation will be executed on.

Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).

From .NET 4.0 on, there's is the Stream.CopyTo method

input.CopyTo(output);

For .NET 3.5 and before

There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length? Because that Length may not be available! From the docs:

If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.

Python, how to check if a result set is empty?

if you're connecting to a postgres database, the following works:

result = cursor.execute(query)

if result.returns_rows:
    # we got rows!
    return [{k:v for k,v in zip(result.keys(), r)} for r in result.rows]
else:
    return None

What key shortcuts are to comment and uncomment code?

"commentLine" is the name of function you are looking for. This function coment and uncoment with the same keybinding

What is a NullPointerException, and how do I fix it?

A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception.

In general, it's because something hasn't been initialized properly.

How do I manage conflicts with git submodules?

Well In my parent directory I see:

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Unmerged paths:
(use "git reset HEAD <file>..." to unstage)
(use "git add <file>..." to mark resolution)

So I just did this

git reset HEAD linux

VSCode regex find & replace submatch math?

In my case $1 was not working, but $0 works fine for my purpose.

In this case I was trying to replace strings with the correct format to translate them in Laravel, I hope this could be useful to someone else because it took me a while to sort it out!

Search: (?<=<div>).*?(?=</div>)
Replace: {{ __('$0') }}

Regex Replace String for Laravel Translation

Permutation of array

Implementation via recursion (dynamic programming), in Java, with test case (TestNG).


Code

PrintPermutation.java

import java.util.Arrays;

/**
 * Print permutation of n elements.
 * 
 * @author eric
 * @date Oct 13, 2018 12:28:10 PM
 */
public class PrintPermutation {
    /**
     * Print permutation of array elements.
     * 
     * @param arr
     * @return count of permutation,
     */
    public static int permutation(int arr[]) {
        return permutation(arr, 0);
    }

    /**
     * Print permutation of part of array elements.
     * 
     * @param arr
     * @param n
     *            start index in array,
     * @return count of permutation,
     */
    private static int permutation(int arr[], int n) {
        int counter = 0;
        for (int i = n; i < arr.length; i++) {
            swapArrEle(arr, i, n);
            counter += permutation(arr, n + 1);
            swapArrEle(arr, n, i);
        }
        if (n == arr.length - 1) {
            counter++;
            System.out.println(Arrays.toString(arr));
        }

        return counter;
    }

    /**
     * swap 2 elements in array,
     * 
     * @param arr
     * @param i
     * @param k
     */
    private static void swapArrEle(int arr[], int i, int k) {
        int tmp = arr[i];
        arr[i] = arr[k];
        arr[k] = tmp;
    }
}

PrintPermutationTest.java (test case via TestNG)

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * PrintPermutation test.
 * 
 * @author eric
 * @date Oct 14, 2018 3:02:23 AM
 */
public class PrintPermutationTest {
    @Test
    public void test() {
        int arr[] = new int[] { 0, 1, 2, 3 };
        Assert.assertEquals(PrintPermutation.permutation(arr), 24);

        int arrSingle[] = new int[] { 0 };
        Assert.assertEquals(PrintPermutation.permutation(arrSingle), 1);

        int arrEmpty[] = new int[] {};
        Assert.assertEquals(PrintPermutation.permutation(arrEmpty), 0);
    }
}

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

How to debug stored procedures with print statements?

Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.

Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.

  • For even more opinions/observations focus your attention on this SO post here.
  • Specifically look at this answer of the same post by Phil_factor (Ha ha! Love the SQL humor)
  • Regarding the suggestion of using RAISERROR WITH NOWAIT look at this answer of the same post by JimCarden

Don't do these things

  1. Some people are under the impression that they can just use a GO statement after their PRINT statement, but you CANNOT use the GO statement INSIDE of a sproc. So that solution is out.
  2. I don't recommend SELECT-ing your print statements because it is just going to muddy your result set with nonsense and if your sproc is supposed to be consumed by a program later, then you will have to know which result sets to skip when looping through the results from your data reader. This is just a bad idea, so don't do it.
  3. Another problem with SELECT-ING your print statements is that they don't always show up immediately. I have had different experiences with this for different executions, so don't expect any kind of consistency with this methodology.

Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...

It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
    SET NOCOUNT ON;

    -- This will print immediately
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    -- Five second delay to simulate lengthy execution
    WAITFOR DELAY '00:00:05'

    -- This will print after the five second delay
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample]

Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.

Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
    SET NOCOUNT ON;

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P Start';
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    WAITFOR DELAY '00:00:05'

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P End'
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample2]

Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.

How to truncate float values?

You can do:

def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

testing:

>>> f=1.923328437452
>>> [truncate(f, n) for n in range(5)]
[1.0, 1.9, 1.92, 1.923, 1.9233]

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

Set new id with jQuery

What happens when you set all of the attributes in one attr() command like so

$(this).attr({
               id : this.id + '_' + new_id,
               name: this.name + '_' + new_id,
               value: 'test' 
             });

How to loop through a plain JavaScript object with the objects as members?

In ES7 you can do:

for (const [key, value] of Object.entries(obj)) {
  //
}

How to run an .ipynb Jupyter Notebook from terminal?

You can also use the boar package to run your notebook within a python code.

from boar.running import run_notebook

outputs = run_notebook("nb.ipynb")

If you update your notebook, you won't have to convert it again to a python file.


More information at:

https://github.com/alexandreCameron/boar/blob/master/USAGE.md

Append a single character to a string or char array in java?

just add them like this :

        String character = "a";
        String otherString = "helen";
        otherString=otherString+character;
        System.out.println(otherString);

What are all the different ways to create an object in Java?

There are various ways:

  • Through Class.newInstance.
  • Through Constructor.newInstance.
  • Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
  • Through Object.clone (does not call a constructor).
  • Through JNI (should call a constructor).
  • Through any other method that calls a new for you.
  • I guess you could describe class loading as creating new objects (such as interned Strings).
  • A literal array as part of the initialisation in a declaration (no constructor for arrays).
  • The array in a "varargs" (...) method call (no constructor for arrays).
  • Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
  • Causing an exception to be created and thrown by the runtime. For instance throw null; or "".toCharArray()[0].
  • Oh, and boxing of primitives (unless cached), of course.
  • JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
  • For completeness (and Paulo Ebermann), there's some syntax with the new keyword as well.

How to display the current time and date in C#

DateTime.Now.Tostring();

. You can supply parameters to To string function in a lot of ways like given in this link http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

This will be a lot useful. If you reside somewhere else than the regular format (MM/dd/yyyy)

use always MM not mm, mm gives minutes and MM gives month.

gdb fails with "Unable to find Mach task port for process-id" error

The problem is that you are not logged in as a root user (which you don't want). You need to create a certificate for gdb to be allowed access. Follow this tutorial and you should be good to go...

http://sourceware.org/gdb/wiki/BuildingOnDarwin

If all else fails, just use: sudo gdb executableFileName

MySQL set current date in a DATETIME field on insert

Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.

See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html

How to generate List<String> from SQL query?

Or a nested List (okay, the OP was for a single column and this is for multiple columns..):

        //Base list is a list of fields, ie a data record
        //Enclosing list is then a list of those records, ie the Result set
        List<List<String>> ResultSet = new List<List<String>>();

        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(qString, connection);

            // Create and execute the DataReader..
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var rec = new List<string>();
                for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                {                      
                    rec.Add(reader.GetString(i));
                }
                ResultSet.Add(rec);

            }
        }

How to use a variable for a key in a JavaScript object literal?

2020 update/example...

A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so

[ ` ... ` ]

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}

How can I add a hint text to WPF textbox?

I accomplish this with a VisualBrush and some triggers in a Style suggested by :sellmeadog.

<TextBox>
        <TextBox.Style>
            <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
                <Style.Resources>
                    <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
                        <VisualBrush.Visual>
                            <Label Content="Search" Foreground="LightGray" />
                        </VisualBrush.Visual>
                    </VisualBrush>
                </Style.Resources>
                <Style.Triggers>
                    <Trigger Property="Text" Value="{x:Static sys:String.Empty}">
                        <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                    </Trigger>
                    <Trigger Property="Text" Value="{x:Null}">
                        <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                    </Trigger>
                    <Trigger Property="IsKeyboardFocused" Value="True">
                        <Setter Property="Background" Value="White" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

@sellmeadog :Application running, bt Design not loading...the following Error comes: Ambiguous type reference. A type named 'StaticExtension' occurs in at least two namespaces, 'MS.Internal.Metadata.ExposedTypes.Xaml' and 'System.Windows.Markup'. Consider adjusting the assembly XmlnsDefinition attributes. 'm using .net 3.5

Regarding C++ Include another class

When you want to convert your code to result( executable, library or whatever ), there is 2 steps:
1) compile
2) link
In first step compiler should now about some things like sizeof objects that used by you, prototype of functions and maybe inheritance. on the other hand linker want to find implementation of functions and global variables in your code.

Now when you use ClassTwo in File1.cpp compiler know nothing about it and don't know how much memory should allocate for it or for example witch members it have or is it a class and enum or even a typedef of int, so compilation will be failed by the compiler. adding File2.cpp solve the problem of linker that look for implementation but the compiler is still unhappy, because it know nothing about your type.

So remember, in compile phase you always work with just one file( and of course files that included by that one file ) and in link phase you need multiple files that contain implementations. and since C/C++ are statically typed and they allow their identifier to work for many purposes( definition, typedef, enum class, ... ) so you should always identify you identifier to the compiler and then use it and as a rule compiler should always know size of your variable!!

Is there any way to configure multiple registries in a single npmrc file

My approach was to make a slight command line variant that adds the registry switch.

I created these files in the nodejs folder where the npm executable is found:

npm-.cmd:

@ECHO OFF
npm --registry https://registry.npmjs.org %*

npm-:

#!/bin/sh
"npm" --registry https://registry.npmjs.org "$@"

Now, if I want to do an operation against the normal npm registry (while I am not connected to the VPN), I just type npm- where I would usually type npm.

To test this command and see the registry for a package, use this example:

npm- view lodash

PS. I am in windows and have tested this in Bash, CMD, and Powershell. I also

SELECT FOR UPDATE with SQL Server

Have you tried READPAST?

I've used UPDLOCK and READPAST together when treating a table like a queue.

How to change line width in ggplot?

Whilst @Didzis has the correct answer, I will expand on a few points

Aesthetics can be set or mapped within a ggplot call.

  • An aesthetic defined within aes(...) is mapped from the data, and a legend created.

  • An aesthetic may also be set to a single value, by defining it outside aes().

As far as I can tell, what you want is to set size to a single value, not map within the call to aes()

When you call aes(size = 2) it creates a variable called `2` and uses that to create the size, mapping it from a constant value as it is within a call to aes (thus it appears in your legend).

Using size = 1 (and without reg_labeller which is perhaps defined somewhere in your script)

Figure29 +
    geom_line(aes(group=factor(tradlib)),size=1) +
    facet_grid(regionsFull~., scales="free_y") +
    scale_colour_brewer(type = "div") +
    theme(axis.text.x = element_text(
          colour = 'black', angle = 90, size = 13,
          hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
    ylab("FSI (%Change)") +
    theme(axis.text.y = element_text(colour = 'black', size = 12), 
          axis.title.y = element_text(size = 12, 
          hjust = 0.5, vjust = 0.2)) + 
    theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust =    0.5, face = 'bold'))

enter image description here

and with size = 2

 Figure29 + 
     geom_line(aes(group=factor(tradlib)),size=2) +
     facet_grid(regionsFull~., scales="free_y") + 
     scale_colour_brewer(type = "div") +
     theme(axis.text.x = element_text(colour = 'black', angle = 90,
          size = 13, hjust = 0.5, vjust = 
          0.5),axis.title.x=element_blank()) + 
     ylab("FSI (%Change)") +
     theme(axis.text.y = element_text(colour = 'black', size = 12),
          axis.title.y = element_text(size = 12,
          hjust = 0.5, vjust = 0.2)) + 
      theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust = 0.5, face = 'bold'))

enter image description here

You can now define the size to work appropriately with the final image size and device type.

Slack URL to open a channel from browser

When I tried yorammi's solution I was taken to Slack, but not the channel I specified.

I had better luck with:

https://<organization>.slack.com/messages/#<channel>/

and

https://<organization>.slack.com/messages/<channel>/details/

Although, they were both still displayed in a browser window and not the app.

How can I wrap text in a label using WPF?

You can put a TextBlock inside the label:

<Label> 
  <TextBlock Text="Long Text . . . ." TextWrapping="Wrap" /> 
</Label> 

jQuery: enabling/disabling datepicker

This is what worked for me

$("#from").attr("disabled", true);

How to work with string fields in a C struct?

This does not work:

string s = (string)malloc(sizeof string); 

string refers to a pointer, you need the size of the structure itself:

string s = malloc(sizeof (*string)); 

Note the lack of cast as well (conversion from void* (malloc's return type) is implicitly performed).

Also, in your main, you have a globally delcared patient, but that is uninitialized. Try:

 patient.number = 3;     
 patient.name = "John";     
 patient.address = "Baker street";     
 patient.birthdate = "4/15/2012";     
 patient.gender = 'M';     

before you read-access any of its members

Also, strcpy is inherently unsafe as it does not have boundary checking (will copy until the first '\0' is encountered, writing past allocated memory if the source is too long). Use strncpy instead, where you can at least specify the maximum number of characters copied -- read the documentation to ensure you pass the correct value, it is easy to make an off-by-one error.

HTML-Tooltip position relative to mouse pointer

For default tooltip behavior simply add the title attribute. This can't contain images though.

<div title="regular tooltip">Hover me</div>

Before you clarified the question I did this up in pure JavaScript, hope you find it useful. The image will pop up and follow the mouse.

jsFiddle

JavaScript

var tooltipSpan = document.getElementById('tooltip-span');

window.onmousemove = function (e) {
    var x = e.clientX,
        y = e.clientY;
    tooltipSpan.style.top = (y + 20) + 'px';
    tooltipSpan.style.left = (x + 20) + 'px';
};

CSS

.tooltip span {
    display:none;
}
.tooltip:hover span {
    display:block;
    position:fixed;
    overflow:hidden;
}

Extending for multiple elements

One solution for multiple elements is to update all tooltip span's and setting them under the cursor on mouse move.

jsFiddle

var tooltips = document.querySelectorAll('.tooltip span');

window.onmousemove = function (e) {
    var x = (e.clientX + 20) + 'px',
        y = (e.clientY + 20) + 'px';
    for (var i = 0; i < tooltips.length; i++) {
        tooltips[i].style.top = y;
        tooltips[i].style.left = x;
    }
};

check if variable empty

Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following

if (!empty($var) && is_null($var))

Note the PHP manual

variable is considered empty if it does not exist or if its value equals FALSE

As opposed to being null which is handy here!

What is the difference between pull and clone in git?

Hmm, what's missing to see the remote branch "4.2" when I pull, as I do when I clone? Something's clearly not identical.

tmp$  mkdir some_repo

tmp$  cd some_repo

some_repo$  git init
Initialized empty Git repository in /tmp/some_repo/.git/

some_repo$  git pull https://github.ourplace.net/babelfish/some_repo.git
  :
From https://github.ourplace.net/babelfish/some_repo
 * branch            HEAD       -> FETCH_HEAD

some_repo$  git branch
* master

vs

tmp$  rm -rf some_repo

tmp$  git clone https://github.ourplace.net/babelfish/some_repo.git
Cloning into 'some_repo'...
  :
Checking connectivity... done.

tmp$  cd some_repo

some_repo$  git branch
* 4.2

scp or sftp copy multiple files with single command

In the specific case where all the files have the same extension but with different suffix (say number of log file) you use the following:

scp [email protected]:/some/log/folder/some_log_file.* ./

This will copy all files named some_log_file from the given folder within the remote, i.e.- some_log_file.1 , some_log_file.2, some_log_file.3 ....

How to change the color of text in javafx TextField?

The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.

.text-input {
    -fx-text-fill: -fx-text-inner-color;
    -fx-highlight-fill: derive(-fx-control-inner-background,-20%);
    -fx-highlight-text-fill: -fx-text-inner-color;
    -fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
    -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: 0, 1;
    -fx-background-radius: 3, 2;
    -fx-cursor: text;
    -fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
    -fx-highlight-fill: -fx-accent;
    -fx-highlight-text-fill: white;
    -fx-background-color: 
        -fx-focus-color,
        -fx-control-inner-background,
        -fx-faint-focus-color,
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: -0.2, 1, -1.4, 3;
    -fx-background-radius: 3, 2, 4, 0;
    -fx-prompt-text-fill: transparent;
}

Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:

textField.setStyle("-fx-text-inner-color: red;");

Best timestamp format for CSV/Excel?

I believe if you used the double data type, the re-calculation in Excel would work just fine.

Align <div> elements side by side

Apply float:left; to both of your divs should make them stand side by side.

Browse and display files in a git repo without cloning

This is probably considered dirty by some, but a very practical solution in case of github repositories is just to make a script, e.g. "git-ls":

#!/bin/sh
remote_url=${1:? "$0 requires URL as argument"}
curl -s $remote_url | grep js-directory-link | sed "s/.* title=\"\(.*\)\".*/\1/"

Make it executable and reachable of course: chmod a+x git-ls; sudo cp git-ls /usr/local/bin. Now, you just run it as you wish:

git-ls https://github.com/mrquincle/aim-bzr
git-ls https://github.com/mrquincle/aim-bzr/tree/master/aim_modules

Also know that there is a git instaweb utility for your local files. To have the ability to show files and have a server like that does in my opinion not destroy any of the inherent decentralized characteristics of git.

How to put a jar in classpath in Eclipse?

In your Android Developer Tools , From the SDK Manager, install Extras > Google Cloud Messaging for Android Library . After the installation is complete restart your SDK.Then navigate to sdk\extras\google\gcm\gcm-client\dist . there will be your gcm.jar file.

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

I am on Ubuntu 18.04 and got the same error, was worried for weeks too. Finally realized that gpg2 is not pointing towards anything. So simply run

git config --global gpg.program gpg

And tada, it works like charm.

Signed commit

Your commits will now have verified tag with them.

Difference between Mutable objects and Immutable objects

Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.

For example:(Point is mutable and string immutable)

     Point myPoint = new Point( 0, 0 );
    System.out.println( myPoint );
    myPoint.setLocation( 1.0, 0.0 );
    System.out.println( myPoint );

    String myString = new String( "old String" );
    System.out.println( myString );
    myString.replaceAll( "old", "new" );
    System.out.println( myString );

The output is:

java.awt.Point[0.0, 0.0]
java.awt.Point[1.0, 0.0]
old String
old String

How to get the data-id attribute?

Try

this.dataset.id

_x000D_
_x000D_
$("#list li").on('click', function() {_x000D_
  alert( this.dataset.id );_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>_x000D_
_x000D_
<ul id="list" class="grid">_x000D_
  <li data-id="id-40" class="win">_x000D_
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">_x000D_
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />_x000D_
    </a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Binding to static property

You can't bind to a static like that. There's no way for the binding infrastructure to get notified of updates since there's no DependencyObject (or object instance that implement INotifyPropertyChanged) involved.

If that value doesn't change, just ditch the binding and use x:Static directly inside the Text property. Define app below to be the namespace (and assembly) location of the VersionManager class.

<TextBox Text="{x:Static app:VersionManager.FilterString}" />

If the value does change, I'd suggest creating a singleton to contain the value and bind to that.

An example of the singleton:

public class VersionManager : DependencyObject {
    public static readonly DependencyProperty FilterStringProperty =
        DependencyProperty.Register( "FilterString", typeof( string ),
        typeof( VersionManager ), new UIPropertyMetadata( "no version!" ) );
    public string FilterString {
        get { return (string) GetValue( FilterStringProperty ); }
        set { SetValue( FilterStringProperty, value ); }
    }

    public static VersionManager Instance { get; private set; }

    static VersionManager() {
        Instance = new VersionManager();
    }
}
<TextBox Text="{Binding Source={x:Static local:VersionManager.Instance},
                        Path=FilterString}"/>

How to access elements of a JArray (or iterate over them)

Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.

var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));

Simple way to create matrix of random numbers

First, create numpy array then convert it into matrix. See the code below:

import numpy

B = numpy.random.random((3, 4)) #its ndArray
C = numpy.matrix(B)# it is matrix
print(type(B))
print(type(C)) 
print(C)

How to call a function from another controller in angularjs?

If the two controller is nested in One controller.
Then you can simply call:

$scope.parentmethod();  

Angular will search for parentmethod function starting with current scope and up until it will reach the rootScope.

what is the use of Eval() in asp.net

While binding a databound control, you can evaluate a field of the row in your data source with eval() function.

For example you can add a column to your gridview like that :

<asp:BoundField DataField="YourFieldName" />

And alternatively, this is the way with eval :

<asp:TemplateField>
<ItemTemplate>
        <asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
        </asp:Label>
</ItemTemplate>
</asp:TemplateField>

It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :

<asp:TemplateField>
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" 
          NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>' 
          Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

How to create windows service from java jar?

The easiest solution I found for this so far is the Non-Sucking Service Manager

Usage would be

nssm install <servicename> "C:\Program Files\Java\jre7\java.exe" "-jar <path-to-jar-file>"

Spring MVC - How to return simple String as JSON in Rest Controller

In one project we addressed this using JSONObject (maven dependency info). We chose this because we preferred returning a simple String rather than a wrapper object. An internal helper class could easily be used instead if you don't want to add a new dependency.

Example Usage:

@RestController
public class TestController
{
    @RequestMapping("/getString")
    public String getString()
    {
        return JSONObject.quote("Hello World");
    }
}

Can't change z-index with JQuery

because your jQuery code is wrong. Correctly would be:

var theParent = $(this).parent().get(0); 
$(theParent).css('z-index', 3000);

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

The warning comes up because Tomcat scans all Jars for TLDs (Tagging Library Definitions).

Step1: To see which JARs are throwing up this warning, insert he following line to tomcat/conf/logging.properties

org.apache.jasper.servlet.TldScanner.level = FINE

Now you should be able to see warnings with a detail of which JARs are causing the intial warning

Step2 Since skipping unneeded JARs during scanning can improve startup time and JSP compilation time, we will skip un-needed JARS in the catalina.properties file. You have two options here -

  1. List all the JARs under the tomcat.util.scan.StandardJarScanFilter.jarsToSkip. But this can get cumbersome if you have a lot jars or if the jars keep changing.
  2. Alternatively, Insert tomcat.util.scan.StandardJarScanFilter.jarsToSkip=* to skip all the jars

You should now not see the above warnings and if you have a considerably large application, it should save you significant time in deploying an application.

Note: Tested in Tomcat8

Android emulator: How to monitor network traffic?

You can use http://docs.mitmproxy.org/en/stable/install.html

Its easy to setup and won't require any extra tweaks.

I go through various tool but found it to be really good and easy.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.

Here's how I'm doing it for a long time, very successfully:

  1. Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).

  2. Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that (see FileStorm link at the bottom for a good tool). The background image is usually an image we put into a hidden folder (".something") on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).

  3. Unmount the DMG again, all settings should be stored by now.

  4. Write a create DMG script, that works as follows:

    • It copies the DMG, so the original one is never touched again.
    • It mounts the copy.
    • It replaces all files with the most up to date ones (e.g. latest app after build). You can simply use mv or ditto for that on command line. Note, when you replace a file like that, the icon will stay the same, the position will stay the same, everything but the file (or directory) content stays the same (at least with ditto, which we usually use for that task). You can of course also replace the background image with another one (just make sure it has the same dimensions).
    • After replacing the files, make the script unmount the DMG copy again.
    • Finally call hdiutil to convert the writable, to a compressed (and such not writable) DMG.

This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named "Create DMG") and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).

Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a relase DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).

Regarding the initial layout of the template, FileStorm is a good tool for doing it. It is commercial, but very powerful and easy to use. The normal version is less than $20, so it is really affordable. Maybe one can automate FileStorm to create a DMG (e.g. via AppleScript), never tried that, but once you have found the perfect template DMG, it's really easy to update it for every release.

How to generate unique id in MySQL?

How you generate the unique_ids is a useful question - but you seem to be making a counter productive assumption about when you generate them!

My point is that you do not need to generate these unique id's at the time of creating your rows, because they are essentially independent of the data being inserted.

What I do is pre-generate unique id's for future use, that way I can take my own sweet time and absolutely guarantee they are unique, and there's no processing to be done at the time of the insert.

For example I have an orders table with order_id in it. This id is generated on the fly when the user enters the order, incrementally 1,2,3 etc forever. The user does not need to see this internal id.

Then I have another table - unique_ids with (order_id, unique_id). I have a routine that runs every night which pre-loads this table with enough unique_id rows to more than cover the orders that might be inserted in the next 24 hours. (If I ever get 10000 orders in one day I'll have a problem - but that would be a good problem to have!)

This approach guarantees uniqueness and takes any processing load away from the insert transaction and into the batch routine, where it does not affect the user.

executing shell command in background from script

Building off of ngoozeff's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:

cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
  • &>/dev/null sets the command’s stdout and stderr to /dev/null instead of inheriting them from the parent process.
  • & makes the shell run the command in the background.
  • disown removes the “current” job, last one stopped or put in the background, from under the shell’s job control.

In some shells you can also use &! instead of & disown; they both have the same effect. Bash doesn’t support &!, though.

Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}" rather than "${cmd}":

cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;

If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.

Here's a function for it:

#!/bin/bash

# Run a command in the background.
_evalBg() {
    eval "$@" &>/dev/null & disown;
}

cmd="google-chrome";
_evalBg "${cmd}";

Also, see: Running bash commands in the background properly

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

Convert pyspark string to date format

Update (1/10/2018):

For Spark 2.2+ the best way to do this is probably using the to_date or to_timestamp functions, which both support the format argument. From the docs:

>>> from pyspark.sql.functions import to_timestamp
>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])
>>> df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect()
[Row(dt=datetime.datetime(1997, 2, 28, 10, 30))]

Original Answer (for Spark < 2.2)

It is possible (preferrable?) to do this without a udf:

from pyspark.sql.functions import unix_timestamp, from_unixtime

df = spark.createDataFrame(
    [("11/25/1991",), ("11/24/1991",), ("11/30/1991",)], 
    ['date_str']
)

df2 = df.select(
    'date_str', 
    from_unixtime(unix_timestamp('date_str', 'MM/dd/yyy')).alias('date')
)

print(df2)
#DataFrame[date_str: string, date: timestamp]

df2.show(truncate=False)
#+----------+-------------------+
#|date_str  |date               |
#+----------+-------------------+
#|11/25/1991|1991-11-25 00:00:00|
#|11/24/1991|1991-11-24 00:00:00|
#|11/30/1991|1991-11-30 00:00:00|
#+----------+-------------------+

For div to extend full height

Did you remember setting the height of the html and body tags in your CSS? This is generally how I've gotten DIVs to extend to full height:


<html>
  <head>
    <style type="text/css">

      html,body { height: 100%; margin: 0px; padding: 0px; }
      #full { background: #0f0; height: 100% }

    </style>
  </head>
  <body>
    <div id="full">
    </div>
  </body>
</html>



Is it possible to opt-out of dark mode on iOS 13?

First, here is Apple's entry related to opting out of dark mode. The content at this link is written for Xcode 11 & iOS 13:

This section applies to Xcode 11 usage


If you wish to opt out your ENTIRE application

Approach #1

Use the following key in your info.plist file:

UIUserInterfaceStyle

And assign it a value of Light.

The XML for the UIUserInterfaceStyle assignment:

<key>UIUserInterfaceStyle</key>
<string>Light</string>

Approach #2

You can set overrideUserInterfaceStyle against the app's window variable.

Depending on how your project was created, this may be in the AppDelegate file or the SceneDelegate.

if #available(iOS 13.0, *) {
    window?.overrideUserInterfaceStyle = .light
}


If you wish to opt out your UIViewController on an individual basis

override func viewDidLoad() {
    super.viewDidLoad()
    // overrideUserInterfaceStyle is available with iOS 13
    if #available(iOS 13.0, *) {
        // Always adopt a light interface style.
        overrideUserInterfaceStyle = .light
    }
}

Apple documentation for overrideUserInterfaceStyle

How the above code will look in Xcode 11:

enter image description here

This section applies to Xcode 10.x usage


If you are using Xcode 11 for your submission, you can safely ignore everything below this line.

Since the relevant API does not exist in iOS 12, you will get errors when attempting to use the values provided above:

For setting overrideUserInterfaceStyle in your UIViewController

enter image description here

If you wish to opt out your UIViewController on an individual basis

This can be handled in Xcode 10 by testing the compiler version and the iOS version:

#if compiler(>=5.1)
if #available(iOS 13.0, *) {
    // Always adopt a light interface style.
    overrideUserInterfaceStyle = .light
}
#endif

If you wish to opt out your ENTIRE application

You can modify the above snippet to work against the entire application for Xcode 10, by adding the following code to your AppDelegate file.

#if compiler(>=5.1)
if #available(iOS 13.0, *) {
    // Always adopt a light interface style.
    window?.overrideUserInterfaceStyle = .light
}
#endif

However, the plist setting will fail when using Xcode version 10.x:

enter image description here

Credit to @Aron Nelson, @Raimundas Sakalauskas, @NSLeader and rmaddy for improving this answer with their feedback.

Accessing JSON elements

import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']

What you get from the url is a json string. And your can't parse it with index directly. You should convert it to a dict by json.loads and then you can parse it with index.

Instead of using .read() to intermediately save it to memory and then read it to json, allow json to load it directly from the file:

wjdata = json.load(urllib2.urlopen('url'))

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.

Blowfish();

Could not find a version that satisfies the requirement tensorflow

As of October 2020:

  • Tensorflow only supports the 64-bit version of Python

  • Tensorflow only supports Python 3.5 to 3.8

So, if you're using an out-of-range version of Python (older or newer) or a 32-bit version, then you'll need to use a different version.

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

How do I get the APK of an installed app without root access?

When you have Eclipse for Android developement installed:

  • Use your device as debugging device. On your phone: Settings > Applications > Development and enable USB debugging, see http://developer.android.com/tools/device.html
  • In Eclipse, open DDMS-window: Window > Open Perspective > Other... > DDMS, see http://developer.android.com/tools/debugging/ddms.html
  • If you can't see your device try (re)installing USB-Driver for your device
  • In middle pane select tab "File Explorer" and go to system > app
  • Now you can select one or more files and then click the "Pull a file from the device" icon at the top (right to the tabs)
  • Select target folder - tada!

How to get a time zone from a location using latitude and longitude coordinates?

For those of us using Javascript and looking to get a timezone from a zip code via Google APIs, here is one method.

  1. Fetch the lat/lng via geolocation
  2. fetch the timezone by pass that into the timezone API.
    • Using Luxon here for timezone conversion.

Note: my understanding is that zipcodes are not unique across countries, so this is likely best suited for use in the USA.

const googleMapsClient; // instantiate your client here
const zipcode = '90210'
const myDateThatNeedsTZAdjustment; // define your date that needs adjusting
// fetch lat/lng from google api by zipcode
const geocodeResponse = await googleMapsClient.geocode({ address: zipcode }).asPromise();
if (geocodeResponse.json.status === 'OK') {
  lat = geocodeResponse.json.results[0].geometry.location.lat;
  lng = geocodeResponse.json.results[0].geometry.location.lng;
} else {
  console.log('Geocode was not successful for the following reason: ' + status);
}

// prepare lat/lng and timestamp of profile created_at to fetch time zone
const location = `${lat},${lng}`;
const timestamp = new Date().valueOf() / 1000;
const timezoneResponse = await googleMapsClient
  .timezone({ location: location, timestamp: timestamp })
  .asPromise();

const timeZoneId = timezoneResponse.json.timeZoneId;
// adjust by setting timezone
const timezoneAdjustedDate = DateTime.fromJSDate(
  myDateThatNeedsTZAdjustment
).setZone(timeZoneId);

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

There's a bit of confusion in your question:

  • a Date datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE into a Date.
  • When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the TO_CHAR function. In Oracle, a Date has no format: it is a point in time.
  • Reciprocally, you would use TO_TIMESTAMP_TZ to convert a VARCHAR2 to a TIMESTAMP, but this won't convert a Date to a TIMESTAMP.
  • You use FROM_TZ to add the time zone information to a TIMESTAMP (or a Date).
  • In Oracle, CST is a time zone but CDT is not. CDT is a daylight saving information.
  • To complicate things further, CST/CDT (-05:00) and CST/CST (-06:00) will have different values obviously, but the time zone CST will inherit the daylight saving information depending upon the date by default.

So your conversion may not be as simple as it looks.

Assuming that you want to convert a Date d that you know is valid at time zone CST/CST to the equivalent at time zone CST/CDT, you would use:

SQL> SELECT from_tz(d, '-06:00') initial_ts,
  2         from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
  3    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  4                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  5            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00

My default timestamp format has been used here. I can specify a format explicitely:

SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
  2         to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
  3                 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
  4    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  5                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  6            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00      2012-10-09 02:10:21 -05:00

How to save CSS changes of Styles panel of Chrome Developer Tools?

As long as you haven't been sticking the CSS in element.style:

  1. Go to a style you have added. There should be a link saying inspector-stylesheet:

enter image description here

  1. Click on that, and it will open up all the CSS that you have added in the sources panel

  2. Copy and paste it - yay!

If you have been using element.style:

You can just right-click on your HTML element, click Edit as HTML and then copy and paste the HTML with the inline styles.

How to compare two maps by their values

If you assume that there can be duplicate values the only way to do this is to put the values in lists, sort them and compare the lists viz:

List<String> values1 = new ArrayList<String>(map1.values());
List<String> values2 = new ArrayList<String>(map2.values());
Collections.sort(values1);
Collections.sort(values2);
boolean mapsHaveEqualValues = values1.equals(values2);

If values cannot contain duplicate values then you can either do the above without the sort using sets.

Hash and salt passwords in C#

I read all answers and I think those enough, specially @Michael articles with slow hashing and @CodesInChaos good comments, but I decided to share my code snippet for hashing/validating that may be useful and it does not require [Microsoft.AspNet.Cryptography.KeyDerivation].

    private static bool SlowEquals(byte[] a, byte[] b)
            {
                uint diff = (uint)a.Length ^ (uint)b.Length;
                for (int i = 0; i < a.Length && i < b.Length; i++)
                    diff |= (uint)(a[i] ^ b[i]);
                return diff == 0;
            }

    private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes)
            {
                Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
                pbkdf2.IterationCount = iterations;
                return pbkdf2.GetBytes(outputBytes);
            }

    private static string CreateHash(string value, int salt_bytes, int hash_bytes, int pbkdf2_iterations)
            {
                // Generate a random salt
                RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
                byte[] salt = new byte[salt_bytes];
                csprng.GetBytes(salt);

                // Hash the value and encode the parameters
                byte[] hash = PBKDF2(value, salt, pbkdf2_iterations, hash_bytes);

                //You need to return the salt value too for the validation process
                return Convert.ToBase64String(hash) + ":" + 
                       Convert.ToBase64String(hash);
            }

    private static bool ValidateHash(string pureVal, string saltVal, string hashVal, int pbkdf2_iterations)
            {
                try
                {
                    byte[] salt = Convert.FromBase64String(saltVal);
                    byte[] hash = Convert.FromBase64String(hashVal);

                    byte[] testHash = PBKDF2(pureVal, salt, pbkdf2_iterations, hash.Length);
                    return SlowEquals(hash, testHash);
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

Please pay attention SlowEquals function that is so important, Finally, I hope this help and Please don't hesitate to advise me about better approaches.

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

Inserting string at position x of another string

Maybe it's even better if you determine position using indexOf() like this:

function insertString(a, b, at)
{
    var position = a.indexOf(at); 

    if (position !== -1)
    {
        return a.substr(0, position) + b + a.substr(position);    
    }  

    return "substring not found";
}

then call the function like this:

insertString("I want apple", "an ", "apple");

Note, that I put a space after the "an " in the function call, rather than in the return statement.

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Limited disk space can cause to this error.

Check your disk space

$ df -h

Try to increase the space if there are 100% used disks.

In my case: I have Vagrant (8.0.1) box (Ubuntu 16.04) My mysql disk capacity was 10GB, I increased it to 20GB

$ sudo lvextend -L20G -r /dev/mapper/homestead--vg-mysql--master

Then restart mysql

$ sudo service mysql restart

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

EOFException - how to handle?

You can use while(in.available() != 0) instead of while(true).

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

Using angular-google-maps

$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
    $scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};    
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());

How to load a UIView using a nib file created with Interface Builder

I had reason to do the same thing (programmatically loading a view from a XIB file), but I needed to do this entirely from the context of a subclass of a subclass of a UIView (i.e. without involving the view controller in any way). To do this I created this utility method:

+ (id) initWithNibName:(NSString *)nibName withSelf:(id)myself {

    NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:nibName
                                                    owner:myself options:nil];
    for (id object in bundle) {
        if ([object isKindOfClass:[myself class]]) {
            return object;
        }
    }  

    return nil;
} 

Then I call it from my subclass' initWithFrame method like so:

- (id)initWithFrame:(CGRect)frame {

    self = [Utilities initWithNibName:@"XIB1" withSelf:self];
    if (self) {
        // Initialization code.
    }
    return self;
}

Posted for general interest; if anyone sees any problems without doing it this way, please let me know.

How to install the Raspberry Pi cross compiler on my Linux host machine?

there is a CDP Studio IDE available that makes cross compile and deploy quite simple from both windows and linux and you can just check the raspberry toolchain checkbox during the installation. (PS. it has GPIO and I2C support so no code is needed to access those)

The IDE demo of raspberry use is up here: https://youtu.be/4SVZ68sQz5U

and you can download the IDE here: https://cdpstudio.com/home-edition

MySQL Event Scheduler on a specific time everyday

The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;

When in the command-line MySQL client, you can:

SHOW EVENTS;

This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
  EVERY 13 DAY_HOUR
  COMMENT 'Clean up sessions at 13:00 daily!'
  DO
    DELETE FROM site_activity.sessions;

How do I disable a jquery-ui draggable?

The following is what this would look like inside of .draggable({});

$("#yourDraggable").draggable({
    revert: "invalid" ,
    start: function(){ 
        $(this).css("opacity",0.3);
    },
    stop: function(){ 
        $(this).draggable( 'disable' )
    },
    opacity: 0.7,
    helper: function () { 
        $copy = $(this).clone(); 
        $copy.css({
            "list-style":"none",
            "width":$(this).outerWidth()
        }); 
        return $copy; 
    },
    appendTo: 'body',
    scroll: false
});

Python logging: use milliseconds in time format

If you prefer to use style='{', fmt="{asctime}.{msecs:0<3.0f}" will 0-pad your microseconds to three places for consistency.

How to test an Internet connection with bash?

Execute the following command to check whether a web site is up, and what status message the web server is showing:

curl -Is http://www.google.com | head -1 HTTP/1.1 200 OK

Status code ‘200 OK’ means that the request has succeeded and a website is reachable.

How can I pass an argument to a PowerShell script?

You can also define a variable directly in the PowerShell command line and then execute the script. The variable will be defined there, too. This helped me in a case where I couldn't modify a signed script.

Example:

 PS C:\temp> $stepsize = 30
 PS C:\temp> .\itunesForward.ps1

with iTunesForward.ps1 being

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $stepsize
}

SQL select only rows with max value on a column

I like to do this by ranking the records by some column. In this case, rank rev values grouped by id. Those with higher rev will have lower rankings. So highest rev will have ranking of 1.

select id, rev, content
from
 (select
    @rowNum := if(@prevValue = id, @rowNum+1, 1) as row_num,
    id, rev, content,
    @prevValue := id
  from
   (select id, rev, content from YOURTABLE order by id asc, rev desc) TEMP,
   (select @rowNum := 1 from DUAL) X,
   (select @prevValue := -1 from DUAL) Y) TEMP
where row_num = 1;

Not sure if introducing variables makes the whole thing slower. But at least I'm not querying YOURTABLE twice.

How to update npm

You can try:

sudo npm i -g npm

Create two threads, one display odd & other even numbers

public class OddEvenPrinetr {
    private static Object printOdd = new Object();

    public static void main(String[] args) {

        Runnable oddPrinter =  new Runnable() {
            int count = 1;
            @Override
            public void run() {
                while(true){
                    synchronized (printOdd) {
                        if(count >= 101){
                            printOdd.notify();
                            return;
                        }
                        System.out.println(count);
                        count = count + 2;                                              
                        try {
                            printOdd.notify();
                            printOdd.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };


        Runnable evenPrinter =  new Runnable() {
            int count = 0;
            @Override
            public void run() {
                while(true){
                    synchronized (printOdd) {
                        printOdd.notify();
                        if(count >= 100){                       
                            return;
                        }                                       
                        count = count + 2;
                        System.out.println(count);
                        printOdd.notify();
                        try {
                            printOdd.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        new Thread(oddPrinter).start();
        new Thread(evenPrinter).start();
    }
}

Trying to use fetch and pass in mode: no-cors

Very easy solution (2 min to config) is to use local-ssl-proxy package from npm

The usage is straight pretty forward:
1. Install the package: npm install -g local-ssl-proxy
2. While running your local-server mask it with the local-ssl-proxy --source 9001 --target 9000

P.S: Replace --target 9000 with the -- "number of your port" and --source 9001 with --source "number of your port +1"

Should I test private methods or only public ones?

If you don't test your private methods, how do you know they won't break?

How to open a page in a new window or tab from code-behind

This code works for me:

Dim script As String = "<script type=""text/javascript"">window.open('" & URL.ToString & "');</script>"
ClientScript.RegisterStartupScript(Me.GetType, "openWindow", script)

How to switch to new window in Selenium for Python?

You can do it by using window_handles and switch_to_window method.

Before clicking the link first store the window handle as

window_before = driver.window_handles[0]

after clicking the link store the window handle of newly opened window as

window_after = driver.window_handles[1]

then execute the switch to window method to move to newly opened window

driver.switch_to_window(window_after)

and similarly you can switch between old and new window. Following is the code example

import unittest
from selenium import webdriver

class GoogleOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_google_search_page(self):
        driver = self.driver
        driver.get("http://www.cdot.in")
        window_before = driver.window_handles[0]
        print window_before
        driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()
        window_after = driver.window_handles[1]
        driver.switch_to_window(window_after)
        print window_after
        driver.find_element_by_link_text("ATM").click()
        driver.switch_to_window(window_before)

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

Select top 10 records for each category

Might the UNION operator work for you? Have one SELECT for each section, then UNION them together. Guess it would only work for a fixed number of sections though.

Mysql: Select all data between two dates

you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)

Searching word in vim?

like this:

/\<word\>

\< means beginning of a word, and \> means the end of a word,

Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*' to search forward in the file or '#' to search backwards.

Android: Tabs at the BOTTOM

For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom. Eclipse Project: android-custom-tabs ; Original explanation: blog; Hope this helped.

How to script FTP upload and download?

Try manually:

$ ftp www.domainhere.com 
> useridhere
> passwordhere
> put test.txt
> bye
> pause

Get month and year from a datetime in SQL Server 2005

I had the same problem and after looking around I found this:

SELECT DATENAME(yyyy, date) AS year
FROM Income
GROUP BY DATENAME(yyyy, date)

It's working great!

Early exit from function?

You can just use return.

function myfunction() {
     if(a == 'stop') 
         return;
}

This will send a return value of undefined to whatever called the function.

var x = myfunction();

console.log( x );  // console shows undefined

Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.

return false;
return true;
return "some string";
return 12345;

Deleting DataFrame row in Pandas based on column value

If I'm understanding correctly, it should be as simple as:

df = df[df.line_race != 0]

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

All of the answers above may work for the time being but whenever you run maven on the command line or Maven → Update project… the JDK will be reset, this was also the question as I understand it.

To fix this for good add the following code to your pom file. Remember to do a Maven → Update project… afterwards or mvn clean compile at the command line.

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>

    </pluginManagement>
</build>

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

How to upgrade scikit-learn package in anaconda

Updating a Specific Library - scikit-learn:

Anaconda (conda):

conda install scikit-learn

Pip Installs Packages (pip):

pip install --upgrade scikit-learn

Verify Update:

conda list scikit-learn

It should now display the current (and desired) version of the scikit-learn library.

For me personally, I tried using the conda command to update the scikit-learn library and it acted as if it were installing the latest version to then later discover (with an execution of the conda list scikit-learn command) that it was the same version as previously and never updated (or recognized the update?). When I used the pip command, it worked like a charm and correctly updated the scikit-learn library to the latest version!

Hope this helps!

More in-depth details of latest version can be found here (be mindful this applies to the scikit-learn library version of 0.22):

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

For me this problem started with upgrading react-native. The upgrade was necessary to add 64-bit support.

Before:
-------- 
Environment:
Node: 10.15.0
npm: 6.9.0
Watchman: 4.9.0
Xcode: Not Found
Android Studio: 3.4 AI-183.6156.11.34.5692245

Packages: (wanted => installed)
react: 16.0.0-alpha.12 => 16.0.0-alpha.12
react-native: ~0.55.2 => 0.55.4
react-native-cli: 2.0.1

After:
------
info 
React Native Environment Info:
Binaries:
Node: 10.15.0
npm: 6.9.0
Watchman: 4.9.0
SDKs:
Android SDK:
API Levels: 23, 26, 27, 28
Build Tools: 27.0.3, 28.0.3
System Images: android-28 | Google APIs Intel x86 Atom
IDEs:
Android Studio: 3.4 AI-183.6156.11.34.5692245
Xcode: /undefined - /usr/bin/xcodebuild
npmPackages:
react: ^16.8.6 => 16.9.0 
react-native: 0.59.9 => 0.59.9 
npmGlobalPackages:
create-react-native-app: 2.0.2
react-native-cli: 2.0.1

Also, One important change that I made for the upgrade was in ../android/build/build.gradle

android {
    ...
    defaultConfig {
        ...
        targetSdkVersion 28
        ...
    }
    ...
}

I had to change the targetSdkVersion from 27 to 28 following warning when I tried to upload the build(.apk) to goole play console. Little did i realise that this was the root cause of the above error for me. Immediatly answers by @tom and @tinmarfrutos made absolute sense.

I solved the problem by adding android:usesCleartextTraffic="true" to my android/app/src/debug/AndroidManifest.xml

Peak memory usage of a linux/unix process

On macOS, you can use DTrace instead. The "Instruments" app is a nice GUI for that, it comes with XCode afaik.

Maven fails to find local artifact

When this happened to me, it was because I'd blindly copied my settings.xml from a template and it still had the blank <localRepository/> element. This means that there's no local repository used when resolving dependencies (though your installed artifacts do still get put in the default location). When I'd replaced that with <localRepository>${user.home}\.m2\repository</localRepository> it started working.

For *nix, that would be <localRepository>${user.home}/.m2/repository</localRepository>, I suppose.

What's the best way to get the last element of an array without deleting it?

Try

$myLastElement = end($yourArray);

To reset it (thanks @hopeseekr):

 reset($yourArray);

Link to manual

@David Murdoch added: $myLastElement = end(array_values($yourArray));// and now you don't need to call reset(). On E_STRICT this produces the warning

Strict Standards: Only variables should be passed by reference

Thanks o_O Tync and everyone!

Going from MM/DD/YYYY to DD-MMM-YYYY in java

java.time

You should use java.time classes with Java 8 and later. To use java.time, add:

import java.time.* ;

Below is an example, how you can format date.

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate); 
System.out.println(formatter.format(localDate));

How to display text in pygame?

Here is my answer:


    def draw_text(text, font_name, size, color, x, y, align="nw"):
        font = pg.font.Font(font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        if align == "nw":
            text_rect.topleft = (x, y)
        if align == "ne":
            text_rect.topright = (x, y)
        if align == "sw":
            text_rect.bottomleft = (x, y)
        if align == "se":
            text_rect.bottomright = (x, y)
        if align == "n":
            text_rect.midtop = (x, y)
        if align == "s":
            text_rect.midbottom = (x, y)
        if align == "e":
            text_rect.midright = (x, y)
        if align == "w":
            text_rect.midleft = (x, y)
        if align == "center":
            text_rect.center = (x, y)
        screen.blit(text_surface, text_rect)

Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".

jquery loop on Json data using $.each

Have you converted your data from string to JavaScript object?

You can do it with data = eval('(' + string_data + ')'); or, which is safer, data = JSON.parse(string_data); but later will only works in FF 3.5 or if you include json2.js

jQuery since 1.4.1 also have function for that, $.parseJSON().

But actually, $.getJSON() should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.

How to output only captured groups with sed?

you can use grep

grep -Eow "[0-9]+" file

How to set text color in submit button?

_x000D_
_x000D_
.button_x000D_
{_x000D_
    font-size: 13px;_x000D_
    color:green;_x000D_
}
_x000D_
<input type="submit" value="Fetch" class="button"/>
_x000D_
_x000D_
_x000D_

How to have git log show filenames like svn log -v

A summary of answers with example output

This is using a local repository with five simple commits.

? git log --name-only
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

file5

commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:36:32 2019 -0700

    foo file1

    really important to foo before the bar

file1

commit 1b6413400b5a6a96d062a7c13109e6325e081c85
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:34:37 2019 -0700

    foobar file2, rm file3

file2
file3

commit e0dd02ce23977c782987a206236da5ab784543cc
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:33:05 2019 -0700

    Add file4

file4

commit b58e85692f711d402bae4ca606d3d2262bb76cf1
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:32:41 2019 -0700

    Added files

file1
file2
file3


? git log --name-status
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

R100    file4   file5

commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:36:32 2019 -0700

    foo file1

    really important to foo before the bar

M       file1

commit 1b6413400b5a6a96d062a7c13109e6325e081c85
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:34:37 2019 -0700

    foobar file2, rm file3

M       file2
D       file3

commit e0dd02ce23977c782987a206236da5ab784543cc
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:33:05 2019 -0700

    Add file4

A       file4

commit b58e85692f711d402bae4ca606d3d2262bb76cf1
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:32:41 2019 -0700

    Added files

A       file1
A       file2
A       file3


? git log --stat
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

 file4 => file5 | 0
 1 file changed, 0 insertions(+), 0 deletions(-)

commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:36:32 2019 -0700

    foo file1

    really important to foo before the bar

 file1 | 3 +++
 1 file changed, 3 insertions(+)

commit 1b6413400b5a6a96d062a7c13109e6325e081c85
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:34:37 2019 -0700

    foobar file2, rm file3

 file2 | 1 +
 file3 | 0
 2 files changed, 1 insertion(+)

commit e0dd02ce23977c782987a206236da5ab784543cc
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:33:05 2019 -0700

    Add file4

 file4 | 0
 1 file changed, 0 insertions(+), 0 deletions(-)

commit b58e85692f711d402bae4ca606d3d2262bb76cf1
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:32:41 2019 -0700

    Added files

 file1 | 0
 file2 | 0
 file3 | 0
 3 files changed, 0 insertions(+), 0 deletions(-)


? git log --name-only --oneline
ed080bc (HEAD -> master) mv file4 to file5
file5
5c4e8cf foo file1
file1
1b64134 foobar file2, rm file3
file2
file3
e0dd02c Add file4
file4
b58e856 Added files
file1
file2
file3


? git log --pretty=oneline --graph --name-status
* ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master) mv file4 to file5
| R100  file4   file5
* 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328 foo file1
| M     file1
* 1b6413400b5a6a96d062a7c13109e6325e081c85 foobar file2, rm file3
| M     file2
| D     file3
* e0dd02ce23977c782987a206236da5ab784543cc Add file4
| A     file4
* b58e85692f711d402bae4ca606d3d2262bb76cf1 Added files
  A     file1
  A     file2
  A     file3


? git diff-tree HEAD
ed080bc88b7bf0c5125e093a26549f3755f7ae74
:100644 000000 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0000000000000000000000000000000000000000 D  file4
:000000 100644 0000000000000000000000000000000000000000 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 A  file5


? git log --stat --pretty=short --graph
* commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
| Author: My Name <[email protected]>
| 
|     mv file4 to file5
| 
|  file4 => file5 | 0
|  1 file changed, 0 insertions(+), 0 deletions(-)
| 
* commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
| Author: My Name <[email protected]>
| 
|     foo file1
| 
|  file1 | 3 +++
|  1 file changed, 3 insertions(+)
| 
* commit 1b6413400b5a6a96d062a7c13109e6325e081c85
| Author: My Name <[email protected]>
| 
|     foobar file2, rm file3
| 
|  file2 | 1 +
|  file3 | 0
|  2 files changed, 1 insertion(+)
| 
* commit e0dd02ce23977c782987a206236da5ab784543cc
| Author: My Name <[email protected]>
| 
|     Add file4
| 
|  file4 | 0
|  1 file changed, 0 insertions(+), 0 deletions(-)
| 
* commit b58e85692f711d402bae4ca606d3d2262bb76cf1
  Author: My Name <[email protected]>

      Added files

   file1 | 0
   file2 | 0
   file3 | 0
   3 files changed, 0 insertions(+), 0 deletions(-)


? git log --name-only --pretty=format:
file5

file1

file2
file3

file4

file1
file2
file3


? git log --name-status --pretty=format:
R100    file4   file5

M       file1

M       file2
D       file3

A       file4

A       file1
A       file2
A       file3


? git diff --stat 'HEAD^!'
 file4 => file5 | 0
 1 file changed, 0 insertions(+), 0 deletions(-)


? git show
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

diff --git a/file4 b/file5
similarity index 100%
rename from file4
rename to file5


Credits to @CB-Bailey @Peter-Suwara @Gaurav @Omer-Dagan @xsor @Hazok @nrz @ptc

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

You can add a following method inside your bootstrap class which is annotated with @SpringBootApplication

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);

    objectMapper.registerModule(new JodaModule());

    return objectMapper;
}

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Invalid default value for 'create_date' timestamp field

Change this:

`create_date` TIMESTAMP NOT NULL DEFAULT  '0000-00-00 00:00:00',
`update_date` TIMESTAMP NOT NULL DEFAULT  CURRENT_TIMESTAMP  ,

To the following:

`create_date` TIMESTAMP NOT NULL DEFAULT  CURRENT_TIMESTAMP ,
`update_date` TIMESTAMP NOT NULL DEFAULT  CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,

Best Practices for mapping one object to another

This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):

public class DtoMapper<DtoType>
{
    Dictionary<string,PropertyInfo> properties;

    public DtoMapper()
    {
        // Cache property infos
        var t = typeof(DtoType);
        properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
     }

    public DtoType Map(Dto dto)
    {
        var instance = Activator.CreateInstance(typeOf(DtoType));

        foreach(var p in properties)
        {
            p.SetProperty(
                instance, 
                Convert.Type(
                    p.PropertyType, 
                    dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);

            return instance;
        }
    }

Usage:

var mapper = new DtoMapper<Model>();
var modelInstance = mapper.Map(dto);

This will be slow when you create the mapper instance but much faster later.

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

This is my solution, i have the same issue and its seems like this solution work for me.

yourObj = [].concat(yourObj);

When creating a service with sc.exe how to pass in context parameters?

It also important taking in account how you access the Arguments in the code of the application.

In my c# application I used the ServiceBase class:

 class MyService : ServiceBase
{

    protected override void OnStart(string[] args)
    {
       }
 }

I registered my service using

sc create myService binpath= "MeyService.exe arg1 arg2"

But I couldn't access the arguments through the args variable when I run it as a service.

The MSDN documentation suggests not using the Main method to retrieve the binPath or ImagePath arguments. Instead it suggests placing your logic in the OnStart method and then using (C#) Environment.GetCommandLineArgs();.

To access the first arguments arg1 I need to do like this:

class MyService : ServiceBase
 {

    protected override void OnStart(string[] args)
    {

                log.Info("arg1 == "+Environment.GetCommandLineArgs()[1]);

       }
 }

this would print

       arg1 == arg1

Set the default value in dropdownlist using jQuery

$('#userZipFiles option').prop('selected', function() {
        return this.defaultSelected;
    });     

How do I programmatically "restart" an Android app?

in MainActivity call restartActivity Method:

public static void restartActivity(Activity mActivity) {
    Intent mIntent = mActivity.getIntent();
    mActivity.finish();
    mActivity.startActivity(mIntent);
}

How do I fix the indentation of selected lines in Visual Studio

For the Mac users.

For selecting all of the code in the document => cmd+A

For formatting selected code => cmd+K, cmd+F

clearing a char array c

Try the following code:

void clean(char *var) {
    int i = 0;
    while(var[i] != '\0') {
        var[i] = '\0';
        i++;
    }
}

Node.js: what is ENOSPC error and how to solve?

If you're using VS Code then it'll should unable to watch in large workspace error.

"Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)

It indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. The current limit can be viewed by running:

cat /proc/sys/fs/inotify/max_user_watches

The limit can be increased to its maximum by editing /etc/sysctl.conf and adding this line to the end of the file:

fs.inotify.max_user_watches=524288

The new value can then be loaded in by running sudo sysctl -p.

Note: 524288 is the max value to watch the files. Though you can watch any no of files but is also recommended to watch upto that limit only.

What does "xmlns" in XML mean?

I think the biggest confusion is that xml namespace is pointing to some kind of URL that doesn't have any information. But the truth is that the person who invented below namespace:

xmlns:android="http://schemas.android.com/apk/res/android"

could also call it like that:

xmlns:android="asjkl;fhgaslifujhaslkfjhliuqwhrqwjlrknqwljk.rho;il"

This is just a unique identifier. However it is established that you should put there URL that is unique and can potentially point to the specification of used tags/attributes in that namespace. It's not required tho.

Why it should be unique? Because namespaces purpose is to have them unique so the attribute for example called background from your namespace can be distinguished from the background from another namespace.

Because of that uniqueness you do not need to worry that if you create your custom attribute you gonna have name collision.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

All the above not working for me.. Because I am using Facebook Ad dependency..

Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'

Try this code instead of above

compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

Where are Docker images stored on the host machine?

In Docker for Windows (native Windows) the default container storage is at:

   > docker info
   ...
   Docker Root Dir: C:\ProgramData\Docker
   ...

Check if a user has scrolled to the bottom

Instead of listening to the scroll event, using Intersection Observer is the inexpensive one for checking if the last element was visible on the viewport (that's mean user was scrolled to the bottom). It also supported for IE7 with the polyfill.

_x000D_
_x000D_
var observer = new IntersectionObserver(function(entries){_x000D_
   if(entries[0].isIntersecting === true)_x000D_
      console.log("Scrolled to the bottom");_x000D_
   else_x000D_
      console.log("Not on the bottom");_x000D_
}, {_x000D_
   root:document.querySelector('#scrollContainer'),_x000D_
   threshold:1 // Trigger only when whole element was visible_x000D_
});_x000D_
_x000D_
observer.observe(document.querySelector('#scrollContainer').lastElementChild);
_x000D_
#scrollContainer{_x000D_
  height: 100px;_x000D_
  overflow: hidden scroll;_x000D_
}
_x000D_
<div id="scrollContainer">_x000D_
  <div>Item 1</div>_x000D_
  <div>Item 2</div>_x000D_
  <div>Item 3</div>_x000D_
  <div>Item 4</div>_x000D_
  <div>Item 5</div>_x000D_
  <div>Item 6</div>_x000D_
  <div>Item 7</div>_x000D_
  <div>Item 8</div>_x000D_
  <div>Item 9</div>_x000D_
  <div>Item 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions: