Programs & Examples On #Inbox

Get all messages from Whatsapp

I'm not sure if WhatsApp really stores it's stuff in a sqlite database stored in the private app space but it may be worth a try to do the same I suggested here. You will need root access for this.

How can I read SMS messages from the device programmatically in Android?

This post is a little bit old, but here is another easy solution for getting data related to SMS content provider in Android:

Use this lib: https://github.com/EverythingMe/easy-content-providers

  • Get all SMS:

    TelephonyProvider telephonyProvider = new TelephonyProvider(context);
    List<Sms> smses = telephonyProvider.getSms(Filter.ALL).getList();
    

    Each Sms has all fields, so you can get any info you need:
    address, body, receivedDate, type(INBOX, SENT, DRAFT, ..), threadId, ...

  • Gel all MMS:

    List<Mms> mmses = telephonyProvider.getMms(Filter.ALL).getList();
    
  • Gel all Thread:

    List<Thread> threads = telephonyProvider.getThreads().getList();
    
  • Gel all Conversation:

    List<Conversation> conversations = telephonyProvider.getConversations().getList();
    

It works with List or Cursor and there is a sample app to see how it looks and works.

In fact, there is a support for all Android content providers like: Contacts, Call logs, Calendar, ... Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers

Hope it also helped :)

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

Bash function to find newest file matching pattern

This is a possible implementation of the required Bash function:

# Print the newest file, if any, matching the given pattern
# Example usage:
#   newest_matching_file 'b2*'
# WARNING: Files whose names begin with a dot will not be checked
function newest_matching_file
{
    # Use ${1-} instead of $1 in case 'nounset' is set
    local -r glob_pattern=${1-}

    if (( $# != 1 )) ; then
        echo 'usage: newest_matching_file GLOB_PATTERN' >&2
        return 1
    fi

    # To avoid printing garbage if no files match the pattern, set
    # 'nullglob' if necessary
    local -i need_to_unset_nullglob=0
    if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then
        shopt -s nullglob
        need_to_unset_nullglob=1
    fi

    newest_file=
    for file in $glob_pattern ; do
        [[ -z $newest_file || $file -nt $newest_file ]] \
            && newest_file=$file
    done

    # To avoid unexpected behaviour elsewhere, unset nullglob if it was
    # set by this function
    (( need_to_unset_nullglob )) && shopt -u nullglob

    # Use printf instead of echo in case the file name begins with '-'
    [[ -n $newest_file ]] && printf '%s\n' "$newest_file"

    return 0
}

It uses only Bash builtins, and should handle files whose names contain newlines or other unusual characters.

Fixed size div?

You can set the height and width of your divs with css.

<style type="text/css">
.box {
     height: 150px;
     width: 150px;
}
</style> 

Is this what you're looking for?

Angular 5 ngHide ngShow [hidden] not working

Try this:

<button (click)="click()">Click me</button>

<input class="txt" type="password" [(ngModel)]="input_pw" [ngClass]="{'hidden': isHidden}" />

component.ts:

isHidden: boolean = false;
click(){
    this.isHidden = !this.isHidden;
}

React "after render" code?

For me, no combination of window.requestAnimationFrame or setTimeout produced consistent results. Sometimes it worked, but not always—or sometimes it would be too late.

I fixed it by looping window.requestAnimationFrame as many times as necessary.
(Typically 0 or 2-3 times)

The key is diff > 0: here we can ensure exactly when the page updates.

// Ensure new image was loaded before scrolling
if (oldH > 0 && images.length > prevState.images.length) {
    (function scroll() {
        const newH = ref.scrollHeight;
        const diff = newH - oldH;

        if (diff > 0) {
            const newPos = top + diff;
            window.scrollTo(0, newPos);
        } else {
            window.requestAnimationFrame(scroll);
        }
    }());
}

Using generic std::function objects with member functions in one class

You can avoid std::bind doing this:

std::function<void(void)> f = [this]-> {Foo::doSomething();}

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

Your problem is that you have 64-bit eclipse running but you have 32 bit JRE.So please download JRE for 64 bit windows and let it install on the default location. Finally add that path till bin in your PATH variable. Try it should work.

What is the difference between json.load() and json.loads() functions

The json.load() method (without "s" in "load") can read a file directly:

import json
with open('strings.json') as f:
    d = json.load(f)
    print(d)

json.loads() method, which is used for string arguments only.

import json

person = '{"name": "Bob", "languages": ["English", "Fench"]}'
print(type(person))
# Output : <type 'str'>

person_dict = json.loads(person)
print( person_dict)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}

print(type(person_dict))
# Output : <type 'dict'>

Here , we can see after using loads() takes a string ( type(str) ) as a input and return dictionary.

SSL "Peer Not Authenticated" error with HttpClient 4.1

This is thrown when

... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.

Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.

The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts file and trust it using keytool which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.

How to use LocalBroadcastManager?

In Eclipse, eventually I had to add Compatibility/Support Library by right-clicking on my project and selecting:

Android Tools -> Add Support Library

Once it was added, then I was able to use LocalBroadcastManager class in my code.


Android Compatibility Library

Exception.Message vs Exception.ToString()

Converting the WHOLE Exception To a String

Calling Exception.ToString() gives you more information than just using the Exception.Message property. However, even this still leaves out lots of information, including:

  1. The Data collection property found on all exceptions.
  2. Any other custom properties added to the exception.

There are times when you want to capture this extra information. The code below handles the above scenarios. It also writes out the properties of the exceptions in a nice order. It's using C# 7 but should be very easy for you to convert to older versions if necessary. See also this related answer.

public static class ExceptionExtensions
{
    public static string ToDetailedString(this Exception exception) =>
        ToDetailedString(exception, ExceptionOptions.Default);

    public static string ToDetailedString(this Exception exception, ExceptionOptions options)
    {
        if (exception == null)
        {
            throw new ArgumentNullException(nameof(exception));
        } 

        var stringBuilder = new StringBuilder();

        AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);

        foreach (PropertyInfo property in exception
            .GetType()
            .GetProperties()
            .OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
            .ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
        {
            var value = property.GetValue(exception, null);
            if (value == null && options.OmitNullProperties)
            {
                if (options.OmitNullProperties)
                {
                    continue;
                }
                else
                {
                    value = string.Empty;
                }
            }

            AppendValue(stringBuilder, property.Name, value, options);
        }

        return stringBuilder.ToString().TrimEnd('\r', '\n');
    }

    private static void AppendCollection(
        StringBuilder stringBuilder,
        string propertyName,
        IEnumerable collection,
        ExceptionOptions options)
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} =");

            var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);

            var i = 0;
            foreach (var item in collection)
            {
                var innerPropertyName = $"[{i}]";

                if (item is Exception)
                {
                    var innerException = (Exception)item;
                    AppendException(
                        stringBuilder,
                        innerPropertyName,
                        innerException,
                        innerOptions);
                }
                else
                {
                    AppendValue(
                        stringBuilder,
                        innerPropertyName,
                        item,
                        innerOptions);
                }

                ++i;
            }
        }

    private static void AppendException(
        StringBuilder stringBuilder,
        string propertyName,
        Exception exception,
        ExceptionOptions options)
    {
        var innerExceptionString = ToDetailedString(
            exception, 
            new ExceptionOptions(options, options.CurrentIndentLevel + 1));

        stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
        stringBuilder.AppendLine(innerExceptionString);
    }

    private static string IndentString(string value, ExceptionOptions options)
    {
        return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
    }

    private static void AppendValue(
        StringBuilder stringBuilder,
        string propertyName,
        object value,
        ExceptionOptions options)
    {
        if (value is DictionaryEntry)
        {
            DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
        }
        else if (value is Exception)
        {
            var innerException = (Exception)value;
            AppendException(
                stringBuilder,
                propertyName,
                innerException,
                options);
        }
        else if (value is IEnumerable && !(value is string))
        {
            var collection = (IEnumerable)value;
            if (collection.GetEnumerator().MoveNext())
            {
                AppendCollection(
                    stringBuilder,
                    propertyName,
                    collection,
                    options);
            }
        }
        else
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
        }
    }
}

public struct ExceptionOptions
{
    public static readonly ExceptionOptions Default = new ExceptionOptions()
    {
        CurrentIndentLevel = 0,
        IndentSpaces = 4,
        OmitNullProperties = true
    };

    internal ExceptionOptions(ExceptionOptions options, int currentIndent)
    {
        this.CurrentIndentLevel = currentIndent;
        this.IndentSpaces = options.IndentSpaces;
        this.OmitNullProperties = options.OmitNullProperties;
    }

    internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }

    internal int CurrentIndentLevel { get; set; }

    public int IndentSpaces { get; set; }

    public bool OmitNullProperties { get; set; }
}

Top Tip - Logging Exceptions

Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.

Top Tip - Human Readable Stack Traces

You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog.

Change UITextField and UITextView Cursor / Caret Color

Try, Its working for me.

[[self.textField valueForKey:@"textInputTraits"] setValue:[UIColor redColor] strong textforKey:@"insertionPointColor"];

How can I make all images of different height and width the same via CSS?

Without code this is difficult to help you but here's some practical advice for you:

I suspect that your "image wall" has some sort of container with an id or class to give it styles.

eg:

<body>

<div id="maincontainer">
  <div id="header"></div>

  <div id="content">
    <div id="imagewall">
      <img src"img.jpg">
<!-- code continues -->

Styling a size on all images for your image wall, while not affecting other images, like you logo, etc. is easy if your code is set up similar to the above.

#imagewall img {
  width: 100px;
  height: 100px; }

But if your images are not perfectly square they will be skewed using this method.

Only numbers. Input number in React

Here's my solution of plain Javascript

Attach a keyup event to the input field of your choice - id in this example.
In the event-handler function just test the key of event.key with the given regex.

In this case if it doesn't match we prevent the default action of the element - so a "wrong" key-press within the input box won't be registered thus it will never appear in the input box.

  let idField = document.getElementById('id');

  idField.addEventListener('keypress', function(event) {
    if (! /([0-9])/g.test(event.key)) {
      event.preventDefault();
    }
  });

The benefit of this solution may be its flexible nature and by changing and/or logically chaining regular expression(s) can fit many requirements. E.g. the regex /([a-z0-9-_])/g should match only lowercase English alphanumeric characters with no spaces and only - and _ allowed.

Note: that if you use /[a-z]/gi (note the i at the end) will ignore letter case and will still accept capital letters.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

After facing a similar issue, below is what I did :

  • Created a class extending javax.ws.rs.core.Application and added a Cors Filter to it.

To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");.

Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*" instead of any specific URL to allow any URL.

public class RestApplication
    extends Application
{
    private Set<Object> singletons = new HashSet<Object>();

    public MessageApplication()
    {
        singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
        CorsFilter corsFilter = new CorsFilter();
        // To allow all origins for CORS add following, otherwise add only specific urls.
        // corsFilter.getAllowedOrigins().add("*");
        System.out.println("To only allow restrcited urls ");
        corsFilter.getAllowedOrigins().add("http://localhost:4200");
        singletons = new LinkedHashSet<Object>();
        singletons.add(corsFilter);
    }

    @Override
    public Set<Object> getSingletons()
    {
        return singletons;
    }
}
  • And here is my web.xml:
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <!-- Auto scan rest service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.app.RestApplication</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>

   <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.app.RestApplication</param-value>
    </init-param>

And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.

AngularJS resource promise

If you want to use asynchronous method you need to use callback function by $promise, here is example:

var Regions = $resource('mocks/regions.json');

$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
    $scope.regions = result;
});

find filenames NOT ending in specific extensions on Unix?

find  /data1/batch/source/export   -type f -not  -name "*.dll" -not -name "*.exe"

Calling a Variable from another Class

You need to specify an access modifier for your variable. In this case you want it public.

public class Variables
{
    public static string name = "";
}

After this you can use the variable like this.

Variables.name

How to use Redirect in the new react-router-dom of Reactjs

Here a small example as response to the title as all mentioned examples are complicated in my opinion as well as the official one.

You should know how to transpile es2015 as well as make your server able to handle the redirect. Here is a snippet for express. More info related to this can be found here.

Make sure to put this below all other routes.

const app = express();
app.use(express.static('distApp'));

/**
 * Enable routing with React.
 */
app.get('*', (req, res) => {
  res.sendFile(path.resolve('distApp', 'index.html'));
});

This is the .jsx file. Notice how the longest path comes first and get's more general. For the most general routes use the exact attribute.

// Relative imports
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';

// Absolute imports
import YourReactComp from './YourReactComp.jsx';

const root = document.getElementById('root');

const MainPage= () => (
  <div>Main Page</div>
);

const EditPage= () => (
  <div>Edit Page</div>
);

const NoMatch = () => (
  <p>No Match</p>
);

const RoutedApp = () => (
  <BrowserRouter >
    <Switch>
      <Route path="/items/:id" component={EditPage} />
      <Route exact path="/items" component={MainPage} />          
      <Route path="/yourReactComp" component={YourReactComp} />
      <Route exact path="/" render={() => (<Redirect to="/items" />)} />          
      <Route path="*" component={NoMatch} />          
    </Switch>
  </BrowserRouter>
);

ReactDOM.render(<RoutedApp />, root); 

Python string.join(list) on object array rather than string array

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

transform object to array with lodash

A modern native solution if anyone is interested:

const arr = Object.keys(obj).map(key => ({ key, value: obj[key] }));

or (not IE):

const arr = Object.entries(obj).map(([key, value]) => ({ key, value }));

List of all unique characters in a string?

Store Unique characters in list

Method 1:

uniue_char = list(set('aaabcabccd'))
#['a', 'b', 'c', 'd']

Method 2: By Loop ( Complex )

uniue_char = []
for c in 'aaabcabccd':
    if not c in uniue_char:
        uniue_char.append(c)
print(uniue_char)
#['a', 'b', 'c', 'd']

Node.js getaddrinfo ENOTFOUND

I got this issue resolved by removing non-desirable characters from the password for the connection. For example, I had these characters: <##% and it caused the problem (most probably hash tag was the root cause of the problem).

Java 8 stream's .min() and .max(): why does this compile?

Let me explain what is happening here, because it isn't obvious!

First, Stream.max() accepts an instance of Comparator so that items in the stream can be compared against each other to find the minimum or maximum, in some optimal order that you don't need to worry too much about.

So the question is, of course, why is Integer::max accepted? After all it's not a comparator!

The answer is in the way that the new lambda functionality works in Java 8. It relies on a concept which is informally known as "single abstract method" interfaces, or "SAM" interfaces. The idea is that any interface with one abstract method can be automatically implemented by any lambda - or method reference - whose method signature is a match for the one method on the interface. So examining the Comparator interface (simple version):

public Comparator<T> {
    T compare(T o1, T o2);
}

If a method is looking for a Comparator<Integer>, then it's essentially looking for this signature:

int xxx(Integer o1, Integer o2);

I use "xxx" because the method name is not used for matching purposes.

Therefore, both Integer.min(int a, int b) and Integer.max(int a, int b) are close enough that autoboxing will allow this to appear as a Comparator<Integer> in a method context.

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

How to get key names from JSON using jq

You need to use jq 'keys[]'. For example:

echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'

Will output a line separated list:

"example1"
"example2"
"example3"

How to get a float result by dividing two integer values using T-SQL?

Because SQL Server performs integer division. Try this:

select 1 * 1.0 / 3

This is helpful when you pass integers as params.

select x * 1.0 / y

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

Get the closest number out of an array

I like the approach from Fusion, but there's a small error in it. Like that it is correct:

    function closest(array, number) {
        var num = 0;
        for (var i = array.length - 1; i >= 0; i--) {
            if(Math.abs(number - array[i]) < Math.abs(number - array[num])){
                num = i;
            }
        }
        return array[num];
    }

It it also a bit faster because it uses the improved for loop.

At the end I wrote my function like this:

    var getClosest = function(number, array) {
        var current = array[0];
        var difference = Math.abs(number - current);
        var index = array.length;
        while (index--) {
            var newDifference = Math.abs(number - array[index]);
            if (newDifference < difference) {
                difference = newDifference;
                current = array[index];
            }
        }
        return current;
    };

I tested it with console.time() and it is slightly faster than the other function.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How to create XML file with specific structure in Java

There is no need for any External libraries, the JRE System libraries provide all you need.

I am infering that you have a org.w3c.dom.Document object you would like to write to a file

To do that, you use a javax.xml.transform.Transformer:

import org.w3c.dom.Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

public class XMLWriter {
    public static void writeDocumentToFile(Document document, File file) {

        // Make a transformer factory to create the Transformer
        TransformerFactory tFactory = TransformerFactory.newInstance();

        // Make the Transformer
        Transformer transformer = tFactory.newTransformer();

        // Mark the document as a DOM (XML) source
        DOMSource source = new DOMSource(document);

        // Say where we want the XML to go
        StreamResult result = new StreamResult(file);

        // Write the XML to file
        transformer.transform(source, result);
    }
}

Source: http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

Semantic Difference

According to HTML 5.2:

When specified on an element, [the hidden attribute] indicates that the element is not yet, or is no longer, directly relevant to the page’s current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user.

Examples include a tab list where some panels are not exposed, or a log-in screen that goes away after a user logs in. I like to call these things “temporally relevant” i.e. they are relevant based on timing.

On the other hand, ARIA 1.1 says:

[The aria-hidden state] indicates whether an element is exposed to the accessibility API.

In other words, elements with aria-hidden="true" are removed from the accessibility tree, which most assistive technology honors, and elements with aria-hidden="false" will definitely be exposed to the tree. Elements without the aria-hidden attribute are in the "undefined (default)" state, which means user agents should expose it to the tree based on its rendering. E.g. a user agent may decide to remove it if its text color matches its background color.

Now let’s compare semantics. It’s appropriate to use hidden, but not aria-hidden, for an element that is not yet “temporally relevant”, but that might become relevant in the future (in which case you would use dynamic scripts to remove the hidden attribute). Conversely, it’s appropriate to use aria-hidden, but not hidden, on an element that is always relevant, but with which you don’t want to clutter the accessibility API; such elements might include “visual flair”, like icons and/or imagery that are not essential for the user to consume.

Effective Difference

The semantics have predictable effects in browsers/user agents. The reason I make a distinction is that user agent behavior is recommended, but not required by the specifications.

The hidden attribute should hide an element from all presentations, including printers and screen readers (assuming these devices honor the HTML specs). If you want to remove an element from the accessibility tree as well as visual media, hidden would do the trick. However, do not use hidden just because you want this effect. Ask yourself if hidden is semantically correct first (see above). If hidden is not semantically correct, but you still want to visually hide the element, you can use other techniques such as CSS.

Elements with aria-hidden="true" are not exposed to the accessibility tree, so for example, screen readers won’t announce them. This technique should be used carefully, as it will provide different experiences to different users: accessible user agents won’t announce/render them, but they are still rendered on visual agents. This can be a good thing when done correctly, but it has the potential to be abused.

Syntactic Difference

Lastly, there is a difference in syntax between the two attributes.

hidden is a boolean attribute, meaning if the attribute is present it is true—regardless of whatever value it might have—and if the attribute is absent it is false. For the true case, the best practice is to either use no value at all (<div hidden>...</div>), or the empty string value (<div hidden="">...</div>). I would not recommend hidden="true" because someone reading/updating your code might infer that hidden="false" would have the opposite effect, which is simply incorrect.

aria-hidden, by contrast, is an enumerated attribute, allowing one of a finite list of values. If the aria-hidden attribute is present, its value must be either "true" or "false". If you want the "undefined (default)" state, remove the attribute altogether.


Further reading: https://github.com/chharvey/chharvey.github.io/wiki/Hidden-Content

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

A possible solution for this is that you most probably not bundling your application first, perform the following steps and then deploy your app-debug.apk to your device

$ cd myproject  
$ react-native start > /dev/null 2>&1 &  
$ curl "http://localhost:8081/index.android.bundle?platform=android" -o "android/app/src/main/assets/index.android.bundle"

(if the folder assets does not exists create it)

Then run from project root

$> (cd android/ && ./gradlew assembleDebug)

install the created apk to you device, from location: android/app/build/outputs/apk/app-debug.apk

let me know if that fixes your issue

EDIT:

You can simply put it to your package.json as a script to automate it, I believe it will be fixed in upcoming releases of react-native and will be executed prior assembling the final APK, hence this won't be needed (I hope as well)

put :

"scripts": {
    "build": "(cd android/ && ./gradlew assembleDebug)",
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "bundle-android": "react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --sourcemap-output android/app/src/main/assets/index.android.map --assets-dest android/app/src/main/res/"
  },

or as mentioned the curl equivalent, but for most cases the above is more robust

How does one create an InputStream from a String?

Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:

InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );

Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.

What does ||= (or-equals) mean in Ruby?

x ||= y

is

x || x = y

"if x is false or undefined, then x point to y"

Place API key in Headers or URL

It should be put in the HTTP Authorization header. The spec is here https://tools.ietf.org/html/rfc7235

How to use Sublime over SSH

I am on MacOS, and the most convenient way for me is to using CyberDuck, which is free (also available for Windows). You can connect to your remote SSH file system and edit your file using your local editor. What CyberDuck does is download the file to a temporary place on your local OS and open it with your editor. Once you save the file, CyberDuck automatically upload it to your remote system. It seems transparent as if you are editing your remote file using your local editor. The developers of Cyberduck also make MountainDuck for mounting remote files systems.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

How to install both Python 2.x and Python 3.x in Windows

Check your system environment variables after installing Python, python 3's directories should be first in your PATH variable, then python 2.

Whichever path variable matches first is the one Windows uses.

As always py -2 will launch python2 in this scenario.

How to read data when some numbers contain commas as thousand separator?

Using read_delim function, which is part of readr library, you can specify additional parameter:

locale = locale(decimal_mark = ",")

read_delim("filetoread.csv", ';", locale = locale(decimal_mark = ","))

*Semicolon in second line means that read_delim will read csv semicolon separated values.

This will help to read all numbers with a comma as proper numbers.

Regards

Mateusz Kania

Space between border and content? / Border distance from content?

Add padding. Padding the element will increase the space between its content and its border. However, note that a box-shadow will begin outside the border, not the content, meaning you can't put space between the shadow and the box. Alternatively you could use :before or :after pseudo selectors on the element to create a slightly bigger box that you place the shadow on, like so: http://jsbin.com/aqemew/edit#source

Handling identity columns in an "Insert Into TABLE Values()" statement?

Another "trick" for generating the column list is simply to drag the "Columns" node from Object Explorer onto a query window.

java how to use classes in other package?

Given your example, you need to add the following import in your main.main class:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

git was working fine for be and all of sudden it started showing this fatal: Not a git repository (or any of the parent directories): .git message.

For me not sure what was corrupted in .git folder, I did git clone ** newfolder and copied the entire .git folder to my corrupted/old folder where I was making changes before git started showing error message..

Everything got back to normal and git also recognized my changed/un-staged files.

Understanding the Gemfile.lock file

You can find more about it in the bundler website (emphasis added below for your convenience):

After developing your application for a while, check in the application together with the Gemfile and Gemfile.lock snapshot. Now, your repository has a record of the exact versions of all of the gems that you used the last time you know for sure that the application worked...

This is important: the Gemfile.lock makes your application a single package of both your own code and the third-party code it ran the last time you know for sure that everything worked. Specifying exact versions of the third-party code you depend on in your Gemfile would not provide the same guarantee, because gems usually declare a range of versions for their dependencies.

Best practice: PHP Magic Methods __set and __get

Second code example is much more proper way to do this because you are taking full control of data which are given to class. There are cases in which the __set and __get are useful but not in this case.

Add Keypair to existing EC2 instance

This happened to me earlier (didn't have access to an EC2 instance someone else created but had access to AWS web console) and I blogged the answer: http://readystate4.com/2013/04/09/aws-gaining-ssh-access-to-an-ec2-instance-you-lost-access-to/

Basically, you can detached the EBS drive, attach it to an EC2 that you do have access to. Add your SSH pub key to ~ec2-user/.ssh/authorized_keys on this attached drive. Then put it back on the old EC2 instance. step-by-step in the link using Amazon AMI.

No need to make snapshots or create a new cloned instance.

How to get table cells evenly spaced?

You could always just set the width of each td to 100%/N columns.

<td width="x%"></td>

How can I get device ID for Admob

Another easiest way to show test ads is to use test device id for banner to show admob test ads for all devices. "ca-app-pub-3940256099942544/6300978111" . This admob test ads id was noted in the admob tutorial of google: link. This is the quote from the above link: enter image description here

  • This is the test device id for interstitial "ca-app-pub-3940256099942544/1033173712" . This also was used in interstitial tutorial

jquery draggable: how to limit the draggable area?

$(function() { $( "#draggable" ).draggable({ containment: "window" }); });

of this code does not display. Full code and Demo: http://www.limitsizbilgi.com/div-tasima-surukle-birak-div-drag-and-drop-jquery.html

In order to limit the element inside its parent:

$( "#draggable" ).draggable({ containment: "window" });

Add php variable inside echo statement as href link address?

Try like

HTML in PHP :

echo "<a href='".$link_address."'>Link</a>";

Or even you can try like

echo "<a href='$link_address'>Link</a>";

Or you can use PHP in HTML like

PHP in HTML :

<a href="<?php echo $link_address;?>"> Link </a>

Print content of JavaScript object?

Print content of object you can use

console.log(obj_str);

you can see the result in console like below.

Object {description: "test"} 

For open console press F12 in chrome browser, you will found console tab in debug mode.

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

I got a similar error when adding files from another project, like @paiego explained. My error was that I didn't check "Add to targets". As explained above, I deleted the references and added the files again but this time checking "Add to targets".

Convert .pem to .crt and .key

To extract the key and cert from a pem file:

Extract key

openssl pkey -in foo.pem -out foo.key

Another method of extracting the key...

openssl rsa -in foo.pem -out foo.key

Extract all the certs, including the CA Chain

openssl crl2pkcs7 -nocrl -certfile foo.pem | openssl pkcs7 -print_certs -out foo.cert

Extract the textually first cert as DER

openssl x509 -in foo.pem -outform DER -out first-cert.der

How do I generate random integers within a specific range in Java?

You can do as below.

import java.util.Random;
public class RandomTestClass {

    public static void main(String[] args) {
        Random r = new Random();
        int max, min;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter maximum value : ");
        max = scanner.nextInt();
        System.out.println("Enter minimum value : ");
        min = scanner.nextInt();
        int randomNum;
        randomNum = r.nextInt(max) + min;
        System.out.println("Random Number : " + randomNum);
    }

}

MySQL Job failed to start

In my case, it simply because the disk is full. Just clear some disk space and restart and everything is fine.

Passive Link in Angular 2 - <a href=""> equivalent

A really simple solution is not to use an A tag - use a span instead:

<span class='link' (click)="doSomething()">Click here</span>

span.link {
  color: blue;
  cursor: pointer;
  text-decoration: underline;
}

How to break lines at a specific character in Notepad++?

Let's assume ], is the character where we wanted to break at

  1. Open notePad++
  2. Open Find window Ctrl+F
  3. Switch to Replace Tab
  4. Choose Search Mode to Extended
  5. Type ], in Find What field
  6. Type \nin Replace with field
  7. Hit Replace All
  8. Boom

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

How to format a numeric column as phone number in SQL

If you want to just format the output no need to create a new table or a function. In this scenario the area code was on a separate fields. I use field1, field2 just to illustrate you can select other fields in the same query:

area  phone
213   8962102

Select statement:

Select field1, field2,areacode,phone,SUBSTR(tablename.areacode,1,3) + '-' + SUBSTR(tablename.phone,1,3) + '-' + SUBSTR(tablename.areacode,4,4) as Formatted Phone from tablename

Sample OUTPUT:

columns: FIELD1, FIELD2, AREA, PHONE, FORMATTED PHONE
data:    Field1, Field2, 213,  8962102,  213-896-2102

Expression must be a modifiable lvalue

In C, you will also experience the same error if you declare a:

char array[size];

and than try to assign a value without specifying an index position:

array = '\0'; 

By doing:

array[index] = '0\';

You're specifying the accessible/modifiable address previously declared.

Oracle - How to create a readonly user

A user in an Oracle database only has the privileges you grant. So you can create a read-only user by simply not granting any other privileges.

When you create a user

CREATE USER ro_user
 IDENTIFIED BY ro_user
 DEFAULT TABLESPACE users
 TEMPORARY TABLESPACE temp;

the user doesn't even have permission to log in to the database. You can grant that

GRANT CREATE SESSION to ro_user

and then you can go about granting whatever read privileges you want. For example, if you want RO_USER to be able to query SCHEMA_NAME.TABLE_NAME, you would do something like

GRANT SELECT ON schema_name.table_name TO ro_user

Generally, you're better off creating a role, however, and granting the object privileges to the role so that you can then grant the role to different users. Something like

Create the role

CREATE ROLE ro_role;

Grant the role SELECT access on every table in a particular schema

BEGIN
  FOR x IN (SELECT * FROM dba_tables WHERE owner='SCHEMA_NAME')
  LOOP
    EXECUTE IMMEDIATE 'GRANT SELECT ON schema_name.' || x.table_name || 
                                  ' TO ro_role';
  END LOOP;
END;

And then grant the role to the user

GRANT ro_role TO ro_user;

Android emulator-5554 offline

In my case, I started in 'Cold Boot Now' and clicked on Message to allow the connection.

How to make Toolbar transparent?

I implemented translucent Toolbar by creating two Theme.AppCompat.Light.NoActionBar themes and setting colorPrimary attribute to transparent color.

1) Create one theme for opaque Toolbar:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

    <!-- Toolbar background color -->
    <item name="colorPrimary">#ff212cff</item>

</style>

Second theme for transparent/overlay Toolbar:

<style name="AppTheme.Overlay" parent="AppTheme">
    <item name="colorPrimary">@color/transparent</item>
</style>

2) In your activity layout, put Toolbar behind content so it can be displayed in front of it:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/container"
        android:name="com.test.CustomFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

</RelativeLayout>

3) Apply the transparent theme to your acivity in AndroidManifest.xml

    <activity
        android:name="com.test.TransparentActivity"
        android:parentActivityName="com.test.HomeActivity"
        android:theme="@style/AppTheme.Overlay" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.test.HomeActivity" />
    </activity>

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

When should we call System.exit in Java

System.exit is needed

  • when you want to return a non-0 error code
  • when you want to exit your program from somewhere that isn't main()

In your case, it does the exact same thing as the simple return-from-main.

Comments in Markdown

The following works very well

<empty line>
[whatever comment text]::

that method takes advantage of syntax to create links via reference
since link reference created with [1]: http://example.org will not be rendered, likewise any of the following will not be rendered as well

<empty line>
[whatever]::
[whatever]:whatever
[whatever]: :
[whatever]: whatever

Print series of prime numbers in python

My way of listing primes to an entry number without too much hassle is using the property that you can get any number that is not a prime with the summation of primes.

Therefore, if you divide the entry number with all primes below it, and it is not evenly divisible by any of them, you know that you have a prime.

Of course there are still faster ways of getting the primes, but this one already performs quite well, especially because you are not dividing the entry number by any number, but quite only the primes all the way to that number.

With this code I managed on my computer to list all primes up to 100 000 in less than 4 seconds.

import time as t

start = t.clock()

primes = [2,3,5,7]

for num in xrange(3,100000,2):
    if all(num%x != 0 for x in primes):
        primes.append(num)

print primes
print t.clock() - start
print sum(primes)

Multiple actions were found that match the request in Web Api

Please check you have two methods which has the different name and same parameters.

If so please delete any of the method and try.

When to use which design pattern?

Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)

if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.

Bootstrap 3 and Youtube in Modal

If you don't want to edit the bootstrap CSS or all of the above doesn't help you at all (like in my case), there's an easy fix to get the video running in a modal on Firefox.

You just need to remove the "fade" class from the modal and as it opens the "in" class, too:

$('#myModal').on('shown.bs.modal', function () {
    $('#myModal').removeClass('in');
});

Java file path in Linux

Looks like you are missing a leading slash. Perhaps try:

Scanner s = new Scanner(new File("/home/me/java/ex.txt"));

(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)

CSS - Expand float child DIV height to parent's height

CSS table display is ideal for this:

_x000D_
_x000D_
.parent {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
}_x000D_
.parent > div {_x000D_
  display: table-cell;_x000D_
}_x000D_
.child-left {_x000D_
  background: powderblue;_x000D_
}_x000D_
.child-right {_x000D_
  background: papayawhip;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child-left">Short</div>_x000D_
  <div class="child-right">Tall<br>Tall</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Original answer (assumed any column could be taller):

You're trying to make the parent's height dependent on the children's height and children's height dependent on parent's height. Won't compute. CSS Faux columns is the best solution. There's more than one way of doing that. I'd rather not use JavaScript.

Run php function on button click

Do this:

<input type="button" name="test" id="test" value="RUN" /><br/>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}
if(array_key_exists('test',$_POST)){
   testfun();
}
?>

jQuery bind/unbind 'scroll' event on $(window)

try this:

$(window).unbind('scroll');

it works in my project

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

Text overwrite in visual studio 2010

If pressing the Insert key doesn't work, try doubleclicking the INS/OVR label in the lower right corner of Visual Studio.

Sound effects in JavaScript / HTML5

It's not possible to do multi-shot playing with a single <audio> element. You need to use multiple elements for this.

Max parallel http connections in a browser?

HTTP/1.1

IE 6 and 7:      2
IE 8:            6
IE 9:            6
IE 10:           8
IE 11:           8
Firefox 2:       2
Firefox 3:       6
Firefox 4 to 46: 6
Opera 9.63:      4
Opera 10:        8
Opera 11 and 12: 6
Chrome 1 and 2:  6
Chrome 3:        4
Chrome 4 to 23:  6
Safari 3 and 4:  4

source: http://p2p.wrox.com/book-professional-website-performance-optimizing-front-end-back-end-705/

HTTP/2(SPDY)

Multiplexed support(one single TCP connection for all requests)

editing PATH variable on mac

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

Catching access violation exceptions?

As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:

DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)

The original class came from this very useful article:

http://www.codeproject.com/KB/cpp/exception.aspx

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Swift Error: Editor placeholder in source file

After Command + Shift + B, the project works fine.

How to know Hive and Hadoop versions from command prompt?

I was able to get the version of installed Hadoop 3.0.3 by the following command
$HADOOP_HOME/bin$ ./hadoop version
which gave me the following output

Hadoop 3.0.3
Source code repository https://[email protected]/repos/asf/hadoop.git -r 37fd7d752db73d984dc31e0cdfd590d252f5e075
Compiled by yzhang on 2018-05-31T17:12Z
Compiled with protoc 2.5.0
From source with checksum 736cdcefa911261ad56d2d120bf1fa
This command was run using /usr/local/hadoop/share/hadoop/common/hadoop-common-3.0.3.jar

Java integer list

If you want to rewrite a line on console, print a control character \r (carriage return).

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = myCoords.iterator(); 
while (myListIterator.hasNext()) {
    Integer coord = myListIterator.next();     
    System.out.print("\r");
    System.out.print(coord);
    Thread.sleep(2000);
}

Bootstrap 3 unable to display glyphicon properly

First of all, I try to install the glyphicons fonts by the "oficial" way, with the zip file. I could not do it.

This is my step-by-step solution:

  1. Go to the web page of Bootstrap and then to the "Components" section.
  2. Open the browser console. In Chrome, Ctrl+Shift+C.
  3. In section Resources, inside Frames/getbootstrap.com/Fonts you will find the font that actually is running the glyphicons. It's recommended to use the private mode to evade cache.
  4. With URL of the font file (right-click on the file showed on resources list), copy it in a new tab, and press ENTER. This will download the font file.
  5. Copy another time the URL in a tab and change the font extension to eot, ttf, svg or woff, ass you like.

However, for a more easy acces, this is the link of the woff file.

http://getbootstrap.com/dist/fonts/glyphicons-halflings-regular.woff

Unable to resolve host "<insert URL here>" No address associated with hostname

I got the same error and for the issue was that I was on VPN and I didn't realize that. After disconnecting the VPN and reconnecting the wifi resolved it.

A simple command line to download a remote maven2 artifact to the local repository?

Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=http://download.java.net/maven/2/ \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT

Pass an array of integers to ASP.NET Web API?

You just need to add [FromUri] before parameter, looks like:

GetCategories([FromUri] int[] categoryIds)

And send request:

/Categories?categoryids=1&categoryids=2&categoryids=3 

Passing arguments to "make run"

I don't know a way to do what you want exactly, but a workaround might be:

run: ./prog
    ./prog $(ARGS)

Then:

make ARGS="asdf" run
# or
make run ARGS="asdf"

Echoing the last command run in Bash?

The command history is an interactive feature. Only complete commands are entered in the history. For example, the case construct is entered as a whole, when the shell has finished parsing it. Neither looking up the history with the history built-in (nor printing it through shell expansion (!:p)) does what you seem to want, which is to print invocations of simple commands.

The DEBUG trap lets you execute a command right before any simple command execution. A string version of the command to execute (with words separated by spaces) is available in the BASH_COMMAND variable.

trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
…
echo "last command is $previous_command"

Note that previous_command will change every time you run a command, so save it to a variable in order to use it. If you want to know the previous command's return status as well, save both in a single command.

cmd=$previous_command ret=$?
if [ $ret -ne 0 ]; then echo "$cmd failed with error code $ret"; fi

Furthermore, if you only want to abort on a failed commands, use set -e to make your script exit on the first failed command. You can display the last command from the EXIT trap.

set -e
trap 'echo "exit $? due to $previous_command"' EXIT

Note that if you're trying to trace your script to see what it's doing, forget all this and use set -x.

What exactly is LLVM?

LLVM (used to mean "Low Level Virtual Machine" but not anymore) is a compiler infrastructure, written in C++, which is designed for compile-time, link-time, run-time, and "idle-time" optimization of programs written in arbitrary programming languages. Originally implemented for C/C++, the language-independent design (and the success) of LLVM has since spawned a wide variety of front-ends, including Objective C, Fortran, Ada, Haskell, Java bytecode, Python, Ruby, ActionScript, GLSL, and others.

Read this for more explanation
Also check out Unladen Swallow

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

npm install @angular/[email protected] --save

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

The 'Access-Control-Allow-Origin' header contains multiple values

So stupid and simple:

This problem occurred for me when having two time Header always set Access-Control-Allow-Origin * inside my Apache config file. Once withing the VirtualHost tags and once inside a Limit tag:

<VirtualHost localhost:80>
  ...
  Header set Access-Control-Allow-Origin: *
  ...
  <Limit OPTIONS>
    ...
    Header set Access-Control-Allow-Origin: *
    ...
  </Limit>
</VirtualHost>

Removing one entry resolved the issue.

I guess in the original post it would have been two times:

Header set Access-Control-Allow-Origin: "http://127.0.0.1:9000"

How to display list of repositories from subversion server

If your server is Apache, you should be able to configure it to see the repository list with viewvc - this is the most basic one, other more complex interfaces exist but this is not your purpose here.

In some versions, ViewVC is an option of the standard installation now, for instance from Collabnet.

Edit: Nevermind my previous idea just above, Peter has a much simpler way of sending the repository list.

From there, you will have to:

  • get the HTML page,
  • extract the list, and
  • process it for the individual repository search.

Unfortunately in this case I cannot think of something more straightforward.

There are examples on SO on how to extract text from HTML pages in Python, this would be a good option since Python also has bindings for SVN, to perform the repository search - you can still call svn directly from Python if you prefer.

If Python is not your cup of tea, you will have to process that differently with GNU tools (wget, then parsing tools or existing packages - I can't be of much help there, Carl gave you some more details in this post).

jQuery posting JSON

You post JSON like this

$.ajax(url, {
    data : JSON.stringify(myJSObject),
    contentType : 'application/json',
    type : 'POST',
    ...

if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want

Docker remove <none> TAG images

docker rmi $(docker images -a -q)

Stated the following images where in use. I think this command gets rid of unwanted images.

Show MySQL host via SQL Command

show variables where Variable_name='hostname'; 

That could help you !!

How does Facebook disable the browser's integrated Developer Tools?

Internally devtools injects an IIFE named getCompletions into the page, called when a key is pressed inside the Devtools console.

Looking at the source of that function, it uses a few global functions which can be overwritten.

By using the Error constructor it's possible to get the call stack, which will include getCompletions when called by Devtools.


Example:

_x000D_
_x000D_
const disableDevtools = callback => {_x000D_
  const original = Object.getPrototypeOf;_x000D_
_x000D_
  Object.getPrototypeOf = (...args) => {_x000D_
    if (Error().stack.includes("getCompletions")) callback();_x000D_
    return original(...args);_x000D_
  };_x000D_
};_x000D_
_x000D_
disableDevtools(() => {_x000D_
  console.error("devtools has been disabled");_x000D_
_x000D_
  while (1);_x000D_
});
_x000D_
_x000D_
_x000D_

Run class in Jar file

You want:

java -cp myJar.jar myClass

The Documentation gives the following example:

C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Return content with IHttpActionResult for non-OK response

Anyone who is interested in returning anything with any statuscode with returning ResponseMessage:

//CreateResponse(HttpStatusCode, T value)
return ResponseMessage(Request.CreateResponse(HttpStatusCode.XX, object));

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

Twig: in_array or similar possible within if statement?

It should help you.

{% for user in users if user.active and user.id not 1 %}
   {{ user.name }}
{% endfor %}

More info: http://twig.sensiolabs.org/doc/tags/for.html

Display a float with two decimal places in Python

I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:

Python 3:

>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict) 
0.12_0.13

Convert char* to string C++

std::string str;
char* const s = "test";

str.assign(s);

string& assign (const char* s); => signature FYR

Reference/s here.

Deep copy an array in Angular 2 + TypeScript

This is working for me:

this.listCopy = Object.assign([], this.list);

Specifying colClasses in the read.csv

For multiple datetime columns with no header, and a lot of columns, say my datetime fields are in columns 36 and 38, and I want them read in as character fields:

data<-read.csv("test.csv", head=FALSE,   colClasses=c("V36"="character","V38"="character"))                        

Spring Data JPA map the native query result to Non-Entity POJO

I think the easiest way to do that is to use so called projection. It can map query results to interfaces. Using SqlResultSetMapping is inconvienient and makes your code ugly :).

An example right from spring data JPA source code:

public interface UserRepository extends JpaRepository<User, Integer> {

   @Query(value = "SELECT firstname, lastname FROM SD_User WHERE id = ?1", nativeQuery = true)
   NameOnly findByNativeQuery(Integer id);

   public static interface NameOnly {

     String getFirstname();

     String getLastname();

  }
}

You can also use this method to get a list of projections.

Check out this spring data JPA docs entry for more info about projections.

Note 1:

Remember to have your User entity defined as normal - the fields from projected interface must match fields in this entity. Otherwise field mapping might be broken (getFirstname() might return value of last name et cetera).

Note 2:

If you use SELECT table.column ... notation always define aliases matching names from entity. For example this code won't work properly (projection will return nulls for each getter):

@Query(value = "SELECT user.firstname, user.lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);

But this works fine:

@Query(value = "SELECT user.firstname AS firstname, user.lastname AS lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);

In case of more complex queries I'd rather use JdbcTemplate with custom repository instead.

hash function for string

djb2 has 317 collisions for this 466k english dictionary while MurmurHash has none for 64 bit hashes, and 21 for 32 bit hashes (around 25 is to be expected for 466k random 32 bit hashes). My recommendation is using MurmurHash if available, it is very fast, because it takes in several bytes at a time. But if you need a simple and short hash function to copy and paste to your project I'd recommend using murmurs one-byte-at-a-time version:

uint32_t inline MurmurOAAT32 ( const char * key)
{
  uint32_t h(3323198485ul);
  for (;*key;++key) {
    h ^= *key;
    h *= 0x5bd1e995;
    h ^= h >> 15;
  }
  return h;
}

uint64_t inline MurmurOAAT64 ( const char * key)
{
  uint64_t h(525201411107845655ull);
  for (;*key;++key) {
    h ^= *key;
    h *= 0x5bd1e9955bd1e995;
    h ^= h >> 47;
  }
  return h;
}

The optimal size of a hash table is - in short - as large as possible while still fitting into memory. Because we don't usually know or want to look up how much memory we have available, and it might even change, the optimal hash table size is roughly 2x the expected number of elements to be stored in the table. Allocating much more than that will make your hash table faster but at rapidly diminishing returns, making your hash table smaller than that will make it exponentially slower. This is because there is a non-linear trade-off between space and time complexity for hash tables, with an optimal load factor of 2-sqrt(2) = 0.58... apparently.

Insert NULL value into INT column

If the column has the NOT NULL constraint then it won't be possible; but otherwise this is fine:

INSERT INTO MyTable(MyIntColumn) VALUES(NULL);

No Access-Control-Allow-Origin header is present on the requested resource

You are missing 'json' dataType in the $.post() method:

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
        .done(function(data){
                  alert(data);
         }, "json");
         //-^^^^^^-------here

Updates:

try with this:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Option1:

To set the ASPNETCORE_ENVIRONMENT environment variable in windows,

Command line - setx ASPNETCORE_ENVIRONMENT "Development"

PowerShell - $Env:ASPNETCORE_ENVIRONMENT = "Development"

For other OS refer this - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments

Option2:

If you want to set ASPNETCORE_ENVIRONMENT using web.config then add aspNetCore like this-

<configuration>
  <!--
    Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
  -->
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath=".\MyApplication.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
      <environmentVariables>
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

Sending email with PHP from an SMTP server

For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.

Rails filtering array of objects by attribute value

Try :

This is fine :

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }

but for performance wise you don't need to iterate @attachments twice :

@logos , @images = [], []
@attachments.each do |attachment|
  @logos << attachment if attachment.file_type == 'logo'
  @images << attachment if attachment.file_type == 'image'
end

Javascript regular expression password validation having special characters

Regex for password:

/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[a-zA-Z!#$%&? "])[a-zA-Z0-9!#$%&?]{8,20}$/

Took me a while to figure out the restrictions, but I did it!

Restrictions: (Note: I have used >> and << to show the important characters)

  1. Minimum 8 characters {>>8,20}
  2. Maximum 20 characters {8,>>20}
  3. At least one uppercase character (?=.*[A-Z])
  4. At least one lowercase character (?=.*[a-z])
  5. At least one digit (?=.*\d)
  6. At least one special character (?=.*[a-zA-Z >>!#$%&? "<<])[a-zA-Z0-9 >>!#$%&?<< ]

Extract source code from .jar file

-Covert .jar file to .zip (In windows just change the extension) -Unzip the .zip folder -You will get complete .java files

Salt and hash a password in Python

As of Python 3.4, the hashlib module in the standard library contains key derivation functions which are "designed for secure password hashing".

So use one of those, like hashlib.pbkdf2_hmac, with a salt generated using os.urandom:

from typing import Tuple
import os
import hashlib
import hmac

def hash_new_password(password: str) -> Tuple[bytes, bytes]:
    """
    Hash the provided password with a randomly-generated salt and return the
    salt and hash to store in the database.
    """
    salt = os.urandom(16)
    pw_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
    return salt, pw_hash

def is_correct_password(salt: bytes, pw_hash: bytes, password: str) -> bool:
    """
    Given a previously-stored salt and hash, and a password provided by a user
    trying to log in, check whether the password is correct.
    """
    return hmac.compare_digest(
        pw_hash,
        hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
    )

# Example usage:
salt, pw_hash = hash_new_password('correct horse battery staple')
assert is_correct_password(salt, pw_hash, 'correct horse battery staple')
assert not is_correct_password(salt, pw_hash, 'Tr0ub4dor&3')
assert not is_correct_password(salt, pw_hash, 'rosebud')

Note that:

  • The use of a 16-byte salt and 100000 iterations of PBKDF2 match the minimum numbers recommended in the Python docs. Further increasing the number of iterations will make your hashes slower to compute, and therefore more secure.
  • os.urandom always uses a cryptographically secure source of randomness
  • hmac.compare_digest, used in is_correct_password, is basically just the == operator for strings but without the ability to short-circuit, which makes it immune to timing attacks. That probably doesn't really provide any extra security value, but it doesn't hurt, either, so I've gone ahead and used it.

For theory on what makes a good password hash and a list of other functions appropriate for hashing passwords with, see https://security.stackexchange.com/q/211/29805.

Android Gradle Could not reserve enough space for object heap

I ran into the same issue, here's my post:

Android Studio - Gradle build failing - Java Heap Space

exec summary: Windows looks for the gradle.properties file here:

C:\Users\.gradle\gradle.properties

So create that file, and add a line like this:

org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m

as per @Faiz Siddiqui post

Java LinkedHashMap get first or last entry

One more way to get first and last entry of a LinkedHashMap is to use toArray() method of Set interface.

But I think iterating over the entries in the entry set and getting the first and last entry is a better approach.

The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")].

Here is a small example to demonstrate the usage of toArray() method:

    public static void main(final String[] args) {
        final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
        orderMap.put(6, "Six");
        orderMap.put(7, "Seven");
        orderMap.put(3, "Three");
        orderMap.put(100, "Hundered");
        orderMap.put(10, "Ten");

        final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
        final int maplength = mapValues.size();
        final Entry<Integer,String>[] test = new Entry[maplength];
        mapValues.toArray(test);

        System.out.print("First Key:"+test[0].getKey());
        System.out.println(" First Value:"+test[0].getValue());

        System.out.print("Last Key:"+test[maplength-1].getKey());
        System.out.println(" Last Value:"+test[maplength-1].getValue());
    }

    // the output geneated is :
    First Key:6 First Value:Six
    Last Key:10 Last Value:Ten

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

How can I do SELECT UNIQUE with LINQ?

The Distinct() is going to mess up the ordering, so you'll have to the sorting after that.

var uniqueColors = 
               (from dbo in database.MainTable 
                 where dbo.Property == true 
                 select dbo.Color.Name).Distinct().OrderBy(name=>name);

Assert that a method was called in a Python unit test

You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

Using pymox, you'd do it like this:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)

How to join two sets in one line without using "|"

You can use union method for sets: set.union(other_set)

Note that it returns a new set i.e it doesn't modify itself.

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

Android - Launcher Icon Size

Well as @MartinVonMartinsgrün mentioned Now there is exists Better tools then assert generator in android studio

For application Icon ( Toolbar , ActionBar , DrawableLeft etc ) Use : http://romannurik.github.io/AndroidAssetStudio/icons-actionbar.html

For launcher (Application Icon ) Use : https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html

But Here are some tricks and way to get the better resolution for icons and launcher icons.

Step 1 :

First go to the https://materialdesignicons.com and choose your icon . Or if you have your icon in good resolution then skip this step . Click the desired icon and click on "Advanced Export" it will open up a window like this below Try to generate as large icon as possible

Then click the "Icon" to generate icon (.png) . Well the trick is try to generate as large icon as possible for high resolution devices and the tools will handle it all for small devices but if you use small icon , while generating the icon for high end devices you will loose the icon resolution .

Step 2 :

Then go the Tools page and Upload the Iconenter image description here

Click the "Custom" if you want to color your icon . No matter what color of icon you are uploading , by using Custom you can generate any color you want . Then choose a name and click "Download .ZIP" . This will download the .zip file with the icon for most of the common resolution . You can copy and paste the res folder in your application project folder and you will see the icon in the drawable section .

Linq select objects in list where exists IN (A,B,C)

Just be careful, .Contains() will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A") will return you both A and AA which you might not want. I have been bitten by it.

.Any() or .Exists() is safer choice

Update statement with inner join on Oracle

UPDATE table1 t1
SET t1.value = 
    (select t2.CODE from table2 t2 
     where t1.value = t2.DESC) 
WHERE t1.UPDATETYPE='blah';

Where can I find Android's default icons?

you can use

android.R.drawable.xxx

(use autocomplete to see whats in there)

Or download the stuff from http://developer.android.com/design/downloads/index.html

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

CreateProcess error=206, The filename or extension is too long when running main() method

I have got same error, while invoking Maven.

The root cause for my problem was the classpath was very huge. Updating the classpath fixed the problem.

There are multiple ways to update the large classpath as mentioned in this: How to set a long Java classpath in Windows?

  1. Use wildcards
  2. Argument File
  3. Pathing jar

Since I am using Intellij, they provide the option to use Argument File that i used.

How to hide output of subprocess in Python 2.7

Here's a more portable version (just for fun, it is not necessary in your case):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT

try:
    from subprocess import DEVNULL # py3k
except ImportError:
    import os
    DEVNULL = open(os.devnull, 'wb')

text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

How to change fontFamily of TextView in Android

I just want to mention that the hell with the fonts inside Android is about to end, because this year on Google IO we finally got this -> https://developer.android.com/preview/features/working-with-fonts.html

Now there is a new resource type a font and you can place all your application fonts inside res/fonts folder and access then with R.font.my_custom_font, just like you can access string res values, drawable res values etc. You have even chance to create font-face xml file, which is gonna be set of your custom fonts (about italic, bold and underline attr).

Read the link above for more info. Let's see the support.

Where is SQLite database stored on disk?

In Windows 10 if in the prompt command the path where you start sqlite is

C:\users\USER_NAME

You can find it in the user home folder. The .db file is stored where you start the sqlite command. I hope this solve the issue

How to show empty data message in Datatables

Later versions of dataTables have the following language settings (taken from here):

  • "infoEmpty" - displayed when there are no records in the table
  • "zeroRecords" - displayed when there no records matching the filtering

e.g.

$('#example').DataTable( {
    "language": {
        "infoEmpty": "No records available - Got it?",
    }
});

Note: As the property names do not contain any special characters you can remove the quotes:

$('#example').DataTable( {
    language: {
        infoEmpty: "No records available - Got it?",
    }
});

Numpy converting array from float to strings

If the main problem is the loss of precision when converting from a float to a string, one possible way to go is to convert the floats to the decimalS: http://docs.python.org/library/decimal.html.

In python 2.7 and higher you can directly convert a float to a decimal object.

How to handle AccessViolationException

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

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

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

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

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

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


EDIT

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

From Gaurav Khanna, a developer from the Microsoft CLR Team

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

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

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

How to populate a dropdownlist with json data in jquery?

try this one its worked for me

_x000D_
_x000D_
$(document).ready(function(e){_x000D_
        $.ajax({_x000D_
           url:"fetch",_x000D_
           processData: false,_x000D_
           dataType:"json",_x000D_
           type: 'POST',_x000D_
           cache: false,_x000D_
           success: function (data, textStatus, jqXHR) {_x000D_
                        _x000D_
                         $.each(data.Table,function(i,tweet){_x000D_
      $("#list").append('<option value="'+tweet.actor_id+'">'+tweet.first_name+'</option>');_x000D_
   });}_x000D_
        });_x000D_
    });
_x000D_
_x000D_
_x000D_

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

Try this function

getQuantileGroupNum <- function(vec, group_num, decreasing=FALSE) {
  if(decreasing) {
    abs(cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T) - group_num - 1)
  } else {
    cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T)
  }
}
> t1 <- runif(7)
> t1
[1] 0.4336094 0.2842928 0.5578876 0.2678694 0.6495285 0.3706474 0.5976223
> getQuantileGroupNum(t1, 4)
[1] 2 1 3 1 4 2 4
> getQuantileGroupNum(t1, 4, decreasing=T)
[1] 3 4 2 4 1 3 1

What is Haskell used for in the real world?

This is a pretty good source for info about Haskell and its uses:

Open Source Haskell Releases and Growth

How to set the LDFLAGS in CMakeLists.txt?

For linking against libraries see Andre's answer.

For linker flags - the following 4 CMake variables:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

can be easily manipulated for different configs (debug, release...) with the ucm_add_linker_flags macro of ucm

Why can't I use the 'await' operator within the body of a lock statement?

Stephen Taub has implemented a solution to this question, see Building Async Coordination Primitives, Part 7: AsyncReaderWriterLock.

Stephen Taub is highly regarded in the industry, so anything he writes is likely to be solid.

I won't reproduce the code that he posted on his blog, but I will show you how to use it:

/// <summary>
///     Demo class for reader/writer lock that supports async/await.
///     For source, see Stephen Taub's brilliant article, "Building Async Coordination
///     Primitives, Part 7: AsyncReaderWriterLock".
/// </summary>
public class AsyncReaderWriterLockDemo
{
    private readonly IAsyncReaderWriterLock _lock = new AsyncReaderWriterLock(); 

    public async void DemoCode()
    {           
        using(var releaser = await _lock.ReaderLockAsync()) 
        { 
            // Insert reads here.
            // Multiple readers can access the lock simultaneously.
        }

        using (var releaser = await _lock.WriterLockAsync())
        {
            // Insert writes here.
            // If a writer is in progress, then readers are blocked.
        }
    }
}

If you want a method that's baked into the .NET framework, use SemaphoreSlim.WaitAsync instead. You won't get a reader/writer lock, but you will get tried and tested implementation.

How to highlight cell if value duplicate in same column for google spreadsheet?

From the "Text Contains" dropdown menu select "Custom formula is:", and write: "=countif(A:A, A1) > 1" (without the quotes)

I did exactly as zolley proposed, but there should be done small correction: use "Custom formula is" instead of "Text Contains". And then conditional rendering will work.

Screenshot from menu

Unable to start MySQL server

Go to MySQL installer and click Reconfigure (don't change any existing settings). This should start the server and you'll be off.

How to get main div container to align to centre?

I would omit the * { text-align:center } declaration, as it sets center alignment for all elements.

Usually with a fixed width container margin: 0 auto should be enough

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Just in case it helps any one like me in future:

I have had this issue for 24 hours now, on 3 different 64-bit machines(Win7 , Windows 8.1 VM and WIn 8.1 laptop) - whilst trying to build WebKit with VS 2017.

The simple issue here is that the VC++ compiler (i.e cl.exe and it's dependent DLLs) is not visible to CMake. Simple. By making the VC++ folders containing those binaries visible to CMake and your working command prompt(if you're running Cmake from a command prompt), voila! (In addition to key points raised by others , above)

Anyway, after all kinds of fixes - as posted on these many forums- I discovered that it was SIMPLY a matter of ensuring that the PATH variable's contents are not cluttered with multiple Visual Studio BIN paths etc; and instead, points to :

a) the location of your compiler (i.e. cl.exe for your preferred version of Visual Studio ), which in my case(targeting 64-bit platform, and developing on a 64-bit host) is: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\Hostx64\x64

b) and in addition, the folder containing a dependent DLL called (which cl.exe is dependent on): api-ms-win-crt-runtime-l1-1-0.dll - which on my machine is:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Remote Debugger\x64

These two directories being added to a simplified and CUSTOM System Path variable(working under a Admin priviledged commmand prompt), eliminated my "No CMAKE_C_COMPILER could be found" and "No CMAKE_CXX_COMPILER could be found." errors.

Hope it helps someone.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

Create list of object from another using Java 8 Streams

I prefer to solve this in the classic way, creating a new array of my desired data type:

List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));

How to convert const char* to char* in C?

You can use the strdup function which has the following prototype

char *strdup(const char *s1);

Example of use:

#include <string.h>

char * my_str = strdup("My string literal!");
char * my_other_str = strdup(some_const_str);

or strcpy/strncpy to your buffer

or rewrite your functions to use const char * as parameter instead of char * where possible so you can preserve the const

How do I simulate placeholder functionality on input date field?

The HTML5 date input field actually does not support the attribute for placeholder. It will always be ignored by the browser, at least as per the current spec.

As noted here

How to call Stored Procedure in a View?

If you are using Sql Server 2005 you can use table valued functions. You can call these directly and pass paramters, whilst treating them as if they were tables.

For more info check out Table-Valued User-Defined Functions

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Reload activity in Android

I don't think that's a good idea... it'd be better to implement a cleaner method. For instance, if your activity holds a form, the cleaner method could just clear each widget in the form and delete all temporary data. I guess that's what you want: restore the activity to its initial state.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

"’" showing on page instead of " ' "

In DBeaver (or other editors) the script file you're working can prompt to save as UTF8 and that will change the char:

–

into

–

or

–

Multiple submit buttons in the same form calling different Servlets

You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.

function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});

How do I inject a controller into another controller in AngularJS

<div ng-controller="TestCtrl1">
    <div ng-controller="TestCtrl2">
      <!-- your code--> 
    </div> 
</div>

This works best in my case, where TestCtrl2 has it's own directives.

var testCtrl2 = $controller('TestCtrl2')

This gives me an error saying scopeProvider injection error.

   var testCtrl1ViewModel = $scope.$new();
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); 

This doesn't really work if you have directives in 'TestCtrl1', that directive actually have a different scope from this one created here. You end up with two instances of 'TestCtrl1'.

How to get docker-compose to always re-create containers from fresh images?

You can pass --force-recreate to docker compose up, which should use fresh containers.

I think the reasoning behind reusing containers is to preserve any changes during development. Note that Compose does something similar with volumes, which will also persist between container recreation (a recreated container will attach to its predecessor's volumes). This can be helpful, for example, if you have a Redis container used as a cache and you don't want to lose the cache each time you make a small change. At other times it's just confusing.

I don't believe there is any way you can force this from the Compose file.

Arguably it does clash with immutable infrastructure principles. The counter-argument is probably that you don't use Compose in production (yet). Also, I'm not sure I agree that immutable infra is the basic idea of Docker, although it's certainly a good use case/selling point.

pip install returning invalid syntax

Don't enter in the python shall, Install in the command directory.

Not inside the python pip cannot be installed inside the python.

Even in the version 3.+ you don't have to write the python 3 instead just python.

which looks like

python -m pip install --upgrade pip

and then install others

python -m pip install jupyter

Global variables in header file

There are 3 scenarios, you describe:

  1. with 2 .c files and with int i; in the header.
  2. With 2 .c files and with int i=100; in the header (or any other value; that doesn't matter).
  3. With 1 .c file and with int i=100; in the header.

In each scenario, imagine the contents of the header file inserted into the .c file and this .c file compiled into a .o file and then these linked together.

Then following happens:

  1. works fine because of the already mentioned "tentative definitions": every .o file contains one of them, so the linker says "ok".

  2. doesn't work, because both .o files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o files which are linked together at a given time.

  3. works of course, because you have only one .o file and so no possibility for collision.

IMHO a clean thing would be

  • to put either extern int i; or just int i; into the header file,
  • and then to put the "real" definition of i (namely int i = 100;) into file1.c. In this case, this initialization gets used at the start of the program and the corresponding line in main() can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i in real programs.)

Default behavior of "git push" without a branch specified

git push origin will push all changes on the local branches that have matching remote branches at origin As for git push

Works like git push <remote>, where <remote> is the current branch's remote (or origin, if no remote is configured for the current branch).

From the Examples section of the git-push man page

CSS align images and text on same line

You can simply center the image and text in the parent tag by setting

div {
     text-align: center;
}

vertical center the img and span

img {
     vertical-align:middle;
}
span {
     vertical-align:middle;
}

You can just add second set below, and one thing to mention is that h4 has block display attribute, so you might want to set

h4 {
    display: inline-block
}

to set the h4 "inline".

The full example is shown here.

_x000D_
_x000D_
<div id="photo" style="text-align: center">_x000D_
  <img style="vertical-align:middle" src="https://via.placeholder.com/22x22" alt="">_x000D_
  <span style="vertical-align:middle">Take a photo</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

How do I detect when someone shakes an iPhone?

I came across this post looking for a "shaking" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more "shaking action" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    if (self.lastAcceleration) {
        if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {
            //Shaking here, DO stuff.
            shakeCount = 0;
        } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {
            shakeCount = shakeCount + 5;
        }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {
            if (shakeCount > 0) {
                shakeCount--;
            }
        }
    }
    self.lastAcceleration = acceleration;
}

- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {
    double
    deltaX = fabs(last.x - current.x),
    deltaY = fabs(last.y - current.y),
    deltaZ = fabs(last.z - current.z);

    return
    (deltaX > threshold && deltaY > threshold) ||
    (deltaX > threshold && deltaZ > threshold) ||
    (deltaY > threshold && deltaZ > threshold);
}

PS: I've set the update interval to 1/15th of a second.

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];

jquery Ajax call - data parameters are not being passed to MVC Controller action

You need add -> contentType: "application/json; charset=utf-8",

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

How to change current working directory using a batch file

Specify /D to change the drive also.

CD /D %root%

The name 'controlname' does not exist in the current context

I know this is an old question, but I had a similar problem and wanted to post my solution in case it could benefit someone else. I encountered the problem while learning to use:

  • ASP.NET 3.5
  • C#
  • VS2008

I was trying to create an AJAX-enabled page (look into a tutorial about using the ScriptManager object if you aren't familiar with this). I tried to access the HTML elements in the page via the C# code, and I was getting an error stating the the identifier for the HTML ID value "does not exist in the current context."

To solve it, I had to do the following:

1. Run at server

To access the HTML element as a variable in the C# code, the following value must be placed in the HTML element tag in the aspx file:

runat="server"

Some objects in the Toolbox in the Visual Studio IDE do not automatically include this value when added to the page.

2. Regenerate the auto-generated C# file:

  • In the Solution Explorer, under the aspx file there should be two files: *.aspx.cs and *.aspx.designer.cs. The designer file is auto-generated.
  • Delete the existing *.aspx.designer.cs file. Make sure you only delete the designer file. Do not delete the other one, because it contains your C# code for the page.
  • Right-click on the parent aspx file. In the pop-up menu, select Convert to Web Application.

Now the element should be accessible in the C# code file.

newline in <td title="">

One way to achieve similar effect would be through CSS:

<td>Cell content.
  <div class="popup">
    This is the popup.
    <br>
    Another line of popup.
  </div>
</td>

And then use the following in CSS:

td div.popup { display: none; }
td:hover div.popup { display: block; position: absolute; }

You will want to add some borders and background to make the popup look decent, but this should sketch the idea. It has some drawbacks though, for example the popup is not positioned relative to mouse but relative to the containing cell.

Subset data to contain only columns whose names match a condition

Using dplyr you can:

df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))

How do I make a transparent canvas in html5?

Iif you want a particular <canvas id="canvasID"> to be always transparent you just have to set

#canvasID{
    opacity:0.5;
}

Instead, if you want some particular elements inside the canvas area to be transparent, you have to set transparency when you draw, i.e.

context.fillStyle = "rgba(0, 0, 200, 0.5)";

How can I count occurrences with groupBy?

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

list.add("Hello");
list.add("Hello");
list.add("World");

Map<String, List<String>> collect = list.stream()
                                        .collect(Collectors.groupingBy(o -> o));
collect.entrySet()
       .forEach(e -> System.out.println(e.getKey() + " - " + e.getValue().size()));

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

The only solution worked for me is putting the .jar file under WEB-INF/lib . Hope this will help.

Convert string to Time

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

How to create an array of object literals in a loop?

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});

Radio buttons not checked in jQuery

if ($("input").is(":not(:checked)"))

AFAIK, this should work, tested against the latest stable jQuery (1.2.6).

jQuery: get parent, parent id?

Here are 3 examples:

_x000D_
_x000D_
$(document).on('click', 'ul li a', function (e) {_x000D_
    e.preventDefault();_x000D_
_x000D_
    var example1 = $(this).parents('ul:first').attr('id');_x000D_
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
    var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
  _x000D_
    var example3 = $(this).closest('ul').attr('id');_x000D_
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
  _x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
  <li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
  <h1>Results:</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Let me know whether it was helpful.

How to use DISTINCT and ORDER BY in same SELECT statement?

Just use this code, If you want values of [Category] and [CreationDate] columns

SELECT [Category], MAX([CreationDate]) FROM [MonitoringJob] 
             GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Or use this code, If you want only values of [Category] column.

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

You'll have all the distinct records what ever you want.

How do you list the primary key of a SQL Server table?

Sys.Objects Table contains row for each user-defined, schema-scoped object .

Constraints created like Primary Key or others will be the object and Table name will be the parent_object

Query sys.Objects and collect the Object's Ids of Required Type

declare @TableName nvarchar(50)='TblInvoice' -- your table name
declare @TypeOfKey nvarchar(50)='PK' -- For Primary key

SELECT Name FROM sys.objects
WHERE type = @TypeOfKey 
AND  parent_object_id = OBJECT_ID (@TableName)

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

Install a Python package into a different directory using pip?

With pip v1.5.6 on Python v2.7.3 (GNU/Linux), option --root allows to specify a global installation prefix, (apparently) irrespective of specific package's options. Try f.i.,

$ pip install --root=/alternative/prefix/path package_name

How to simulate a real mouse click using java?

FYI, in newer versions of Windows, there's a new setting where if a program is running in Adminstrator mode, then another program not in administrator mode, cannot send any clicks or other input events to it. Check your source program to which you are trying to send the click (right click -> properties), and see if the 'run as administrator' checkbox is selected.

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

What is the purpose of the return statement?

This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.

In line number 4:

def ret(n):
    if n > 9:
         temp = "two digits"
         return temp     #Line 4        
    else:
         temp = "one digit"
         return temp     #Line 8
    print("return statement")
ret(10)

After the conditional statement gets executed the ret() function gets terminated due to return temp (line 4). Thus the print("return statement") does not get executed.

Output:

two digits   

This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.

Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.

To bring out the difference between print and return:

def ret(n):
    if n > 9:
        print("two digits")
        return "two digits"           
    else :
        print("one digit")
        return "one digit"        
ret(25)

Output:

two digits
'two digits'

Javascript Iframe innerHTML

document.getElementById('iframe01').outerHTML

Solution to "subquery returns more than 1 row" error

When one gets the error 'sub-query returns more than 1 row', the database is actually telling you that there is an unresolvable circular reference. It's a bit like using a spreadsheet and saying cell A1 = B1 and then saying B1 = A1. This error is typically associated with a scenario where one needs to have a double nested sub-query. I would recommend you look up a thing called a 'cross-tab query' this is the type of query one normally needs to solve this problem. It's basically an outer join (left or right) nested inside a sub-query or visa versa. One can also solve this problem with a double join (also considered to be a type of cross-tab query) such as below:

CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_GET_VEHICLES_IN`(
    IN P_email VARCHAR(150),
    IN P_credentials VARCHAR(150)
)
BEGIN
    DECLARE V_user_id INT(11);
    SET V_user_id = (SELECT user_id FROM users WHERE email = P_email AND credentials = P_credentials LIMIT 1);
    SELECT vehicles_in.vehicle_id, vehicles_in.make_id, vehicles_in.model_id, vehicles_in.model_year,
    vehicles_in.registration, vehicles_in.date_taken, make.make_label, model.model_label
    FROM make
    LEFT OUTER JOIN vehicles_in ON vehicles_in.make_id = make.make_id
    LEFT OUTER JOIN model ON model.make_id = make.make_id AND vehicles_in.model_id = model.model_id
    WHERE vehicles_in.user_id = V_user_id;
END

In the code above notice that there are three tables in amongst the SELECT clause and these three tables show up after the FROM clause and after the two LEFT OUTER JOIN clauses, these three tables must be distinct amongst the FROM and LEFT OUTER JOIN clauses to be syntactically correct.

It is noteworthy that this is a very important construct to know as a developer especially if you're writing periodical report queries and it's probably the most important skill for any complex cross referencing, so all developers should study these constructs (cross-tab and double join).

Another thing I must warn about is: If you are going to use a cross-tab as a part of a working system and not just a periodical report, you must check the record count and reconfigure the join conditions until the minimum records are returned, otherwise large tables and cross-tabs can grind your server to a halt. Hope this helps.

XAMPP Object not found error

Agree @Drixson Oseña: You should not write localhost/xampp/...., else write for e.g: localhost/mw-config/index.php

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

Mongoose: findOneAndUpdate doesn't return updated document

I know, I am already late but let me add my simple and working answer here

const query = {} //your query here
const update = {} //your update in json here
const option = {new: true} //will return updated document

const user = await User.findOneAndUpdate(query , update, option)

Running a cron job on Linux every six hours

0 */6 * * * command

This will be the perfect way to say 6 hours a day.

Your command puts in for six minutes!

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

How can I use the binary operator alongside the date filter?

<span class="gallery-date">{{gallery.date | date:'mediumDate' || "Date Empty"}}</span>

you also try:

<span class="gallery-date">{{ gallery.date == 'NULL' ? 'mediumDate' : "gallery.date"}}</span>