Programs & Examples On #Buildout

zc.buildout is a Python-based build system for creating, assembling and deploying applications from multiple parts, some of which may be non-Python-based. It lets you create a buildout configuration and reproduce the same software later on.

cannot load such file -- bundler/setup (LoadError)

I got this error in a fresh Rails app with bundle correctly installed. Commenting out the spring gem in Gemfile resolved the problem.

Best algorithm for detecting cycles in a directed graph

According to Lemma 22.11 of Cormen et al., Introduction to Algorithms (CLRS):

A directed graph G is acyclic if and only if a depth-first search of G yields no back edges.

This has been mentioned in several answers; here I'll also provide a code example based on chapter 22 of CLRS. The example graph is illustrated below.

enter image description here

CLRS' pseudo-code for depth-first search reads:

enter image description here

In the example in CLRS Figure 22.4, the graph consists of two DFS trees: one consisting of nodes u, v, x, and y, and the other of nodes w and z. Each tree contains one back edge: one from x to v and another from z to z (a self-loop).

The key realization is that a back edge is encountered when, in the DFS-VISIT function, while iterating over the neighbors v of u, a node is encountered with the GRAY color.

The following Python code is an adaptation of CLRS' pseudocode with an if clause added which detects cycles:

import collections


class Graph(object):
    def __init__(self, edges):
        self.edges = edges
        self.adj = Graph._build_adjacency_list(edges)

    @staticmethod
    def _build_adjacency_list(edges):
        adj = collections.defaultdict(list)
        for edge in edges:
            adj[edge[0]].append(edge[1])
        return adj


def dfs(G):
    discovered = set()
    finished = set()

    for u in G.adj:
        if u not in discovered and u not in finished:
            discovered, finished = dfs_visit(G, u, discovered, finished)


def dfs_visit(G, u, discovered, finished):
    discovered.add(u)

    for v in G.adj[u]:
        # Detect cycles
        if v in discovered:
            print(f"Cycle detected: found a back edge from {u} to {v}.")

        # Recurse into DFS tree
        if v not in finished:
            dfs_visit(G, v, discovered, finished)

    discovered.remove(u)
    finished.add(u)

    return discovered, finished


if __name__ == "__main__":
    G = Graph([
        ('u', 'v'),
        ('u', 'x'),
        ('v', 'y'),
        ('w', 'y'),
        ('w', 'z'),
        ('x', 'v'),
        ('y', 'x'),
        ('z', 'z')])

    dfs(G)

Note that in this example, the time in CLRS' pseudocode is not captured because we're only interested in detecting cycles. There is also some boilerplate code for building the adjacency list representation of a graph from a list of edges.

When this script is executed, it prints the following output:

Cycle detected: found a back edge from x to v.
Cycle detected: found a back edge from z to z.

These are exactly the back edges in the example in CLRS Figure 22.4.

How to force NSLocalizedString to use a specific language

Do not use on iOS 9. This returns nil for all strings passed through it.

I have found another solution that allows you to update the language strings, w/o restarting the app and compatible with genstrings:

Put this macro in the Prefix.pch:

#define currentLanguageBundle [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"]]

and where ever you need a localized string use:

NSLocalizedStringFromTableInBundle(@"GalleryTitleKey", nil, currentLanguageBundle, @"")

To set the language use:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"de"] forKey:@"AppleLanguages"];

Works even with consecutive language hopping like:

NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"fr"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"it"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"de"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));

How do I calculate a trendline for a graph?

This is the way i calculated the slope: Source: http://classroom.synonym.com/calculate-trendline-2709.html

class Program
    {
        public double CalculateTrendlineSlope(List<Point> graph)
        {
            int n = graph.Count;
            double a = 0;
            double b = 0;
            double bx = 0;
            double by = 0;
            double c = 0;
            double d = 0;
            double slope = 0;

            foreach (Point point in graph)
            {
                a += point.x * point.y;
                bx = point.x;
                by = point.y;
                c += Math.Pow(point.x, 2);
                d += point.x;
            }
            a *= n;
            b = bx * by;
            c *= n;
            d = Math.Pow(d, 2);

            slope = (a - b) / (c - d);
            return slope;
        }
    }

    class Point
    {
        public double x;
        public double y;
    }

How do I edit an incorrect commit message in git ( that I've pushed )?

If you are using Git Extensions: go into the Commit screen, there should be a checkbox that says "Amend Commit" at the bottom, as can be seen below:

enter image description here

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

How to check for null in Twig?

Without any assumptions the answer is:

{% if var is null %}

But this will be true only if var is exactly NULL, and not any other value that evaluates to false (such as zero, empty string and empty array). Besides, it will cause an error if var is not defined. A safer way would be:

{% if var is not defined or var is null %}

which can be shortened to:

{% if var|default is null %}

If you don't provide an argument to the default filter, it assumes NULL (sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):

{% if var|default is empty %}

How to return a class object by reference in C++?

You can only return non-local objects by reference. The destructor may have invalidated some internal pointer, or whatever.

Don't be afraid of returning values -- it's fast!

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

Was able to solve the issue by adding "startup" element with "useLegacyV2RuntimeActivationPolicy" attribute set.

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    <supportedRuntime version="v2.0.50727"/>
</startup>

But had to place it as the first child element of configuration tag in App.config for it to take effect.

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

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

Multi-line string with extra space (preserved indentation)

echo adds spaces between the arguments passed to it. $text is subject to variable expansion and word splitting, so your echo command is equivalent to:

echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n"  ...

You can see that a space will be added before "this". You can either remove the newline characters, and quote $text to preserve the newlines:

text="this is line one
this is line two
this is line three"

echo "$text" > filename

Or you could use printf, which is more robust and portable than echo:

printf "%s\n" "this is line one" "this is line two" "this is line three" > filename

In bash, which supports brace expansion, you could even do:

printf "%s\n" "this is line "{one,two,three} > filename

Pull request vs Merge request

GitLab's "merge request" feature is equivalent to GitHub's "pull request" feature. Both are means of pulling changes from another branch or fork into your branch and merging the changes with your existing code. They are useful tools for code review and change management.

An article from GitLab discusses the differences in naming the feature:

Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we'll refer to them as merge requests.

A "merge request" should not be confused with the git merge command. Neither should a "pull request" be confused with the git pull command. Both git commands are used behind the scenes in both pull requests and merge requests, but a merge/pull request refers to a much broader topic than just these two commands.

PHP Get name of current directory

echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only

Variable used in lambda expression should be final or effectively final

Although other answers prove the requirement, they don't explain why the requirement exists.

The JLS mentions why in §15.27.2:

The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.

To lower risk of bugs, they decided to ensure captured variables are never mutated.

What is the best way to compare 2 folder trees on windows?

Did you try: https://www.araxis.com/merge/index.en It allows to visualize changes and selectively merge specific differences in files and folders.

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

Fixing Segmentation faults in C++

Yes, there is a problem with pointers. Very likely you're using one that's not initialized properly, but it's also possible that you're messing up your memory management with double frees or some such.

To avoid uninitialized pointers as local variables, try declaring them as late as possible, preferably (and this isn't always possible) when they can be initialized with a meaningful value. Convince yourself that they will have a value before they're being used, by examining the code. If you have difficulty with that, initialize them to a null pointer constant (usually written as NULL or 0) and check them.

To avoid uninitialized pointers as member values, make sure they're initialized properly in the constructor, and handled properly in copy constructors and assignment operators. Don't rely on an init function for memory management, although you can for other initialization.

If your class doesn't need copy constructors or assignment operators, you can declare them as private member functions and never define them. That will cause a compiler error if they're explicitly or implicitly used.

Use smart pointers when applicable. The big advantage here is that, if you stick to them and use them consistently, you can completely avoid writing delete and nothing will be double-deleted.

Use C++ strings and container classes whenever possible, instead of C-style strings and arrays. Consider using .at(i) rather than [i], because that will force bounds checking. See if your compiler or library can be set to check bounds on [i], at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers.

Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems. They will doubtless fail to fix everything, and that's why you should use valgrind now and then when you don't have problems, and valgrind and gdb when you do.

How to replace a string in a SQL Server Table Column

If target column type is other than varchar/nvarchar like text, we need to cast the column value as string and then convert it as:

update URL_TABLE
set Parameters = REPLACE ( cast(Parameters as varchar(max)), 'india', 'bharat')
where URL_ID='150721_013359670'

Apache Proxy: No protocol handler was valid

To clarify for future reference, a2enmod, as is suggested in several answers above, is for Debian/Ubuntu. Red Hat does not use this to enable Apache modules - instead it uses LoadModule statements in httpd.conf.

More here: https://serverfault.com/questions/56394/how-do-i-enable-apache-modules-from-the-command-line-in-redhat

The resolution/correct answer is in the comments on the OP:

I think you need mod_ssl and SSLProxyEngine with ProxyPass – Deadooshka May 29 '14 at 11:35

@Deadooshka Yes, this is working. If you post this as an answer, I can accept it – das_j May 29 '14 at 12:04

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Add new row to excel Table (VBA)

I actually just found that if you want to add multiple rows below the selection in your table Selection.ListObject.ListRows.Add AlwaysInsert:=True works really well. I just duplicated the code five times to add five rows to my table

What is the difference between dynamic programming and greedy approach?

With the reference of Biswajit Roy: Dynamic Programming firstly plans then Go. and Greedy algorithm uses greedy choice, it firstly Go then continuously Plans.

How to add click event to a iframe with JQuery

Try using this : iframeTracker jQuery Plugin, like that :

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});

How can I generate a 6 digit unique number?

Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.

random_int(100000, 999999)

Note that here we use random_int, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes was also introduced in PHP 7 and likewise uses a cryptographic random generator.

Many other solutions for random value generation, including those involving time(), microtime(), uniqid(), rand(), mt_rand(), str_shuffle(), and array_rand(), are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.

The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int or random_bytes rather than rand(), mt_rand(), str_shuffle(), etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?

I also list other things to keep in mind when generating unique identifiers, especially random ones.

insert data into database using servlet and jsp in eclipse

In your JSP at line <form> tag, try this code

<form name="registrationform" action="Register" method="post">

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

In this line:

for name, email, lastname in unpaidMembers.items():

unpaidMembers.items() must have only two values per iteration.

Here is a small example to illustrate the problem:

This will work:

for alpha, beta, delta in [("first", "second", "third")]:
    print("alpha:", alpha, "beta:", beta, "delta:", delta)

This will fail, and is what your code does:

for alpha, beta, delta in [("first", "second")]:
    print("alpha:", alpha, "beta:", beta, "delta:", delta)

In this last example, what value in the list is assigned to delta? Nothing, There aren't enough values, and that is the problem.

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

Android Studio how to run gradle sync manually?

In Android Studio 3.3 it is here:

enter image description here

According to the answer https://stackoverflow.com/a/49576954/2914140 in Android Studio 3.1 it is here:

enter image description here

This command is moved to File > Sync Project with Gradle Files.

enter image description here

Convert DataSet to List

Try the above which will run with any list type.

  public DataTable ListToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection props =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item);
            }
            table.Rows.Add(values);
        }
        return table;
    }

Get current time in milliseconds using C++ and Boost

You can use boost::posix_time::time_duration to get the time range. E.g like this

boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();

And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock has milisecond resolution, not microsecond.

An example which is a little dependent on the hardware.

int main(int argc, char* argv[])
{
    boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
    boost::posix_time::time_duration diff = t2 - t1;
    std::cout << diff.total_milliseconds() << std::endl;

    boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
    boost::posix_time::time_duration msdiff = mst2 - mst1;
    std::cout << msdiff.total_milliseconds() << std::endl;
    return 0;
}

On my win7 machine. The first out is either 0 or 1000. Second resolution. The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.

How to check if an int is a null

An int is not null, it may be 0 if not initialized.

If you want an integer to be able to be null, you need to use Integer instead of int.

Integer id;
String name;

public Integer getId() { return id; }

Besides the statement if(person.equals(null)) can't be true, because if person is null, then a NullPointerException will be thrown. So the correct expression is if (person == null)

Use a normal link to submit a form

You can't really do this without some form of scripting to the best of my knowledge.

<form id="my_form">
<!-- Your Form -->    
<a href="javascript:{}" onclick="document.getElementById('my_form').submit(); return false;">submit</a>
</form>

Example from Here.

CLEAR SCREEN - Oracle SQL Developer shortcut?

Use the following command to clear screen in sqlplus.

SQL > clear scr 

jQuery check if <input> exists and has a value

Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

So, you'll either get undefined or "" or null -- all of which evaluate as false in if statements.

How to refresh or show immediately in datagridview after inserting?

Try below piece of code.

this.dataGridView1.RefreshEdit();

Indenting code in Sublime text 2?

It is very simple. Just go to Edit=>Line=>Reindent

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

Using str_replace so that it only acts on the first match?

Unfortunately, I don't know of any PHP function which can do this.
You can roll your own fairly easily like this:

function replace_first($find, $replace, $subject) {
    // stolen from the comments at PHP.net/str_replace
    // Splits $subject into an array of 2 items by $find,
    // and then joins the array with $replace
    return implode($replace, explode($find, $subject, 2));
}

PHP: How to check if a date is today, yesterday or tomorrow

<?php 
 $current = strtotime(date("Y-m-d"));
 $date    = strtotime("2014-09-05");

 $datediff = $date - $current;
 $difference = floor($datediff/(60*60*24));
 if($difference==0)
 {
    echo 'today';
 }
 else if($difference > 1)
 {
    echo 'Future Date';
 }
 else if($difference > 0)
 {
    echo 'tomorrow';
 }
 else if($difference < -1)
 {
    echo 'Long Back';
 }
 else
 {
    echo 'yesterday';
 }  
?>

Clear dropdown using jQuery Select2

This is how I do:

$('#my_input').select2('destroy').val('').select2();

Bloomberg Open API

I don't think so. The API's will provide access to delayed quotes, there is no way that real time data or tick data, will be provided for free.

PersistenceContext EntityManager injection NullPointerException

An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.

Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).

Here's an example of injecting an EntityManagerFactory:

package com.test.service;

import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;

@Path("/service")
public class TestService {

    @PersistenceUnit(unitName = "test")
    private EntityManagerFactory entityManagerFactory;

    @GET
    @Path("/get")
    @Produces("application/json")
    public List get() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            return entityManager.createQuery("from TestEntity").getResultList();
        } finally {
            entityManager.close();
        }
    }
}

The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.

Related question: Inject an EJB into JAX-RS (RESTful service)

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

How to call Oracle MD5 hash function?

@user755806 I do not believe that your question was answered. I took your code but used the 'foo' example string, added a lower function and also found the length of the hash returned. In sqlplus or Oracle's sql developer Java database client you can use this to call the md5sum of a value. The column formats clean up the presentation.

column hash_key format a34;
column hash_key_len format 999999;
select dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo')) as hash_key,
       length(dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo'))) as hash_key_len
 from dual;

The result set

HASH_KEY                           HASH_KEY_LEN
---------------------------------- ------------
acbd18db4cc2f85cedef654fccc4a4d8             32

is the same value that is returned from a Linux md5sum command.

echo -n foo | md5sum
acbd18db4cc2f85cedef654fccc4a4d8  -
  1. Yes you can call or execute the sql statement directly in sqlplus or sql developer. I tested the sql statement in both clients against 11g.
  2. You can use any C, C#, Java or other programming language that can send a statement to the database. It is the database on the other end of the call that needs to be able to understand the sql statement. In the case of 11 g, the code will work.
  3. @tbone provides an excellent warning about the deprecation of the dbms_obfuscation_toolkit. However, that does not mean your code is unusable in 12c. It will work but you will want to eventually switch to dbms_crypto package. dbms_crypto is not available in my version of 11g.

How to convert UTC timestamp to device local time in android

The code in your example looks fine at first glance. BTW, if the server timestamp is in UTC (i.e. it's an epoch timestamp) then you should not have to apply the current timezone offset. In other words if the server timestamp is in UTC then you can simply get the difference between the server timestamp and the system time (System.currentTimeMillis()) as the system time is in UTC (epoch).

I would check that the timestamp coming from your server is what you expect. If the timestamp from the server does not convert into the date you expect (in the local timezone) then the difference between the timestamp and the current system time will not be what you expect.

Use Calendar to get the current timezone. Initialize a SimpleDateFormatter with the current timezone; then log the server timestamp and verify if it's the date you expect:

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

/* debug: is it local time? */
Log.d("Time zone: ", tz.getDisplayName());

/* date formatter in local timezone */
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(tz);

/* print your timestamp and double check it's the date you expect */
long timestamp = cursor.getLong(columnIndex);
String localTime = sdf.format(new Date(timestamp * 1000)); // I assume your timestamp is in seconds and you're converting to milliseconds?
Log.d("Time: ", localTime);

If the server time that is printed is not what you expect then your server time is not in UTC.

If the server time that is printed is the date that you expect then you should not have to apply the rawoffset to it. So your code would be simpler (minus all the debug logging):

long timestamp = cursor.getLong(columnIndex);
Log.d("Server time: ", timestamp);

/* log the device timezone */
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone: ", tz.getDisplayName());

/* log the system time */
Log.d("System time: ", System.currentTimeMillis());

CharSequence relTime = DateUtils.getRelativeTimeSpanString(
    timestamp * 1000,
    System.currentTimeMillis(),
    DateUtils.MINUTE_IN_MILLIS);

((TextView) view).setText(relTime);

What is the difference between 127.0.0.1 and localhost

some applications will treat "localhost" specially. the mysql client will treat localhost as a request to connect to the local unix domain socket instead of using tcp to connect to the server on 127.0.0.1. This may be faster, and may be in a different authentication zone.

I don't know of other apps that treat localhost differently than 127.0.0.1, but there probably are some.

How to convert current date to epoch timestamp?

enter image description hereI think this answer needs an update and the solution would go better this way.

from datetime import datetime

datetime.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S").strftime("%s")

or you may use datetime object and format the time using %s to convert it into epoch time.

Internet Access in Ubuntu on VirtualBox

I had the same problem.

Solved by sharing internet connection (on the hosting OS).

Network Connection Properties -> advanced -> Allow other users to connect...

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

Change type of varchar field to integer: "cannot be cast automatically to type integer"

If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.

UPDATE table_mame SET field_name= 0;

After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.

ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;

I think it will help you.

Can't ignore UserInterfaceState.xcuserstate

Here is a very nice explanation of how to remove the files in question recursively from your git history: http://help.github.com/remove-sensitive-data/

Very useful, because otherwise tools tend to 'hang' while trying to show the diff on those huge files that shouldn't have been checked in the first place...

Here's what you can do (in short) to get rid of the largest stuff:

cd YourProject
git filter-branch --index-filter 'git rm --cached --ignore-unmatch -r YourProject.xcodeproj/project.xcworkspace' HEAD
# see what you want to do with your remote here...
# you can: git push origin master --force
# or you can delete it and push a fresh new one from your cleaned-up local...
rm -rf .git/refs/original
git gc --prune=now
git gc --aggressive --prune=now

Worked very nicely for me :)

How to use a variable inside a regular expression?

I needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:

pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)

Output can be printed using the following:

print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.

Converting a value to 2 decimal places within jQuery

Try to use this

parseFloat().toFixed(2)

What's the difference between ".equals" and "=="?

public static void main(String[] args){
        String s1 = new String("hello");
        String s2 = new String("hello");

        System.out.println(s1.equals(s2));
        ////
        System.out.println(s1 == s2);

    System.out.println("-----------------------------");

        String s3 = "hello";
        String s4 = "hello";

        System.out.println(s3.equals(s4));
        ////
        System.out.println(s3 == s4);
    }

Here in this code u can campare the both '==' and '.equals'

here .equals is used to compare the reference objects and '==' is used to compare state of objects..

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

You are returning an Observable where as your code returns just a boolean. So you need to use as below

.map(response => <boolean>response.json())

If you are using another common service checkservice in your case, you can simply use

this.service.getData().subscribe(data=>console.log(data));

This will make your checkLogin() function with return type as void

 checkLogin():void{
      this.service.getData()
            .map(response => {  
                           this.data = response;                            
                           this.checkservice=true;
             }).subscribe(data=>{ });

and you can use of this.checkService to check your condition

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

In Python, how to display current time in readable format

By using this code, you'll get your live time zone.

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

Python Git Module experiences?

Here's a really quick implementation of "git status":

import os
import string
from subprocess import *

repoDir = '/Users/foo/project'

def command(x):
    return str(Popen(x.split(' '), stdout=PIPE).communicate()[0])

def rm_empty(L): return [l for l in L if (l and l!="")]

def getUntracked():
    os.chdir(repoDir)
    status = command("git status")
    if "# Untracked files:" in status:
        untf = status.split("# Untracked files:")[1][1:].split("\n")
        return rm_empty([x[2:] for x in untf if string.strip(x) != "#" and x.startswith("#\t")])
    else:
        return []

def getNew():
    os.chdir(repoDir)
    status = command("git status").split("\n")
    return [x[14:] for x in status if x.startswith("#\tnew file:   ")]

def getModified():
    os.chdir(repoDir)
    status = command("git status").split("\n")
    return [x[14:] for x in status if x.startswith("#\tmodified:   ")]

print("Untracked:")
print( getUntracked() )
print("New:")
print( getNew() )
print("Modified:")
print( getModified() )

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

Another modification:

function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.

Also, if the server fails to respond, it won't keep trying.

I've used a similar method in the past using .ajax to handle even more complex behaviour:

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

This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.

This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.

Failed to load resource under Chrome

I updated my Chrome browser to the latest version and the issue was fixed.

Git ignore file for Xcode projects

The people of GitHub have exhaustive and documented .gitignore files for Xcode projects:

Swift: https://github.com/github/gitignore/blob/master/Swift.gitignore

Objective-C: https://github.com/github/gitignore/blob/master/Objective-C.gitignore

What is the difference between MVC and MVVM?

Well, generally MVC is used in Web development and MVVM is most popular in WPF/Silverlight development. However, sometimes the web architecute might have a mix of MVC and MVVM.

For example: you might use knockout.js and in this case you will have MVVM on your client side. And your MVC's server side can also change. In the complex apps, nobody uses the pure Model. It might have a sense to use a ViewModel as a "Model" of MVC and your real Model basically will be a part of this VM. This gives you an extra abstraction layer.

angularjs getting previous route path

In your html :

<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>

On your main controller :

$scope.go_back = function() { 
  $window.history.back();
};

When user click on Go Back link the controller function is called and it will go back to previous route.

Counting number of characters in a file through shell script

The following script is tested and gives exactly the results, that are expected

\#!/bin/bash

echo "Enter the file name"

read file

echo "enter the word to be found"

read word

count=0

for i in \`cat $file`

do

if [ $i == $word ]

then

count=\`expr $count + 1`

fi

done

echo "The number of words are $count"

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

<root>
    <level value="ALL" />
    <appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />
</logger>

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

How do I URl encode something in Node.js?

encodeURIComponent(string) will do it:

encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"

Passing SQL around in a query string might not be a good plan though,

see this one

Simple way to measure cell execution time in ipython notebook

You can use timeit magic function for that.

%timeit CODE_LINE

Or on the cell

%%timeit 

SOME_CELL_CODE

Check more IPython magic functions at https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb

Error handling with PHPMailer

You can get more info about the error with the method $mail->ErrorInfo. For example:

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

This is an alternative to the exception model that you need to active with new PHPMailer(true). But if can use exception model, use it as @Phil Rykoff answer.

This comes from the main page of PHPMailer on github https://github.com/PHPMailer/PHPMailer.

How to generate and validate a software license key?

I solved it by interfacing my program with a discord server, where it checks in a specific chat if the product key entered by the user exists and is still valid. In this way to receive a product key the user would be forced to hack discord and it is very difficult.

How do I check if PHP is connected to a database already?

before... (I mean somewhere in some other file you're not sure you've included)

$db = mysql_connect()

later...

if (is_resource($db)) {
// connected
} else {
$db = mysql_connect();
}

Squash my last X commits together using Git

I recommend avoiding git reset when possible -- especially for Git-novices. Unless you really need to automate a process based on a number of commits, there is a less exotic way...

  1. Put the to-be-squashed commits on a working branch (if they aren't already) -- use gitk for this
  2. Check out the target branch (e.g. 'master')
  3. git merge --squash (working branch name)
  4. git commit

The commit message will be prepopulated based on the squash.

PreparedStatement IN clause alternatives?

Limitations of the in() operator is the root of all evil.

It works for trivial cases, and you can extend it with "automatic generation of the prepared statement" however it is always having its limits.

  • if you're creating a statement with variable number of parameters, that will make an sql parse overhead at each call
  • on many platforms, the number of parameters of in() operator are limited
  • on all platforms, total SQL text size is limited, making impossible for sending down 2000 placeholders for the in params
  • sending down bind variables of 1000-10k is not possible, as the JDBC driver is having its limitations

The in() approach can be good enough for some cases, but not rocket proof :)

The rocket-proof solution is to pass the arbitrary number of parameters in a separate call (by passing a clob of params, for example), and then have a view (or any other way) to represent them in SQL and use in your where criteria.

A brute-force variant is here http://tkyte.blogspot.hu/2006/06/varying-in-lists.html

However if you can use PL/SQL, this mess can become pretty neat.

function getCustomers(in_customerIdList clob) return sys_refcursor is 
begin
    aux_in_list.parse(in_customerIdList);
    open res for
        select * 
        from   customer c,
               in_list v
        where  c.customer_id=v.token;
    return res;
end;

Then you can pass arbitrary number of comma separated customer ids in the parameter, and:

  • will get no parse delay, as the SQL for select is stable
  • no pipelined functions complexity - it is just one query
  • the SQL is using a simple join, instead of an IN operator, which is quite fast
  • after all, it is a good rule of thumb of not hitting the database with any plain select or DML, since it is Oracle, which offers lightyears of more than MySQL or similar simple database engines. PL/SQL allows you to hide the storage model from your application domain model in an effective way.

The trick here is:

  • we need a call which accepts the long string, and store somewhere where the db session can access to it (e.g. simple package variable, or dbms_session.set_context)
  • then we need a view which can parse this to rows
  • and then you have a view which contains the ids you're querying, so all you need is a simple join to the table queried.

The view looks like:

create or replace view in_list
as
select
    trim( substr (txt,
          instr (txt, ',', 1, level  ) + 1,
          instr (txt, ',', 1, level+1)
             - instr (txt, ',', 1, level) -1 ) ) as token
    from (select ','||aux_in_list.getpayload||',' txt from dual)
connect by level <= length(aux_in_list.getpayload)-length(replace(aux_in_list.getpayload,',',''))+1

where aux_in_list.getpayload refers to the original input string.


A possible approach would be to pass pl/sql arrays (supported by Oracle only), however you can't use those in pure SQL, therefore a conversion step is always needed. The conversion can not be done in SQL, so after all, passing a clob with all parameters in string and converting it witin a view is the most efficient solution.

android - setting LayoutParams programmatically

  LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                   /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*height*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*weight*/ 1.0f
            );
            YOUR_VIEW.setLayoutParams(param);

How to vertically center <div> inside the parent element with CSS?

You can vertically align a div in another div. See this example on JSFiddle or consider the example below.

HTML

<div class="outerDiv">
    <div class="innerDiv"> My Vertical Div </div>
</div>

CSS

.outerDiv {
    display: inline-flex;  // <-- This is responsible for vertical alignment
    height: 400px;
    background-color: red;
    color: white;
}

.innerDiv {
    margin: auto 5px;   // <-- This is responsible for vertical alignment
    background-color: green;   
}

The .innerDiv's margin must be in this format: margin: auto *px;

[Where, * is your desired value.]

display: inline-flex is supported in the latest (updated/current version) browsers with HTML5 support.

It may not work in Internet Explorer :P :)

Always try to define a height for any vertically aligned div (i.e. innerDiv) to counter compatibility issues.

git stash -> merge stashed change with current changes

What I want is a way to merge my stashed changes with the current changes

Here is another option to do it:

git stash show -p|git apply
git stash drop

git stash show -p will show the patch of last saved stash. git apply will apply it. After the merge is done, merged stash can be dropped with git stash drop.

How to sum digits of an integer in java?

If you need a one-liner I guess this is a very nice solution:

int sum(int n){
  return n >= 10 ? n % 10 + sum(n / 10) : n;
}

Warning :-Presenting view controllers on detached view controllers is discouraged

It depends if you want to show your alert or something similar in anywhere of kind UIViewController.

You can use this code example:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Example" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil];

[alert addAction:cancelAction];


[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alert animated:true completion:nil];

Javascript to convert UTC to local time

The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format

Spring cron expression for every after 30 minutes

If someone is using @Sceduled this might work for you.

@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")

This worked for me.

How to $watch multiple variable change in angular

No one has mentioned the obvious:

var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);

This might mean a little less polling. If you watch both name + age (for this) and name (elsewhere) then I assume Angular will effectively look at name twice to see if it's dirty.

It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.

And you can watch the values in different ways if you need to:

$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);

$watchGroup is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.

If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

How to emulate GPS location in the Android Emulator?

There is a plugin for Android Studio called “Mock Location Plugin”. You can emulate multiple points with this plugin. You can find a detailed manual of use in this link: Android Studio. Simulate multiple GPS points with Mock Location Plugin

How to make RatingBar to show five stars

The actual thing over here is to use wrap_content instead of match_parent. If you will use match_parent the layout will be filled with the stars even if it is more than the numStars variable.

Why rgb and not cmy?

The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).

The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK

A bit more information from the extract about them:

Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.

Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.

How to get a shell environment variable in a makefile?

all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

How to get multiple select box values using jQuery?

You can also use js map function:

$("#multipleSelect :selected").map(function(i, el) {
    return $(el).val();
}).get();

And then you can get any property of the option element:

return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...

Serialize an object to string

I know this is not really an answer to the question, but based on the number of votes for the question and the accepted answer, I suspect the people are actually using the code to serialize an object to a string.

Using XML serialization adds unnecessary extra text rubbish to the output.

For the following class

public class UserData
{
    public int UserId { get; set; }
}

it generates

<?xml version="1.0" encoding="utf-16"?>
<UserData xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <UserId>0</UserId>
</UserData>

Better solution is to use JSON serialization (one of the best is Json.NET). To serialize an object:

var userData = new UserData {UserId = 0};
var userDataString = JsonConvert.SerializeObject(userData);

To deserialize an object:

var userData = JsonConvert.DeserializeObject<UserData>(userDataString);

The serialized JSON string would look like:

{"UserId":0}

Split comma separated column data into additional columns

You can use split function.

    SELECT 
    (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
    (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
    (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
    (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
    FROM MyTbl

C# constructors overloading

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

Property getters and setters

Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.

Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:

class Point {
  private var _x: Int = 0             // _x -> backingX
  var x: Int {
    set { _x = 2 * newValue }
    get { return _x / 2 }
  }
}

Specifically, in the Swift REPL:

 15> var pt = Point()
pt: Point = {
  _x = 0
}
 16> pt.x = 10
 17> pt
$R3: Point = {
  _x = 20
}
 18> pt.x
$R4: Int = 10

How to calculate number of days between two dates

Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.

Link vs compile vs controller

A directive allows you to extend the HTML vocabulary in a declarative fashion for building web components. The ng-app attribute is a directive, so is ng-controller and all of the ng- prefixed attributes. Directives can be attributes, tags or even class names, comments.

How directives are born (compilation and instantiation)

Compile: We’ll use the compile function to both manipulate the DOM before it’s rendered and return a link function (that will handle the linking for us). This also is the place to put any methods that need to be shared around with all of the instances of this directive.

link: We’ll use the link function to register all listeners on a specific DOM element (that’s cloned from the template) and set up our bindings to the page.

If set in the compile() function they would only have been set once (which is often what you want). If set in the link() function they would be set every time the HTML element is bound to data in the object.

<div ng-repeat="i in [0,1,2]">
    <simple>
        <div>Inner content</div>
    </simple>
</div>

app.directive("simple", function(){
   return {
     restrict: "EA",
     transclude:true,
     template:"<div>{{label}}<div ng-transclude></div></div>",        
     compile: function(element, attributes){  
     return {
             pre: function(scope, element, attributes, controller, transcludeFn){

             },
             post: function(scope, element, attributes, controller, transcludeFn){

             }
         }
     },
     controller: function($scope){

     }
   };
});

Compile function returns the pre and post link function. In the pre link function we have the instance template and also the scope from the controller, but yet the template is not bound to scope and still don't have transcluded content.

Post link function is where post link is the last function to execute. Now the transclusion is complete, the template is linked to a scope, and the view will update with data bound values after the next digest cycle. The link option is just a shortcut to setting up a post-link function.

controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.

You have to specify the name of the directive to be required – It should be bound to same element or its parent. The name can be prefixed with:

? – Will not raise any error if a mentioned directive does not exist.
^ – Will look for the directive on parent elements, if not available on the same element.

Use square bracket [‘directive1', ‘directive2', ‘directive3'] to require multiple directives controller.

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

app.controller('MainCtrl', function($scope, $element) {
});

app.directive('parentDirective', function() {
  return {
    restrict: 'E',
    template: '<child-directive></child-directive>',
    controller: function($scope, $element){
      this.variable = "Hi Vinothbabu"
    }
  }
});

app.directive('childDirective', function() {
  return {
    restrict:  'E',
    template: '<h1>I am child</h1>',
    replace: true,
    require: '^parentDirective',
    link: function($scope, $element, attr, parentDirectCtrl){
      //you now have access to parentDirectCtrl.variable
    }
  }
});

Configure DataSource programmatically in Spring Boot

for springboot 2.1.7 working with url seems not to work. change with jdbcUrl instead.

In properties:

security:
      datasource:
        jdbcUrl: jdbc:mysql://ip:3306/security
        username: user
        password: pass

In java:

@ConfigurationProperties(prefix = "security.datasource")
@Bean("dataSource")
@Primary
public DataSource dataSource(){

    return DataSourceBuilder
            .create()
            .build();
}

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Try this (on Windows, i don't know how in others), if you have changed password a now don't work.

1) kill mysql 2) back up /mysql/data folder 3) go to folder /mysql/backup 4) copy files from /mysql/backup/mysql folder to /mysql/data/mysql (rewrite) 5) run mysql

In my XAMPP on Win7 it works.

How to set environment via `ng serve` in Angular 6

You need to use the new configuration option (this works for ng build and ng serve as well)

ng serve --configuration=local

or

ng serve -c local

If you look at your angular.json file, you'll see that you have finer control over settings for each configuration (aot, optimizer, environment files,...)

"configurations": {
  "production": {
    "optimization": true,
    "outputHashing": "all",
    "sourceMap": false,
    "extractCss": true,
    "namedChunks": false,
    "aot": true,
    "extractLicenses": true,
    "vendorChunk": false,
    "buildOptimizer": true,
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  }
}

You can get more info here for managing environment specific configurations.

As pointed in the other response below, if you need to add a new 'environment', you need to add a new configuration to the build task and, depending on your needs, to the serve and test tasks as well.

Adding a new environment

Edit: To make it clear, file replacements must be specified in the build section. So if you want to use ng serve with a specific environment file (say dev2), you first need to modify the build section to add a new dev2 configuration

"build": {
   "configurations": {
        "dev2": {

          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.dev2.ts"
            }
            /* You can add all other options here, such as aot, optimization, ... */
          ],
          "serviceWorker": true
        },

Then modify your serve section to add a new configuration as well, pointing to the dev2 build configuration you just declared

"serve":
      "configurations": {
        "dev2": {
          "browserTarget": "projectName:build:dev2"
        }

Then you can use ng serve -c dev2, which will use the dev2 config file

Find out time it took for a python script to complete execution

import time
start = time.time()

fun()

# python 2
print 'It took', time.time()-start, 'seconds.'

# python 3
print('It took', time.time()-start, 'seconds.')

Responsive iframe using Bootstrap

So, youtube gives out the iframe tag as follows:

<iframe width="560" height="315" src="https://www.youtube.com/embed/2EIeUlvHAiM" frameborder="0" allowfullscreen></iframe>

In my case, i just changed it to width="100%" and left the rest as is. It's not the most elegant solution (after all, in different devices you'll get weird ratios) But the video itself does not get deformed, just the frame.

no module named zlib

After running configure, you can change the config option in the file Modules/Setup as below:

zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz

Or you can uncomment the zlib line as-is.

Sum values in foreach loop php

$total=0;
foreach($group as $key=>$value)
{
   echo $key. " = " .$value. "<br>"; 
   $total+= $value;
}
echo $total;

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

jQuery checkbox checked state changed event

For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.

// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
    if(this.checked) {
      // checkbox is checked
    }
});

Note that it's almost always unnecessary to use document for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.

The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.

_x000D_
_x000D_
$postList = $('#post-list');_x000D_
_x000D_
$postList.find('h1').on('click', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
  alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
  $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 5000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
  <article class="post">_x000D_
    <h1>Title 1</h1>_x000D_
  </article>_x000D_
  <article class="post">_x000D_
    <h1>Title 2</h1>_x000D_
  </article>_x000D_
</section>
_x000D_
_x000D_
_x000D_

While this example displays the usage of event delegation to capture events for a specific node (h1 in this case), and issue a callback for such events.

_x000D_
_x000D_
$postList = $('#post-list');_x000D_
_x000D_
$postList.on('click', 'h1', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
  alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
  $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
  <article class="post">_x000D_
    <h1>Title 1</h1>_x000D_
  </article>_x000D_
  <article class="post">_x000D_
    <h1>Title 2</h1>_x000D_
  </article>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to validate phone numbers using regex

I believe the Number::Phone::US and Regexp::Common (particularly the source of Regexp::Common::URI::RFC2806) Perl modules could help.

The question should probably be specified in a bit more detail to explain the purpose of validating the numbers. For instance, 911 is a valid number in the US, but 911x isn't for any value of x. That's so that the phone company can calculate when you are done dialing. There are several variations on this issue. But your regex doesn't check the area code portion, so that doesn't seem to be a concern.

Like validating email addresses, even if you have a valid result you can't know if it's assigned to someone until you try it.

If you are trying to validate user input, why not normalize the result and be done with it? If the user puts in a number you can't recognize as a valid number, either save it as inputted or strip out undailable characters. The Number::Phone::Normalize Perl module could be a source of inspiration.

What is the maximum length of a String in PHP?

To properly answer this qustion you need to consider PHP internals or the target that PHP is built for.

To answer this from a typical Linux perspective on x86...

Sizes of types in C: https://usrmisc.wordpress.com/2012/12/27/integer-sizes-in-c-on-32-bit-and-64-bit-linux/

Types used in PHP for variables: http://php.net/manual/en/internals2.variables.intro.php

Strings are always 2GB as the length is always 32bits and a bit is wasted because it uses int rather than uint. int is impractical for lengths over 2GB as it requires a cast to avoid breaking arithmetic or "than" comparisons. The extra bit is likely being used for overflow checks.

Strangely, hash keys might internally support 4GB as uint is used although I have never put this to the test. PHP hash keys have a +1 to the length for a trailing null byte which to my knowledge gets ignored so it may need to be unsigned for that edge case rather than to allow longer keys.

A 32bit system may impose more external limits.

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

I reinstalled with the commmand: Install-Package EntityFramework -IncludePrerelease and the problem went away.

Cannot connect to repo with TortoiseSVN

Try clearing the settings under "Saved Data" - refer to:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html

This worked for me with Windows 7.

Eric

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

Angularjs -> ng-click and ng-show to show a div

Just get rid of the display: none; from your CSS. AngularJS is in control of showing/hiding that div.

If you want to hide it by default, just set the value of scope.myvalue to false initially - which you're already doing.

Removing specific rows from a dataframe

This boils down to two distinct steps:

  1. Figure out when your condition is true, and hence compute a vector of booleans, or, as I prefer, their indices by wrapping it into which()
  2. Create an updated data.frame by excluding the indices from the previous step.

Here is an example:

R> set.seed(42)
R> DF <- data.frame(sub=rep(1:4, each=4), day=sample(1:4, 16, replace=TRUE))
R> DF
   sub day
1    1   4
2    1   4
3    1   2
4    1   4
5    2   3
6    2   3
7    2   3
8    2   1
9    3   3
10   3   3
11   3   2
12   3   3
13   4   4
14   4   2
15   4   2
16   4   4
R> ind <- which(with( DF, sub==2 & day==3 ))
R> ind
[1] 5 6 7
R> DF <- DF[ -ind, ]
R> table(DF)
   day
sub 1 2 3 4
  1 0 1 0 3
  2 1 0 0 0
  3 0 1 3 0
  4 0 2 0 2
R> 

And we see that sub==2 has only one entry remaining with day==1.

Edit The compound condition can be done with an 'or' as follows:

ind <- which(with( DF, (sub==1 & day==2) | (sub=3 & day=4) ))

and here is a new full example

R> set.seed(1)
R> DF <- data.frame(sub=rep(1:4, each=5), day=sample(1:4, 20, replace=TRUE))
R> table(DF)
   day
sub 1 2 3 4
  1 1 2 1 1
  2 1 0 2 2
  3 2 1 1 1
  4 0 2 1 2
R> ind <- which(with( DF, (sub==1 & day==2) | (sub==3 & day==4) ))
R> ind
[1]  1  2 15
R> DF <- DF[-ind, ]
R> table(DF)
   day
sub 1 2 3 4
  1 1 0 1 1
  2 1 0 2 2
  3 2 1 1 0
  4 0 2 1 2
R> 

Append lines to a file using a StreamWriter

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();

How to debug (only) JavaScript in Visual Studio?

The debugger should automatically attach to the browser with Visual Studio 2012. You can use the debugger keyword to halt at a certain point in the application or use the breakpoints directly inside VS.

You can also detatch the default debugger in Visual Studio and use the Developer Tools which come pre loaded with Internet Explorer or FireBug etc.

To do this goto Visual Studio -> Debug -> Detatch All and then click Start debugging in Internet Explorer. You can then set breakpoints at this level. enter image description here

Html.ActionLink as a button or an image, not a link

Url.Action() will get you the bare URL for most overloads of Html.ActionLink, but I think that the URL-from-lambda functionality is only available through Html.ActionLink so far. Hopefully they'll add a similar overload to Url.Action at some point.

Best way to find os name and version in Unix/Linux platform

My own take at @kvivek's script, with more easily machine parsable output:

#!/bin/sh
# Outputs OS Name, Version & misc. info in a machine-readable way.
# See also NeoFetch for a more professional and elaborate bash script:
# https://github.com/dylanaraps/neofetch

SEP=","
PRINT_HEADER=false

print_help() {

    echo "`basename $0` - Outputs OS Name, Version & misc. info"
    echo "in a machine-readable way."
    echo
    echo "Usage:"
    echo "    `basename $0` [OPTIONS]"
    echo "Options:"
    echo "    -h, --help           print this help message"
    echo "    -n, --names          print a header line, naming the fields"
    echo "    -s, --separator SEP  overrides the default field-separator ('$SEP') with the supplied one"
}

# parse command-line args
while [ $# -gt 0 ]
do
    arg="$1"
    shift # past switch

    case "${arg}" in
        -h|--help)
            print_help
            exit 0
            ;;
        -n|--names)
            PRINT_HEADER=true
            ;;
        -s|--separator)
            SEP="$1"
            shift # past value
            ;;
        *) # non-/unknown option
            echo "Unknown switch '$arg'" >&2
            print_help
            ;;
    esac
done

OS=`uname -s`
DIST="N/A"
REV=`uname -r`
MACH=`uname -m`
PSUEDONAME="N/A"

GetVersionFromFile()
{
    VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}

if [ "${OS}" = "SunOS" ] ; then
    DIST=Solaris
    DIST_VER=`uname -v`
    # also: cat /etc/release
elif [ "${OS}" = "AIX" ] ; then
    DIST="${OS}"
    DIST_VER=`oslevel -r`
elif [ "${OS}" = "Linux" ] ; then
    if [ -f /etc/redhat-release ] ; then
        DIST='RedHat'
        PSUEDONAME=`sed -e 's/.*\(//' -e 's/\)//' /etc/redhat-release `
        DIST_VER=`sed -e 's/.*release\ //' -e 's/\ .*//' /etc/redhat-release `
    elif [ -f /etc/SuSE-release ] ; then
        DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
        DIST_VER=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
    elif [ -f /etc/mandrake-release ] ; then
        DIST='Mandrake'
        PSUEDONAME=`sed -e 's/.*\(//' -e 's/\)//' /etc/mandrake-release`
        DIST_VER=`sed -e 's/.*release\ //' -e 's/\ .*//' /etc/mandrake-release`
    elif [ -f /etc/debian_version ] ; then
        DIST="Debian"
        DIST_VER=`cat /etc/debian_version`
    PSUEDONAME=`lsb_release -a 2> /dev/null | grep '^Codename:' | sed -e 's/.*[[:space:]]//'`
    #elif [ -f /etc/gentoo-release ] ; then
        #TODO
    #elif [ -f /etc/slackware-version ] ; then
        #TODO
    elif [ -f /etc/issue ] ; then
        # We use this indirection because /etc/issue may look like
    # "Debian GNU/Linux 10 \n \l"
        ISSUE=`cat /etc/issue`
        ISSUE=`echo -e "${ISSUE}" | head -n 1 | sed -e 's/[[:space:]]\+$//'`
        DIST=`echo -e "${ISSUE}" | sed -e 's/[[:space:]].*//'`
        DIST_VER=`echo -e "${ISSUE}" | sed -e 's/.*[[:space:]]//'`
    fi
    if [ -f /etc/UnitedLinux-release ] ; then
        DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
    fi
    # NOTE `sed -e 's/.*(//' -e 's/).*//' /proc/version`
    #      is an option that worked ~ 2010 and earlier
fi

if $PRINT_HEADER
then
    echo "OS${SEP}Distribution${SEP}Distribution-Version${SEP}Pseudo-Name${SEP}Kernel-Revision${SEP}Machine-Architecture"
fi
echo "${OS}${SEP}${DIST}${SEP}${DIST_VER}${SEP}${PSUEDONAME}${SEP}${REV}${SEP}${MACH}"

NOTE: Only tested on Debian 11

Example Runs

No args

osInfo

output:

Linux,Debian,10.0,buster,4.19.0-5-amd64,x86_64

Header with names and custom separator

osInfo --names -s "\t| "

output:

OS  | Distribution  | Distribution-Version  | Pseudo-Name   | Kernel-Revision   | Machine-Architecture
Linux   | Debian    | 10.0  | buster    | 4.19.0-5-amd64    | x86_64

Filtered output

osInfo | awk -e 'BEGIN { FS=","; } { print $2 " " $3 " (" $4 ")" }'

output:

Debian 10.0 (buster)

Difference between "on-heap" and "off-heap"

from http://code.google.com/p/fast-serialization/wiki/QuickStartHeapOff

What is Heap-Offloading ?

Usually all non-temporary objects you allocate are managed by java's garbage collector. Although the VM does a decent job doing garbage collection, at a certain point the VM has to do a so called 'Full GC'. A full GC involves scanning the complete allocated Heap, which means GC pauses/slowdowns are proportional to an applications heap size. So don't trust any person telling you 'Memory is Cheap'. In java memory consumtion hurts performance. Additionally you may get notable pauses using heap sizes > 1 Gb. This can be nasty if you have any near-real-time stuff going on, in a cluster or grid a java process might get unresponsive and get dropped from the cluster.

However todays server applications (frequently built on top of bloaty frameworks ;-) ) easily require heaps far beyond 4Gb.

One solution to these memory requirements, is to 'offload' parts of the objects to the non-java heap (directly allocated from the OS). Fortunately java.nio provides classes to directly allocate/read and write 'unmanaged' chunks of memory (even memory mapped files).

So one can allocate large amounts of 'unmanaged' memory and use this to save objects there. In order to save arbitrary objects into unmanaged memory, the most viable solution is the use of Serialization. This means the application serializes objects into the offheap memory, later on the object can be read using deserialization.

The heap size managed by the java VM can be kept small, so GC pauses are in the millis, everybody is happy, job done.

It is clear, that the performance of such an off heap buffer depends mostly on the performance of the serialization implementation. Good news: for some reason FST-serialization is pretty fast :-).

Sample usage scenarios:

  • Session cache in a server application. Use a memory mapped file to store gigabytes of (inactive) user sessions. Once the user logs into your application, you can quickly access user-related data without having to deal with a database.
  • Caching of computational results (queries, html pages, ..) (only applicable if computation is slower than deserializing the result object ofc).
  • very simple and fast persistance using memory mapped files

Edit: For some scenarios one might choose more sophisticated Garbage Collection algorithms such as ConcurrentMarkAndSweep or G1 to support larger heaps (but this also has its limits beyond 16GB heaps). There is also a commercial JVM with improved 'pauseless' GC (Azul) available.

Bootstrap carousel multiple frames at once

Reference to above link i added 1 new thing called show 4 at time, slide one at a time for bootstrap 3 (v3.3.7)

CODEPLY:- https://www.codeply.com/go/eWUbGlspqU

LIVE SNIPPET

_x000D_
_x000D_
(function(){_x000D_
  $('#carousel123').carousel({ interval: 2000 });_x000D_
}());_x000D_
_x000D_
(function(){_x000D_
  $('.carousel-showmanymoveone .item').each(function(){_x000D_
    var itemToClone = $(this);_x000D_
_x000D_
    for (var i=1;i<4;i++) {_x000D_
      itemToClone = itemToClone.next();_x000D_
_x000D_
      // wrap around if at end of item collection_x000D_
      if (!itemToClone.length) {_x000D_
        itemToClone = $(this).siblings(':first');_x000D_
      }_x000D_
_x000D_
      // grab item, clone, add marker class, add to collection_x000D_
      itemToClone.children(':first-child').clone()_x000D_
        .addClass("cloneditem-"+(i))_x000D_
        .appendTo($(this));_x000D_
    }_x000D_
  });_x000D_
}());
_x000D_
body {_x000D_
    margin-top: 50px;_x000D_
}_x000D_
_x000D_
.carousel-showmanymoveone .carousel-control {_x000D_
  width: 4%;_x000D_
  background-image: none;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-control.left {_x000D_
  margin-left: 15px;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-control.right {_x000D_
  margin-right: 15px;_x000D_
}_x000D_
.carousel-showmanymoveone .cloneditem-1,_x000D_
.carousel-showmanymoveone .cloneditem-2,_x000D_
.carousel-showmanymoveone .cloneditem-3 {_x000D_
  display: none;_x000D_
}_x000D_
@media all and (min-width: 768px) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev {_x000D_
    left: -50%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .next {_x000D_
    left: 50%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .active {_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner .cloneditem-1 {_x000D_
    display: block;_x000D_
  }_x000D_
}_x000D_
@media all and (min-width: 768px) and (transform-3d), all and (min-width: 768px) and (-webkit-transform-3d) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.next {_x000D_
    -webkit-transform: translate3d(50%, 0, 0);_x000D_
            transform: translate3d(50%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev {_x000D_
    -webkit-transform: translate3d(-50%, 0, 0);_x000D_
            transform: translate3d(-50%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active {_x000D_
    -webkit-transform: translate3d(0, 0, 0);_x000D_
            transform: translate3d(0, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
}_x000D_
@media all and (min-width: 992px) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev {_x000D_
    left: -25%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .next {_x000D_
    left: 25%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .active {_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner .cloneditem-2,_x000D_
  .carousel-showmanymoveone .carousel-inner .cloneditem-3 {_x000D_
    display: block;_x000D_
  }_x000D_
}_x000D_
@media all and (min-width: 992px) and (transform-3d), all and (min-width: 992px) and (-webkit-transform-3d) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.next {_x000D_
    -webkit-transform: translate3d(25%, 0, 0);_x000D_
            transform: translate3d(25%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev {_x000D_
    -webkit-transform: translate3d(-25%, 0, 0);_x000D_
            transform: translate3d(-25%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active {_x000D_
    -webkit-transform: translate3d(0, 0, 0);_x000D_
            transform: translate3d(0, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<div class="carousel carousel-showmanymoveone slide" id="carousel123">_x000D_
 <div class="carousel-inner">_x000D_
  <div class="item active">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/0054A6/fff/&amp;text=1" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002d5a/fff/&amp;text=2" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/d6d6d6/333&amp;text=3" class="img-responsive"></a></div>_x000D_
  </div>          _x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002040/eeeeee&amp;text=4" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/0054A6/fff/&amp;text=5" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002d5a/fff/&amp;text=6" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/eeeeee&amp;text=7" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/40a1ff/002040&amp;text=8" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <a class="left carousel-control" href="#carousel123" data-slide="prev"><i class="glyphicon glyphicon-chevron-left"></i></a>_x000D_
 <a class="right carousel-control" href="#carousel123" data-slide="next"><i class="glyphicon glyphicon-chevron-right"></i></a>_x000D_
</div>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
_x000D_
_x000D_
_x000D_

Round to 2 decimal places

Don't use doubles. You can lose some precision. Here's a general purpose function.

public static double round(double unrounded, int precision, int roundingMode)
{
    BigDecimal bd = new BigDecimal(unrounded);
    BigDecimal rounded = bd.setScale(precision, roundingMode);
    return rounded.doubleValue();
}

You can call it with

round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);

"precision" being the number of decimal points you desire.

How to remove the last character from a bash grep output

don't have to chain so many tools. Just one awk command does the job

 COMPANY_NAME=$(awk -F"=" '/company_name/{gsub(/;$/,"",$2) ;print $2}' file.txt)

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Use SET STATISTICS TIME ON

above your query.

Below near result tab you can see a message tab. There you can see the time.

What's the difference between a single precision and double precision floating point operation?

Double precision means the numbers takes twice the word-length to store. On a 32-bit processor, the words are all 32 bits, so doubles are 64 bits. What this means in terms of performance is that operations on double precision numbers take a little longer to execute. So you get a better range, but there is a small hit on performance. This hit is mitigated a little by hardware floating point units, but its still there.

The N64 used a MIPS R4300i-based NEC VR4300 which is a 64 bit processor, but the processor communicates with the rest of the system over a 32-bit wide bus. So, most developers used 32 bit numbers because they are faster, and most games at the time did not need the additional precision (so they used floats not doubles).

All three systems can do single and double precision floating operations, but they might not because of performance. (although pretty much everything after the n64 used a 32 bit bus so...)

How to create a Custom Dialog box in android?

Simplest way to change the background color and text style is to make custom theme for android alert dialog as below :-

: Just put below code to styles.xml :

    <style name="AlertDialogCustom" parent="@android:style/Theme.Dialog">
    <item name="android:textColor">#999999</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
    <item name="android:typeface">monospace</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:textSize">@dimen/abc_text_size_medium_material</item>
    <item name="android:background">#80ff00ff</item>
</style>

: Now customization thing is done , now just apply to your alertBuilder object :

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this,R.style.AlertDialogCustom);

Hope , this will help you !

android on Text Change Listener

Another solution that may help someone. There are 2 EditText which change instead of each other after editing. By default, it led to cyclicity.

use variable:

Boolean uahEdited = false;
Boolean usdEdited = false;

add TextWatcher

uahEdit = findViewById(R.id.uahEdit);
usdEdit = findViewById(R.id.usdEdit);

uahEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!usdEdited) {
                uahEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = uahEdit.getText().toString();

            if(!tmp.isEmpty() && uahEdited) {
                uah = Double.valueOf(tmp);
                usd = uah / 27;
                usdEdit.setText(String.valueOf(usd));
            } else if (tmp.isEmpty()) {
                usdEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            uahEdited = false;
        }
    });

usdEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!uahEdited) {
                usdEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = usdEdit.getText().toString();

            if (!tmp.isEmpty() && usdEdited) {
                usd = Double.valueOf(tmp);
                uah = usd * 27;
                uahEdit.setText(String.valueOf(uah));
            } else if (tmp.isEmpty()) {
                uahEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            usdEdited = false;
        }
    });

Don't criticize too much. I am a novice developer

pass parameter by link_to ruby on rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

How to scroll to an element inside a div?

Native JS, Cross Browser, Smooth Scroll (Update 2020)

Setting ScrollTop does give the desired result but the scroll is very abrupt. Using jquery to have smooth scroll was not an option. So here's a native way to get the job done that supports all major browsers. Reference - caniuse

// get the "Div" inside which you wish to scroll (i.e. the container element)
const El = document.getElementById('xyz');

// Lets say you wish to scroll by 100px, 
El.scrollTo({top: 100, behavior: 'smooth'});

// If you wish to scroll until the end of the container
El.scrollTo({top: El.scrollHeight, behavior: 'smooth'});

That's it!


And here's a working snippet for the doubtful -

_x000D_
_x000D_
document.getElementById('btn').addEventListener('click', e => {
  e.preventDefault();
  // smooth scroll
  document.getElementById('container').scrollTo({top: 175, behavior: 'smooth'});
});
_x000D_
/* just some styling for you to ignore */
.scrollContainer {
  overflow-y: auto;
  max-height: 100px;
  position: relative;
  border: 1px solid red;
  width: 120px;
}

body {
  padding: 10px;
}

.box {
  margin: 5px;
  background-color: yellow;
  height: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}

#goose {
  background-color: lime;
}
_x000D_
<!-- Dummy html to be ignored -->
<div id="container" class="scrollContainer">
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div id="goose" class="box">goose</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
</div>

<button id="btn">goose</button>
_x000D_
_x000D_
_x000D_

Update: As you can perceive in the comments, it seems that Element.scrollTo() is not supported in IE11. So if you don't care about IE11 (you really shouldn't), feel free to use this in all your projects. Note that support exists for Edge! So you're not really leaving your Edge/Windows users behind ;)

Reference

ValueError : I/O operation on closed file

I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with block, and then it stopped happening.

How can I read and manipulate CSV file data in C++?

Using boost tokenizer to parse records, see here for more details.

ifstream in(data.c_str());
if (!in.is_open()) return 1;

typedef tokenizer< escaped_list_separator<char> > Tokenizer;

vector< string > vec;
string line;

while (getline(in,line))
{
    Tokenizer tok(line);
    vec.assign(tok.begin(),tok.end());

    /// do something with the record
    if (vec.size() < 3) continue;

    copy(vec.begin(), vec.end(),
         ostream_iterator<string>(cout, "|"));

    cout << "\n----------------------" << endl;
}

Pull all images from a specified directory and then display them

You need to change the loop from for ($i=1; $i<count($files); $i++) to for ($i=0; $i<count($files); $i++):

So the correct code is

<?php
$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print $image ."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}

?>

How can I create a simple index.html file which lists all files/directories?

This can't be done with pure HTML.

However if you have access to PHP on the Apache server (you tagged the post "apache") it can be done easilly - se the PHP glob function. If not - you might try Server Side Include - it's an Apache thing, and I don't know much about it.

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

Debug vs Release in CMake

Instead of manipulating the CMAKE_CXX_FLAGS strings directly (which could be done more nicely using string(APPEND CMAKE_CXX_FLAGS_DEBUG " -g3") btw), you can use add_compiler_options:

add_compile_options(
  "-Wall" "-Wpedantic" "-Wextra" "-fexceptions"
  "$<$<CONFIG:DEBUG>:-O0;-g3;-ggdb>"
)

This would add the specified warnings to all build types, but only the given debugging flags to the DEBUG build. Note that compile options are stored as a CMake list, which is just a string separating its elements by semicolons ;.

Fatal error: Call to a member function prepare() on null

@delato468 comment must be listed as a solution as it worked for me.

In addition to defining the parameter, the user must pass it too at the time of calling the function

fetch_data(PDO $pdo, $cat_id)

How to set initial value and auto increment in MySQL?

With CREATE TABLE statement

CREATE TABLE my_table (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL,
  PRIMARY KEY (id)
) AUTO_INCREMENT = 100;

or with ALTER TABLE statement

ALTER TABLE my_table AUTO_INCREMENT = 200;

How can I iterate through a string and also know the index (current position)?

You can use standard STL function distance as mentioned before

index = std::distance(s.begin(), it);

Also, you can access string and some other containers with the c-like interface:

for (i=0;i<string1.length();i++) string1[i];

Bootstrap date time picker

Try This:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>_x000D_
  <script src="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
      <div class='col-sm-6'>_x000D_
        <div class="form-group">_x000D_
          <div class='input-group date' id='datetimepicker1'>_x000D_
            <input type='text' class="form-control" />_x000D_
            <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
            </span>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <script type="text/javascript">_x000D_
        $(function() {_x000D_
          $('#datetimepicker1').datetimepicker();_x000D_
        });_x000D_
      </script>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

What issues should be considered when overriding equals and hashCode in Java?

A clarification about the obj.getClass() != getClass().

This statement is the result of equals() being inheritance unfriendly. The JLS (Java language specification) specifies that if A.equals(B) == true then B.equals(A) must also return true. If you omit that statement inheriting classes that override equals() (and change its behavior) will break this specification.

Consider the following example of what happens when the statement is omitted:

    class A {
      int field1;

      A(int field1) {
        this.field1 = field1;
      }

      public boolean equals(Object other) {
        return (other != null && other instanceof A && ((A) other).field1 == field1);
      }
    }

    class B extends A {
        int field2;

        B(int field1, int field2) {
            super(field1);
            this.field2 = field2;
        }

        public boolean equals(Object other) {
            return (other != null && other instanceof B && ((B)other).field2 == field2 && super.equals(other));
        }
    }    

Doing new A(1).equals(new A(1)) Also, new B(1,1).equals(new B(1,1)) result give out true, as it should.

This looks all very good, but look what happens if we try to use both classes:

A a = new A(1);
B b = new B(1,1);
a.equals(b) == true;
b.equals(a) == false;

Obviously, this is wrong.

If you want to ensure the symmetric condition. a=b if b=a and the Liskov substitution principle call super.equals(other) not only in the case of B instance, but check after for A instance:

if (other instanceof B )
   return (other != null && ((B)other).field2 == field2 && super.equals(other)); 
if (other instanceof A) return super.equals(other); 
   else return false;

Which will output:

a.equals(b) == true;
b.equals(a) == true;

Where, if a is not a reference of B, then it might be a be a reference of class A (because you extend it), in this case you call super.equals() too.

Disable ONLY_FULL_GROUP_BY

Im working with mysql and registered with root user, the solution that work for me is the following:

mysql > SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

Using wget to recursively fetch a directory with arbitrary files in it

You should be able to do it simply by adding a -r

wget -r http://stackoverflow.com/

How to display with n decimal places in Matlab

You can convert a number to a string with n decimal places using the SPRINTF command:

>> x = 1.23;
>> sprintf('%0.6f', x)

ans =

1.230000

>> x = 1.23456789;
>> sprintf('%0.6f', x)

ans =

1.234568

How do I find the install time and date of Windows?

Determine the Windows Installation Date with WMIC

wmic os get installdate

How to execute a Windows command on a remote PC?

This can be done by using PsExec which can be downloaded here

psexec \\computer_name -u username -p password ipconfig

If this isn't working try doing this :-

  1. Open RegEdit on your remote server.
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.

  3. Add a new DWORD value called LocalAccountTokenFilterPolicy

  4. Set its value to 1.
  5. Reboot your remote server.
  6. Try running PSExec again from your local server.

CSS @media print issues with background-color;

If you don't mind using an image instead of a background color(or possibly an image with your background color) the solution below has worked for me in FireFox,Chrome and even IE without any over-rides. Set the image somewhere on the page and hide it until the user prints.

The html on the page with the background image

<img src="someImage.png" class="background-print-img">

The Css

.background-print-img{
    display: none;
}

@media print{
    .background-print-img{
        background:red;
        display: block;
        width:100%;
        height:100%;
        position:absolute;
        left:0;
        top:0;
        z-index:-10;
    }

}

Set variable in jinja

Just Set it up like this

{% set active_link = recordtype -%}

How do I create a datetime in Python from milliseconds?

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

Non-invocable member cannot be used like a method?

I had the same issue and realized that removing the parentheses worked. Sometimes having someone else read your code can be useful if you have been the only one working on it for some time.

E.g.

  cmd.CommandType = CommandType.Text(); 

Replace: cmd.CommandType = CommandType.Text;

RESTful call in Java

Indeed, this is "very complicated in Java":

From: https://jersey.java.net/documentation/latest/client.html

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://foo").path("bar");
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();

Capitalize or change case of an NSString in Objective-C

Here ya go:

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];

Btw:
"april" is lowercase ? [NSString lowercaseString]
"APRIL" is UPPERCASE ? [NSString uppercaseString]
"April May" is Capitalized/Word Caps ? [NSString capitalizedString]
"April may" is Sentence caps ? (method missing; see workaround below)

Hence what you want is called "uppercase", not "capitalized". ;)

As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

@interface NSString ()

- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences

@end

@implementation NSString

- (NSString *)sentenceCapitalizedString {
    if (![self length]) {
        return [NSString string];
    }
    NSString *uppercase = [[self substringToIndex:1] uppercaseString];
    NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
    return [uppercase stringByAppendingString:lowercase];
}

- (NSString *)realSentenceCapitalizedString {
    __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationBySentences
                          usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
        [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
    }];
    return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}

@end

How to disable and then enable onclick event on <div> with javascript

I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:

$("#id").on('click', function(){ //enables click event
    //do your thing here
});

$("#id").off('click'); //disables click event

If you want to disable a div, use the following code:

$("#id").attr('disabled','disabled');

Hope this helps.

edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

For me, after I've removed Xcode, I have to switch active developer path as follows: sudo xcode-select -s /

Hiding an Excel worksheet with VBA

To hide from the UI, use Format > Sheet > Hide

To hide programatically, use the Visible property of the Worksheet object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.

ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden 
' or xlSheetHidden or xlSheetVisible

You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).

How to print variables in Perl

How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids, but Perl complains.

Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open returned an error, and make sure you are using use strict; use warnings;.

my ($ids, $nIds) is a list, right? With two elements?

It's a (very special) function call. $ids,$nIds is a list with two elements.

How to get response using cURL in PHP

Just use the below piece of code to get the response from restful web service url, I use social mention url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    ); 

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

Accessing the last entry in a Map

Find missing all elements from array
        int[] array = {3,5,7,8,2,1,32,5,7,9,30,5};
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int i=0;i<array.length;i++) {
            map.put(array[i], 1);
        }
        int maxSize = map.lastKey();
        for(int j=0;j<maxSize;j++) {
            if(null == map.get(j))
                System.out.println("Missing `enter code here`No:"+j);
        }

What is the difference between <section> and <div>?

Just an observation - haven't found any documentation corroborating this

If a section contains another section, a h1-header in the inner section is displayed in a smaller font than a h1- header in outer section. When using div instead of section the inner div h1-header is diplayed as h1.

<section>
  <h1>Level1</h1>
  some text
  <section>
    <h1>Level2</h1>
    some more text
  </section>
</section>

-- the Level2 - header is displayed in a smaller font than the Level1 - header.

When using css to color h1 header, the inner h1 were also colored (behaves as regular h1). It's the same behaviour in Firefox 18, IE 10 and Chrome 28.

Insert the same fixed value into multiple rows

To create a new empty column and fill it with the same value (here 100) for every row (in Toad for Oracle):

ALTER TABLE my_table ADD new_column INT;
UPDATE my_table SET new_column = 100;

Padding characters in printf

I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.

Just substrings and the ${#...} meta-variable.

A="[>---------------------<]";

# Strip excess padding from the right
#

B="A very long header"; echo "${A:0:-${#B}} $B"
B="shrt hdr"          ; echo "${A:0:-${#B}} $B"

Produces

[>----- A very long header
[>--------------- shrt hdr


# Strip excess padding from the left
#

B="A very long header"; echo "${A:${#B}} $B"
B="shrt hdr"          ; echo "${A:${#B}} $B"

Produces

-----<] A very long header
---------------<] shrt hdr

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

How to add a line break within echo in PHP?

You may want to try \r\n for carriage return / line feed

WPF: ItemsControl with scrollbar (ScrollViewer)

Put your ScrollViewer in a DockPanel and set the DockPanel MaxHeight property

[...]
<DockPanel MaxHeight="700">
  <ScrollViewer VerticalScrollBarVisibility="Auto">
   <ItemsControl ItemSource ="{Binding ...}">
     [...]
   </ItemsControl>
  </ScrollViewer>
</DockPanel>
[...]

How to perform a sum of an int[] array

Once is out (March 2014) you'll be able to use streams:

int sum = IntStream.of(a).sum();

or even

int sum = IntStream.of(a).parallel().sum();

Capture screenshot of active window?

Based on ArsenMkrt's reply, but this one allows you to capture a control in your form (I'm writing a tool for example that has a WebBrowser control in it and want to capture just its display). Note the use of PointToScreen method:

//Project: WebCapture
//Filename: ScreenshotUtils.cs
//Author: George Birbilis (http://zoomicon.com)
//Version: 20130820

using System.Drawing;
using System.Windows.Forms;

namespace WebCapture
{
  public static class ScreenshotUtils
  {

    public static Rectangle Offseted(this Rectangle r, Point p)
    {
      r.Offset(p);
      return r;
    }

    public static Bitmap GetScreenshot(this Control c)
    {
      return GetScreenshot(new Rectangle(c.PointToScreen(Point.Empty), c.Size));
    }

    public static Bitmap GetScreenshot(Rectangle bounds)
    {
      Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
      using (Graphics g = Graphics.FromImage(bitmap))
        g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
      return bitmap;
    }

    public const string DEFAULT_IMAGESAVEFILEDIALOG_TITLE = "Save image";
    public const string DEFAULT_IMAGESAVEFILEDIALOG_FILTER = "PNG Image (*.png)|*.png|JPEG Image (*.jpg)|*.jpg|Bitmap Image (*.bmp)|*.bmp|GIF Image (*.gif)|*.gif";

    public const string CUSTOMPLACES_COMPUTER = "0AC0837C-BBF8-452A-850D-79D08E667CA7";
    public const string CUSTOMPLACES_DESKTOP = "B4BFCC3A-DB2C-424C-B029-7FE99A87C641";
    public const string CUSTOMPLACES_DOCUMENTS = "FDD39AD0-238F-46AF-ADB4-6C85480369C7";
    public const string CUSTOMPLACES_PICTURES = "33E28130-4E1E-4676-835A-98395C3BC3BB";
    public const string CUSTOMPLACES_PUBLICPICTURES = "B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5";
    public const string CUSTOMPLACES_RECENT = "AE50C081-EBD2-438A-8655-8A092E34987A";

    public static SaveFileDialog GetImageSaveFileDialog(
      string title = DEFAULT_IMAGESAVEFILEDIALOG_TITLE, 
      string filter = DEFAULT_IMAGESAVEFILEDIALOG_FILTER)
    {
      SaveFileDialog dialog = new SaveFileDialog();

      dialog.Title = title;
      dialog.Filter = filter;


      /* //this seems to throw error on Windows Server 2008 R2, must be for Windows Vista only
      dialog.CustomPlaces.Add(CUSTOMPLACES_COMPUTER);
      dialog.CustomPlaces.Add(CUSTOMPLACES_DESKTOP);
      dialog.CustomPlaces.Add(CUSTOMPLACES_DOCUMENTS);
      dialog.CustomPlaces.Add(CUSTOMPLACES_PICTURES);
      dialog.CustomPlaces.Add(CUSTOMPLACES_PUBLICPICTURES);
      dialog.CustomPlaces.Add(CUSTOMPLACES_RECENT);
      */

      return dialog;
    }

    public static void ShowSaveFileDialog(this Image image, IWin32Window owner = null)
    {
      using (SaveFileDialog dlg = GetImageSaveFileDialog())
        if (dlg.ShowDialog(owner) == DialogResult.OK)
          image.Save(dlg.FileName);
    }

  }
}

Having the Bitmap object you can just call Save on it

private void btnCapture_Click(object sender, EventArgs e)
{
  webBrowser.GetScreenshot().Save("C://test.jpg", ImageFormat.Jpeg);
}

The above assumes the GC will grab the bitmap, but maybe it's better to assign the result of someControl.getScreenshot() to a Bitmap variable, then dispose that variable manually when finished with each image, especially if you're doing this grabbing often (say you have a list of webpages you want to load and save screenshots of them):

private void btnCapture_Click(object sender, EventArgs e)
{
  Bitmap bitmap = webBrowser.GetScreenshot();
  bitmap.ShowSaveFileDialog();
  bitmap.Dispose(); //release bitmap resources
}

Even better, could employ a using clause, which has the added benefit of releasing the bitmap resources even in case of an exception occuring inside the using (child) block:

private void btnCapture_Click(object sender, EventArgs e)
{
  using(Bitmap bitmap = webBrowser.GetScreenshot())
    bitmap.ShowSaveFileDialog();
  //exit from using block will release bitmap resources even if exception occured
}

Update:

Now WebCapture tool is ClickOnce-deployed (http://gallery.clipflair.net/WebCapture) from the web (also has nice autoupdate support thanks to ClickOnce) and you can find its source code at https://github.com/Zoomicon/ClipFlair/tree/master/Server/Tools/WebCapture

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

python dataframe pandas drop column using int

Since there can be multiple columns with same name , we should first rename the columns. Here is code for the solution.

df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns

Detecting which UIButton was pressed in a UITableView

It works for me aswell, Thanks @Cocoanut

I found the method of using the superview's superview to obtain a reference to the cell's indexPath worked perfectly. Thanks to iphonedevbook.com (macnsmith) for the tip link text

-(void)buttonPressed:(id)sender {
 UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
 NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell];
...

}

How to make fixed header table inside scrollable div?

I needed the same and this solution worked the most simple and straightforward way:

http://www.farinspace.com/jquery-scrollable-table-plugin/

I just give an id to the table I want to scroll and put one line in Javascript. That's it!

By the way, first I also thought I want to use a scrollable div, but it is not necessary at all. You can use a div and put it into it, but this solution does just what we need: scrolls the table.

Notification Icon with the new Firebase Cloud Messaging system

Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.

With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:

<meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/google_blue" />

Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.

Generate a range of dates using SQL

I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.

print("code sample");

select  top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select  1 as A union
select  2 union
select  3 union
select  4 union
select  5 union
select  6 union
select  7 union
select  8 union
select  9 union
select  10 union
select  11 union
select  12 union
select  13 union
select  14 union
select  15 union
select  16 union
select  17 union
select  18 union
select  19 union
select  20 union
select  21 
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");

How to convert a boolean array to an int array

A funny way to do this is

>>> np.array([True, False, False]) + 0 
np.array([1, 0, 0])

Node JS Error: ENOENT

To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".

The path

/tmp/test.jpg

thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.

./tmp/test.jpg = tmp/test.jpg

Java : Accessing a class within a package, which is the better way?

Import package is for better readability;

Fully qualified class has to be used in special scenarios. For example, same class name in different package, or use reflect such as Class.forName().

Plotting time-series with Date labels on x-axis

I like using the ggplot2 for this sort of thing:

df$Date <- as.Date( df$Date, '%m/%d/%Y')
require(ggplot2)
ggplot( data = df, aes( Date, Visits )) + geom_line() 

enter image description here

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

Iterator invalidation rules

C++17 (All references are from the final working draft of CPP17 - n4659)


Insertion

Sequence Containers

  • vector: The functions insert, emplace_back, emplace, push_back cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
    With respect to the reserve function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). [26.3.11.3/6]

  • deque: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]

  • list: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
    The insert, emplace_front, emplace_back, emplace, push_front, push_back functions are covered under this rule.

  • forward_list: None of the overloads of insert_after shall affect the validity of iterators and references [26.3.9.5/1]

  • array: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.

Associative Containers

  • All Associative Containers: The insert and emplace members shall not affect the validity of iterators and references to the container [26.2.6/9]

Unordered Associative Containers

  • All Unordered Associative Containers: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
    The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
    The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. [26.2.7/15]

  • All Unordered Associative Containers: In case of a merge operation (e.g., a.merge(a2)), iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid. (Table 91 — Unordered associative container requirements)

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence Containers

  • vector: The functions erase and pop_back invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]

  • deque: An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque. [ Note: pop_front and pop_back are erase operations. —end note ] [26.3.8.4/4]

  • list: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase, pop_front, pop_back, clear functions.
    remove and remove_if member functions: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version of unique with no arguments) or pred(*i, *(i - 1)) (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]

  • forward_list: erase_after shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
    remove and remove_if member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version with no arguments) or pred(*i, *(i - 1)) (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]

  • All Sequence Containers: clear invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list, clear does not invalidate past-the-end iterators. [26.3.9.5/32]

  • All Sequence Containers: assign invalidates all references, pointers and iterators referring to the elements of the container. For vector and deque, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)

Associative Containers

  • All Associative Containers: The erase members shall invalidate only iterators and references to the erased elements [26.2.6/9]

  • All Associative Containers: The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

General container requirements relating to iterator invalidation:

  • Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]

  • no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]

As examples of the above requirements:

  • transform algorithm: The op and binary_op functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]

  • accumulate algorithm: In the range [first, last], binary_op shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]

  • reduce algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]

and so on...

Can I dynamically add HTML within a div tag from C# on load event?

You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?

I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.

Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.

Angular: Cannot find a differ supporting object '[object Object]'

Missing square brackets around input property may cause this error. For example:

Component Foo {
    @Input()
    bars: BarType[];
}

Correct:

<app-foo [bars]="smth"></app-foo>

Incorrect (triggering error):

<app-foo bars="smth"></app-foo>

How to change color of the back arrow in the new material theme?

Unless there's a better solution...

What I did is to take the @drawable/abc_ic_ab_back_mtrl_am_alpha images, which seem to be white, and paint them in the color I desire using a photo editor.

Hibernate Criteria Query to get specific columns

You can use JPQL as well as JPA Criteria API for any kind of DTO projection(Mapping only selected columns to a DTO class) . Look at below code snippets showing how to selectively select various columns instead of selecting all columns . These example also show how to select various columns from joining multiple columns . I hope this helps .

JPQL code :

String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
                + "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
                + " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
                + " si.name, sv.vehicleNumber , svd.name) ";

        List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
                "select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
                        + " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
                        + " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
                        + " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
                CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);

        if (Objects.nonNull(instructors))
            instructors.forEach(i -> i.setName("Latest Update"));

        DataPrinters.listDataPrinter.accept(instructors);

JPA Criteria API code :

@Test
    public void fetchFullDataWithCriteria() {
        CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
        CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);

        // prepare from expressions
        Root<Instructor> root = cq.from(Instructor.class);
        Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
        Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
        Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
        Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
        Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
        Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);

        // prepare select expressions.
        CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
                root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
                insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
                insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
                insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
                studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));

        // prepare where expressions.
        Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
        Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
        Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);

        // prepare orderBy expressions.
        List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
                cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(vehicleDocumentJoin.get(Document_.name)));

        // prepare query
        cq.select(selection).where(where).orderBy(orderBy);
        DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));

    }

Split (explode) pandas dataframe string entry to separate rows

TL;DR

import pandas as pd
import numpy as np

def explode_str(df, col, sep):
    s = df[col]
    i = np.arange(len(s)).repeat(s.str.count(sep) + 1)
    return df.iloc[i].assign(**{col: sep.join(s).split(sep)})

def explode_list(df, col):
    s = df[col]
    i = np.arange(len(s)).repeat(s.str.len())
    return df.iloc[i].assign(**{col: np.concatenate(s)})

Demonstration

explode_str(a, 'var1', ',')

  var1  var2
0    a     1
0    b     1
0    c     1
1    d     2
1    e     2
1    f     2

Let's create a new dataframe d that has lists

d = a.assign(var1=lambda d: d.var1.str.split(','))

explode_list(d, 'var1')

  var1  var2
0    a     1
0    b     1
0    c     1
1    d     2
1    e     2
1    f     2

General Comments

I'll use np.arange with repeat to produce dataframe index positions that I can use with iloc.

FAQ

Why don't I use loc?

Because the index may not be unique and using loc will return every row that matches a queried index.

Why don't you use the values attribute and slice that?

When calling values, if the entirety of the the dataframe is in one cohesive "block", Pandas will return a view of the array that is the "block". Otherwise Pandas will have to cobble together a new array. When cobbling, that array must be of a uniform dtype. Often that means returning an array with dtype that is object. By using iloc instead of slicing the values attribute, I alleviate myself from having to deal with that.

Why do you use assign?

When I use assign using the same column name that I'm exploding, I overwrite the existing column and maintain its position in the dataframe.

Why are the index values repeat?

By virtue of using iloc on repeated positions, the resulting index shows the same repeated pattern. One repeat for each element the list or string.
This can be reset with reset_index(drop=True)


For Strings

I don't want to have to split the strings prematurely. So instead I count the occurrences of the sep argument assuming that if I were to split, the length of the resulting list would be one more than the number of separators.

I then use that sep to join the strings then split.

def explode_str(df, col, sep):
    s = df[col]
    i = np.arange(len(s)).repeat(s.str.count(sep) + 1)
    return df.iloc[i].assign(**{col: sep.join(s).split(sep)})

For Lists

Similar as for strings except I don't need to count occurrences of sep because its already split.

I use Numpy's concatenate to jam the lists together.

import pandas as pd
import numpy as np

def explode_list(df, col):
    s = df[col]
    i = np.arange(len(s)).repeat(s.str.len())
    return df.iloc[i].assign(**{col: np.concatenate(s)})

An App ID with Identifier '' is not available. Please enter a different string

I got solution for this kind of problem by selecting this option at the time of build export.

enter image description here

Regularly I select second option for build export process but after installing Xcode 7.3 when I try to export build at that time I receive above error. After some sort of forum discussion, I conclude that I need to select last option now to export build.

I hope this information become helpful to other members of forum as well.

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Password encryption at client side

I've listed a complete JavaScript for creating an MD5 at the bottom but it's really pointless without a secure connection for several reasons.

If you MD5 the password and store that MD5 in your database then the MD5 is the password. People can tell exactly what's in your database. You've essentially just made the password a longer string but it still isn't secure if that's what you're storing in your database.

If you say, "Well I'll MD5 the MD5" you're missing the point. By looking at the network traffic, or looking in your database, I can spoof your website and send it the MD5. Granted this is a lot harder than just reusing a plain text password but it's still a security hole.

Most of all though you can't salt the hash client side without sending the salt over the 'net unencrypted therefore making the salting pointless. Without a salt or with a known salt I can brute force attack the hash and figure out what the password is.

If you are going to do this kind of thing with unencrypted transmissions you need to use a public key/private key encryption technique. The client encrypts using your public key then you decrypt on your end with your private key then you MD5 the password (using a user unique salt) and store it in your database. Here's a JavaScript GPL public/private key library.

Anyway, here is the JavaScript code to create an MD5 client side (not my code):

/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/

var MD5 = function (string) {

    function RotateLeft(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    }

    function AddUnsigned(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }

    function F(x,y,z) { return (x & y) | ((~x) & z); }
    function G(x,y,z) { return (x & z) | (y & (~z)); }
    function H(x,y,z) { return (x ^ y ^ z); }
    function I(x,y,z) { return (y ^ (x | (~z))); }

    function FF(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;

    string = Utf8Encode(string);

    x = ConvertToWordArray(string);

    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

    for (k=0;k<x.length;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=AddUnsigned(a,AA);
        b=AddUnsigned(b,BB);
        c=AddUnsigned(c,CC);
        d=AddUnsigned(d,DD);
    }

    var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);

    return temp.toLowerCase();
}

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

The steps to apply a theme are fairly simple. To really understand how everything works together, you'll need to understand what the ASP.NET MVC 5 template is providing out of the box and how you can customize it for your needs.

Note: If you have a basic understanding of how the MVC 5 template works, scroll down to the theming section.


ASP.NET MVC 5 Template: How it works

This walk-through goes over how to create an MVC 5 project and what's going on under the hood. See all the features of MVC 5 Template in this blog.

  1. Create a new project. Under Templates Choose Web > ASP.NET Web Application. Enter a name for your project and click OK.

  2. On the next wizard, choose MVC and click OK. This will apply the MVC 5 template.

    Example of choosing MVC Template

  3. The MVC 5 template creates an MVC application that uses Bootstrap to provide responsive design and theming features. Under the hood, the template includes a bootstrap 3.* nuget package that installs 4 files: bootstrap.css, bootstrap.min.css, bootstrap.js, and bootstrap.min.js.

    Example of installed css and js

  4. Bootstrap is bundled in your application by using the Web Optimization feature. Inspect Views/Shared/_Layout.cshtml and look for

    @Styles.Render("~/Content/css")
    

    and

    @Scripts.Render("~/bundles/bootstrap") 
    

    These two paths refer to bundles set up in App_Start/BundleConfig.cs:

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
        "~/Scripts/bootstrap.js",
        "~/Scripts/respond.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
        "~/Content/bootstrap.css",
        "~/Content/site.css"));
    
  5. This is what makes it possible to run your application without any configuring up front. Try running your project now.

    Default Application Running


Applying Bootstrap Themes in ASP.NET MVC 5

This walk-through covers how to apply bootstrap themes in an MVC 5 project

  1. First, download the css of the theme you'd like to apply. For this example, I'll be using Bootswatch's Flatly. Include the downloaded flatly.bootstrap.css and flatly.bootstrap.min.css in the Content folder (be sure to Include in Project as well).
  2. Open App_Start/BundleConfig.cs and change the following:

    bundles.Add(new StyleBundle("~/Content/css").Include(
        "~/Content/bootstrap.css",
        "~/Content/site.css"));
    

    to include your new theme:

    bundles.Add(new StyleBundle("~/Content/css").Include(
        "~/Content/flatly.bootstrap.css",
        "~/Content/site.css"));
    
  3. If you're using the default _Layout.cshtml included in the MVC 5 template, you can skip to step 4. If not, as a bare minimum, include these two line in your layout along with your Bootstrap HTML template:

    In your <head>:

    @Styles.Render("~/Content/css")
    

    Last line before closing </body>:

    @Scripts.Render("~/bundles/bootstrap")
    
  4. Try running your project now. You should see your newly created application now using your theme.

    Default template using flatly theme


Resources

Check out this awesome 30 day walk-through guide by James Chambers for more information, tutorials, tips and tricks on how to use Twitter Bootstrap with ASP.NET MVC 5.

How to register ASP.NET 2.0 to web server(IIS7)?

I got it resolved by doing Repir on .NET framework Extended, in Add/Remove program ;

Using win2008R2, .NET framework 4.0

How to position a CSS triangle using ::after?

Just add position:relative to the parent element .sidebar-resources-categories

http://jsfiddle.net/matthewabrman/5msuY/

explanation: the ::after elements position is based off of it's parent, in your example you probably had a parent element of the .sidebar-res... which had a set height, therefore it rendered just below it. Adding position relative to the .sidebar-res... makes the after elements move to 100% of it's parent which now becomes the .sidebar-res... because it's position is set to relative. I'm not sure how to explain it but it's expected behaviour.

read more on the subject: http://css-tricks.com/absolute-positioning-inside-relative-positioning/

CURL and HTTPS, "Cannot resolve host"

I had the same problem. Coudn't resolve google.com. There was a bug somewhere in php fpm, which i am using. Restarting php-fpm solved it for me.

Show hide divs on click in HTML and CSS without jQuery

Of course! jQuery is just a library that utilizes javascript after all.

You can use document.getElementById to get the element in question, then change its height accordingly, through element.style.height.

elementToChange = document.getElementById('collapseableEl');
elementToChange.style.height = '100%';

Wrap that up in a neat little function that caters for toggling back and forth and you have yourself a solution.

Disable / Check for Mock Location (prevent gps spoofing)

try this code its very simple and usefull

  public boolean isMockLocationEnabled() {
        boolean isMockLocation = false;
        try {
            //if marshmallow
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                AppOpsManager opsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
                isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID)== AppOpsManager.MODE_ALLOWED);
            } else {
                // in marshmallow this will always return true
                isMockLocation = !android.provider.Settings.Secure.getString(getApplicationContext().getContentResolver(), "mock_location").equals("0");
            }
        } catch (Exception e) {
            return isMockLocation;
        }
        return isMockLocation;
    }

Can't check signature: public key not found

I got the same message but my files are decrypted as expected. Please check in your destination path if you could see the output file file.

How do I measure time elapsed in Java?

If the purpose is to simply print coarse timing information to your program logs, then the easy solution for Java projects is not to write your own stopwatch or timer classes, but just use the org.apache.commons.lang.time.StopWatch class that is part of Apache Commons Lang.

final StopWatch stopwatch = new StopWatch();
stopwatch.start();
LOGGER.debug("Starting long calculations: {}", stopwatch);
...
LOGGER.debug("Time after key part of calcuation: {}", stopwatch);
...
LOGGER.debug("Finished calculating {}", stopwatch);

How do I do top 1 in Oracle?

Use:

SELECT x.*
  FROM (SELECT fname 
          FROM MyTbl) x
 WHERE ROWNUM = 1

If using Oracle9i+, you could look at using analytic functions like ROW_NUMBER() but they won't perform as well as ROWNUM.

How to remove class from all elements jquery

You need to select the li tags contained within the .edgetoedge class. .edgetoedge only matches the one ul tag:

$(".edgetoedge li").removeClass("highlight");

Find TODO tags in Eclipse

  1. Push Ctrl+H
  2. Got to File Search tab
  3. Enter "// TODO Auto-generated method stub" in Containing Text field
  4. Enter "*.java" in Filename patterns field
  5. Select proper scope

Undefined behavior and sequence points

C++98 and C++03

This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.


Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.

Pre-requisites : An elementary knowledge of C++ Standard


What are Sequence Points?

The Standard says

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)

Side effects? What are side effects?

Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).

For example:

int x = y++; //where y is also an int

In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.

So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit:

Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.


What are the common sequence points listed in the C++ Standard ?

Those are:

  • at the end of the evaluation of full expression (§1.9/16) (A full-expression is an expression that is not a subexpression of another expression.)1

    Example :

    int a = 5; // ; is a sequence point here
    
  • in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18) 2

    • a && b (§5.14)
    • a || b (§5.15)
    • a ? b : c (§5.16)
    • a , b (§5.18) (here a , b is a comma operator; in func(a,a++) , is not a comma operator, it's merely a separator between the arguments a and a++. Thus the behaviour is undefined in that case (if a is considered to be a primitive type))
  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument

2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.


What is Undefined Behaviour?

The Standard defines Undefined Behaviour in Section §1.3.12 as

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.

Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.

3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.


What is the relation between Undefined Behaviour and Sequence Points?

Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.

You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

For example:

int x = 5, y = 6;

int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.

Another example here.


Now the Standard in §5/4 says

  • 1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

What does it mean?

Informally it means that between two sequence points a variable must not be modified more than once. In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.

From the above sentence the following expressions invoke Undefined Behaviour:

i++ * ++i;   // UB, i is modified more than once btw two SPs
i = ++i;     // UB, same as above
++i = 2;     // UB, same as above
i = ++i + 1; // UB, same as above
++++++i;     // UB, parsed as (++(++(++i)))

i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)

But the following expressions are fine:

i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i);   // well defined 
int j = i;
j = (++i, i++, j*i); // well defined

  • 2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

For example in i = i + 1 all the access of i (in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.

This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.

Example 1:

std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2

Example 2:

a[i] = i++ // or a[++i] = i or a[i++] = ++i etc

is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.

Example 3 :

int x = i + i++ ;// Similar to above

Follow up answer for C++11 here.

Eclipse error "ADB server didn't ACK, failed to start daemon"

Check for the path of the Android directory. It should not contain spaces, etc.

Also check if the plugin has been properly configured in Eclipse ? Preferences.

In my case I had everything checked multiple times, but it was still not working. I was about to reinstall everything, but I came upon an answer on this site (some other post).

Do check your antivirus. It may be blocking the ports of adb.exe or emulator programs, etc. That solved the problem in my case.

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

adding css class to multiple elements

Try using:

.button input, .button a {
    // css stuff
}

Also, read up on CSS.

Edit: If it were me, I'd add the button class to the element, not to the parent tag. Like so:

HTML:

<a href="#" class='button'>BUTTON TEXT</a>
<input type="submit" class='button' value='buttontext' />

CSS:

.button {
    // css stuff
}

For specific css stuff use:

input.button {
    // css stuff
}
a.button {
    // css stuff
}

Bootstrap 3 jquery event for active tab change

To add to Mosh Feu answer, if the tabs where created on the fly like in my case, you would use the following code

$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    var tab = $(e.target);
    var contentId = tab.attr("href");

    //This check if the tab is active
    if (tab.parent().hasClass('active')) {
         console.log('the tab with the content id ' + contentId + ' is visible');
    } else {
         console.log('the tab with the content id ' + contentId + ' is NOT visible');
    }

});

I hope this helps someone

Difference between Activity Context and Application Context

The reason I think is that ProgressDialog is attached to the activity that props up the ProgressDialog as the dialog cannot remain after the activity gets destroyed so it needs to be passed this(ActivityContext) that also gets destroyed with the activity whereas the ApplicationContext remains even after the activity gets destroyed.

Sum of Numbers C++

I have the following formula that works without loops. I discovered it while trying to find a formula for factorials:

#include <iostream>
using namespace std;

int main() {
    unsigned int positiveInteger;
    cout << "Please input an integer up to 100." << endl;
    cin >> positiveInteger;

    cout << (positiveInteger * (positiveInteger + 1)) / 2;
    return 0;
}