Programs & Examples On #Noise reduction

Anything related to noise reduction techniques and tools. This tag may be employed for questions on algorithms (and corresponding implementations) used to reduce noise in digital data and signals.

How can I escape a double quote inside double quotes?

A simple example of escaping quotes in the shell:

$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc

It's done by finishing an already-opened one ('), placing the escaped one (\'), and then opening another one (').

Alternatively:

$ echo 'abc'"'"'abc'
abc'abc
$ echo "abc"'"'"abc"
abc"abc

It's done by finishing already opened one ('), placing a quote in another quote ("'"), and then opening another one (').

More examples: Escaping single-quotes within single-quoted strings

Including jars in classpath on commandline (javac or apt)

Using:

apt HelloImpl.java -classpath /sac/tools/thirdparty/jaxws-ri/jaxws-ri-2.1.4/lib/jsr181-api.jar:.

works but it gives me another error, see new question

java.util.Date and getYear()

Use date format

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);

Node package ( Grunt ) installed but not available

In my case, i need modify the file /usr/local/bin/grunt in line 1 ( don't make this ):

 #!/usr/bin/env node //remove this line
 #!/usr/bin/env nodejs // and put this line to run with nodejs

Edited:

To avoid problems, I created a link with the name of "node" because many other programs still use "node" command.

 sudo ln -s /usr/bin/nodejs /usr/sbin/node

Handling back button in Android Navigation Component

In 2.1.0-alpha06

If you want to handle backpress only in current fragment

requireActivity().onBackPressedDispatcher.addCallback(this@LoginFragment) {
    // handle back event
}

For whole Activity

requireActivity().onBackPressedDispatcher.addCallback() {
    // handle back event
}

a tag as a submit button?

This is an improve of @ComFreek ans:

<form id="myform">
  <!-- form elements -->
  <a href="javascript:;" onclick="document.getElementById('myform').submit()">Submit</a>
</form>

So the will not trigger action and reload your page. Specially if your are developing with a framework with SPA.

Google Maps API warning: NoApiKeys

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

Get the key here: GoogleApiKey Generation site

Regex to check if valid URL that ends in .jpg, .png, or .gif

(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png) worked really well for me.

This will match URLs in the following forms:

https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png

Check this regular expression against the URLs here: http://regexr.com/3g1v7

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

The accepted answer did not resolve the issue, hence posting what worked for me.

Error/Issue: While trying to run my application as a Java application or as a Spring boot application, I am getting below error

A JNI error has occurred, please check your installation and try again. A Java exception has occured.

as well as getting this error on console Exception in thread "main" java.lang.UnsupportedClassVersionError: com/example/demo/IocApplication has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

What is the Root cause?

The reason for this error is that

  • the Code is getting compiled on a higher version, in my case, it is version 11.. and
  • the code is getting executed on a lower version, in my case it is version 8.
  • ie: Java(JDK) compiled code on 11 , where as JRE version is 8.

Where did I configure JDK 11 and JRE 8 ?

  • I am using SpringToolSuite (STS). When I created the project, the JRE System library in the build path, which got added is the default JRE library version of 8 (1.8) But When I go to Project -> properties -> Java Compiler -> Compiler Compliance Level, it is by default having a selected version of 11

Solution:

Project -> properties -> Java Compiler -> Compiler Compliance Level

  • Set the Compiler Compliance Level to 1.8 That's it. Now you are compiling your code in 1.8 and executing the compiled code with a JRE 1.8.

Adding 30 minutes to time formatted as H:i in PHP

In order for that to work $time has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00'); which is what you seem to do, because then I get 0:30 and 1:30 as results too.

Try

$time = strtotime('10:00');

As an alternative, consider using DateTime (the below requires PHP 5.3 though):

$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M'));              // substract 30 minutes
echo $dt->format('H:i');                          // echo modified time
$dt->add(new DateInterval('PT1H'));               // add 1 hour
echo $dt->format('H:i');                          // echo modified time

or procedural if you don't like OOP

$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');

Trusting all certificates with okHttp

You should never look to override certificate validation in code! If you need to do testing, use an internal/test CA and install the CA root certificate on the device or emulator. You can use BurpSuite or Charles Proxy if you don't know how to setup a CA.

How to determine the longest increasing subsequence using dynamic programming?

The O(NLog(N)) Approach To Find Longest Increasing Sub sequence
Let us maintain an array where the ith element is the smallest possible number with which a i sized sub sequence can end.

On purpose I am avoiding further details as the top voted answer already explains it, but this technique eventually leads to a neat implementation using the set data structure (at least in c++).

Here is the implementation in c++ (assuming strictly increasing longest sub sequence size is required)

#include <bits/stdc++.h> // gcc supported header to include (almost) everything
using namespace std;
typedef long long ll;

int main()
{
  ll n;
  cin >> n;
  ll arr[n];
  set<ll> S;

  for(ll i=0; i<n; i++)
  {
    cin >> arr[i];
    auto it = S.lower_bound(arr[i]);
    if(it != S.end())
      S.erase(it);
    S.insert(arr[i]);
  }

  cout << S.size() << endl; // Size of the set is the required answer

  return 0;
}

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

My go environment looked similar to yours.

$go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go-1.6"
GOTOOLDIR="/usr/lib/go-1.6/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT="1"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

I resolved it with setting GOPATH to /usr/lib/go. Try it out.

export GOPATH=/usr/lib/go
export PATH=$PATH:$GOPATH/bin

XSLT string replace

The rouine is pretty good, however it causes my app to hang, so I needed to add the case:

  <xsl:when test="$text = '' or $replace = ''or not($replace)" >
    <xsl:value-of select="$text" />
    <!-- Prevent thsi routine from hanging -->
  </xsl:when>

before the function gets called recursively.

I got the answer from here: When test hanging in an infinite loop

Thank you!

Convert XML String to Object

You can use xsd.exe to create schema bound classes in .Net then XmlSerializer to Deserialize the string : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx

How to insert multiple rows from array using CodeIgniter framework?

Assembling one INSERT statement with multiple rows is much faster in MySQL than one INSERT statement per row.

That said, it sounds like you might be running into string-handling problems in PHP, which is really an algorithm problem, not a language one. Basically, when working with large strings, you want to minimize unnecessary copying. Primarily, this means you want to avoid concatenation. The fastest and most memory efficient way to build a large string, such as for inserting hundreds of rows at one, is to take advantage of the implode() function and array assignment.

$sql = array(); 
foreach( $data as $row ) {
    $sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));

The advantage of this approach is that you don't copy and re-copy the SQL statement you've so far assembled with each concatenation; instead, PHP does this once in the implode() statement. This is a big win.

If you have lots of columns to put together, and one or more are very long, you could also build an inner loop to do the same thing and use implode() to assign the values clause to the outer array.

How do I find out which computer is the domain controller in Windows programmatically?

With the most simple programming language: DOS batch

echo %LOGONSERVER%

Using custom std::set comparator

Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.

template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
    struct ftor {
        bool operator()( T const &l, T const &r )
            { return comp( l, r ); }
    };
public:
    typedef std::set< T, ftor > t;
};

// usage

bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!

Wow, I think that was worth the trouble!

CSS background image to fit width, height should auto-scale in proportion

body{
    background-image: url(../url/imageName.jpg);
    background-attachment: fixed;
    background-size: auto 100%;
    background-position: center;
}

How do I use shell variables in an awk script?

It seems that the good-old ENVIRON built-in hash is not mentioned at all. An example of its usage:

$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Plotting power spectrum in python

if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n) is the frequency array of every point in fft. You can use rfft to calculate the fft in your data is real values:

import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)

enter image description here

signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

This is a well-known issue and based on this answer you could add setLenient:

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Now, if you add this to your retrofit, it gives you another error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

For better comprehension, compare your response with Github api.

Suggestion: to find out what's going on to your request/response add HttpLoggingInterceptor in your retrofit.

Based on this answer your ServiceHelper would be:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

Also don't forget to add:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Filter Linq EXCEPT on properties

MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy

https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs

namespace MoreLinq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    static partial class MoreEnumerable
    {
        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector)
        {
            return ExceptBy(first, second, keySelector, null);
        }

        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
        /// If null, the default equality comparer for <c>TSource</c> is used.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
            if (keySelector == null) throw new ArgumentNullException("keySelector");
            return ExceptByImpl(first, second, keySelector, keyComparer);
        }

        private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
            foreach (var element in first)
            {
                var key = keySelector(element);
                if (keys.Contains(key))
                {
                    continue;
                }
                yield return element;
                keys.Add(key);
            }
        }
    }
}

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I got the same error

Could not connect to the Magento WebService API: SOAP-ERROR: Parsing WSDL: Couldn't load from 'example.com/api/soap/?wsdl' : failed to load external entity "example.com/api/soap/?wsdl"

and my issue resolved once I update my Magento Root URL to

example.com/index.php/api/soap/?wsdl

Yes, I was missing index.php that causes the error.

"java.lang.OutOfMemoryError : unable to create new native Thread"

I encountered same issue during the load test, the reason is because of JVM is unable to create a new Java thread further. Below is the JVM source code

if (native_thread->osthread() == NULL) {    
// No one should hold a reference to the 'native_thread'.    
    delete native_thread;   
if (JvmtiExport::should_post_resource_exhausted()) {      
    JvmtiExport::post_resource_exhausted(        
        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 
        JVMTI_RESOURCE_EXHAUSTED_THREADS, 
        "unable to create new native thread");    
    } THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "unable to create new native thread");  
} Thread::start(native_thread);`

Root cause : JVM throws this exception when JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR (resources exhausted (means memory exhausted) ) or JVMTI_RESOURCE_EXHAUSTED_THREADS (Threads exhausted).

In my case Jboss is creating too many threads , to serve the request, but all the threads are blocked . Because of this, JVM is exhausted with threads as well with memory (each thread holds memory , which is not released , because each thread is blocked).

Analyzed the java thread dumps observed nearly 61K threads are blocked by one of our method, which is causing this issue . Below is the portion of Thread dump

"SimpleAsyncTaskExecutor-16562" #38070 prio=5 os_prio=0 tid=0x00007f9985440000 nid=0x2ca6 waiting for monitor entry [0x00007f9d58c2d000]
   java.lang.Thread.State: BLOCKED (on object monitor)

What is the OAuth 2.0 Bearer Token exactly?

Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for you a Token. Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer token basically says "Give the bearer of this token access".

The Bearer Token is normally some kind of opaque value created by the authentication server. It isn't random; it is created based upon the user giving you access and the client your application getting access.

In order to access an API for example you need to use an Access Token. Access tokens are short lived (around an hour). You use the bearer token to get a new Access token. To get an access token you send the Authentication server this bearer token along with your client id. This way the server knows that the application using the bearer token is the same application that the bearer token was created for. Example: I can't just take a bearer token created for your application and use it with my application it wont work because it wasn't generated for me.

Google Refresh token looks something like this: 1/mZ1edKKACtPAb7zGlwSzvs72PvhAbGmB8K1ZrGxpcNM

copied from comment: I don't think there are any restrictions on the bearer tokens you supply. Only thing I can think of is that its nice to allow more than one. For example a user can authenticate the application up to 30 times and the old bearer tokens will still work. oh and if one hasn't been used for say 6 months I would remove it from your system. It's your authentication server that will have to generate them and validate them so how it's formatted is up to you.

Update:

A Bearer Token is set in the Authorization header of every Inline Action HTTP Request. For example:

POST /rsvp?eventId=123 HTTP/1.1
Host: events-organizer.com
Authorization: Bearer AbCdEf123456
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions)

rsvpStatus=YES

The string "AbCdEf123456" in the example above is the bearer authorization token. This is a cryptographic token produced by the authentication server. All bearer tokens sent with actions have the issue field, with the audience field specifying the sender domain as a URL of the form https://. For example, if the email is from [email protected], the audience is https://example.com.

If using bearer tokens, verify that the request is coming from the authentication server and is intended for the the sender domain. If the token doesn't verify, the service should respond to the request with an HTTP response code 401 (Unauthorized).

Bearer Tokens are part of the OAuth V2 standard and widely adopted by many APIs.

Check with jquery if div has overflowing elements

This is the jQuery solution that worked for me. offsetWidth etc. didn't work.

function is_overflowing(element, extra_width) {
    return element.position().left + element.width() + extra_width > element.parent().width();
}

If this doesn't work, ensure that elements' parent has the desired width (personally, I had to use parent().parent()). position is relative to the parent. I've also included extra_width because my elements ("tags") contain images which take small time to load, but during the function call they have zero width, spoiling the calculation. To get around that, I use the following calling code:

var extra_width = 0;
$(".tag:visible").each(function() {
    if (!$(this).find("img:visible").width()) {
        // tag image might not be visible at this point,
        // so we add its future width to the overflow calculation
        // the goal is to hide tags that do not fit one line
        extra_width += 28;
    }
    if (is_overflowing($(this), extra_width)) {
        $(this).hide();
    }
});

Hope this helps.

How to sort 2 dimensional array by column value?

in one line:

var cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
]


function myFunction() {
  return cars.sort((a, b)=> a.year - b.year)
}

Xcode 4 - build output directory

Another thing to check before you start playing with Xcode preferences is:

Select your target and go to Build Settings > Packaging > Wrapper Extension

The value there should be: app

If not double click it and type "app" without the qoutes.

HTML meta tag for content language

Html5 also recommend to use <html lang="es-ES"> The small letter lang tag only specifies: language code The large letter specifies: country code

This is really useful for ie.Chrome, when the browser is proposing to translate web content(ie google translate)

How to execute an Oracle stored procedure via a database link

check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html

one needs to use something like

cmd.CommandText = "BEGIN foo@v; END;" 

worked for me in vb.net, c#

Reset IntelliJ UI to Default

On Mac OS for IntelliJ v12, shut down the IDE, and then you can execute:

rm -rf ~/Library/Preferences/IdeaIC12/*

Restart the IDE, or open a pom.xml of your choosing. You will be asked whether you want to import the preferences from an existing IntelliJ instance. Select the "No, I do not have a previous IntelliJ version" radio button.

Check if string is neither empty nor space in shell script

To check if a string is empty or contains only whitespace you could use:

shopt -s extglob  # more powerful pattern matching

if [ -n "${str##+([[:space:]])}" ]; then
    echo '$str is not null or space'
fi

See Shell Parameter Expansion and Pattern Matching in the Bash Manual.

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

PHP __get and __set magic methods

Intenta con:

__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}

Jquery change background color

try putting a delay on the last color fade.

$("p#44.test").delay(3000).css("background-color","red");

What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!

iOS - Dismiss keyboard when touching outside of UITextField

Plenty of great answers here about using UITapGestureRecognizer--all of which break UITextField's clear (X) button. The solution is to suppress the gesture recognizer via its delegate:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    BOOL touchViewIsButton = [touch.view isKindOfClass:[UIButton class]];
    BOOL touchSuperviewIsTextField = [[touch.view superview] isKindOfClass:[UITextField class]];
    return !(touchViewIsButton && touchSuperviewIsTextField);
}

It's not the most robust solution but it works for me.

How to get a unique device ID in Swift?

You can use identifierForVendor public property present in UIDevice class

let UUIDValue = UIDevice.currentDevice().identifierForVendor!.UUIDString
        print("UUID: \(UUIDValue)")

EDIT Swift 3:

UIDevice.current.identifierForVendor!.uuidString

END EDIT

Screenshot for property hierarchy

VMware Workstation and Device/Credential Guard are not compatible

install the latest vmware workstation > 15.5.5 version

which has support of Hyper-V Host

With the release of VMware Workstation/Player 15.5. 5 or >, we are very excited and proud to announce support for Windows hosts with Hyper-V mode enabled! As you may know, this is a joint project from both Microsoft and VMware

https://blogs.vmware.com/workstation/2020/05/vmware-workstation-now-supports-hyper-v-mode.html

i installed the VMware.Workstation.Pro.16.1.0

and now it fixed my issue now i am using docker & vmware same time even my window Hyper-V mode is enabled

How can I connect to MySQL on a WAMP server?

Try opening Port 3306, and using that in the connection string not 8080.

Align button at the bottom of div using CSS

Goes to the right and can be used the same way for the left

.yourComponent
{
   float: right;
   bottom: 0;
}

CSS animation delay in repeating

Delay is possible only once at the beginning with infinite. in sort delay doesn't work with infinite loop. for that you have to keep keyframes animation blanks example:

@-webkit-keyframes barshine {
  10% {background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(100%,#7db9e8));
    }
  60% {background: -webkit-linear-gradient(top, #7db9e8 0%,#d32a2d 100%);}
}

it will animate 10% to 60% and wait to complete 40% more. So 40% comes in delay.

find fiddle example

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

What is __stdcall?

I agree that all the answers so far are correct, but here is the reason. Microsoft's C and C++ compilers provide various calling conventions for (intended) speed of function calls within an application's C and C++ functions. In each case, the caller and callee must agree on which calling convention to use. Now, Windows itself provides functions (APIs), and those have already been compiled, so when you call them you must conform to them. Any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention.

Force encode from US-ASCII to UTF-8 (iconv)

ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded. The bytes in the ASCII file and the bytes that would result from "encoding it to UTF-8" would be exactly the same bytes. There's no difference between them, so there's no need to do anything.

It looks like your problem is that the files are not actually ASCII. You need to determine what encoding they are using, and transcode them properly.

Add space between <li> elements

Since you are asking for space between , I would add an override to the last item to get rid of the extra margin there:

_x000D_
_x000D_
li {_x000D_
  background: red;_x000D_
  margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
 margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  background: silver;_x000D_
  padding: 1px;  _x000D_
  padding-left: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding to the ul-element to prevent the collapsing. Try removing the li:last-child-rule, and you'll see that the last item now extends the size of the ul-element.

String.strip() in Python

In this case, you might get some differences. Consider a line like:

"foo\tbar "

In this case, if you strip, then you'll get {"foo":"bar"} as the dictionary entry. If you don't strip, you'll get {"foo":"bar "} (note the extra space at the end)

Note that if you use line.split() instead of line.split('\t'), you'll split on every whitespace character and the "striping" will be done during splitting automatically. In other words:

line.strip().split()

is always identical to:

line.split()

but:

line.strip().split(delimiter)

Is not necessarily equivalent to:

line.split(delimiter)

How to select the first row for each group in MySQL?

Yet another way to do it

Select max from group that works in views

SELECT * FROM action a 
WHERE NOT EXISTS (
   SELECT 1 FROM action a2 
   WHERE a2.user_id = a.user_id 
   AND a2.action_date > a.action_date 
   AND a2.action_type = a.action_type
)
AND a.action_type = "CF"

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I had the same problem with something like

@foreach (var item in Model)
{
    @Html.DisplayFor(m => !item.IsIdle, "BoolIcon")
}

I solved this just by doing

@foreach (var item in Model)
{
    var active = !item.IsIdle;
    @Html.DisplayFor(m => active , "BoolIcon")
}

When you know the trick, it's simple.

The difference is that, in the first case, I passed a method as a parameter whereas in the second case, it's an expression.

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Laravel Eloquent - Get one Row

Using Laravel Eloquent you can get one row using first() method,

it returns first row of table if where() condition is not found otherwise it gives the first matched row of given criteria.

Syntax:

Model::where('fieldname',$value)->first();

Example:

$user = User::where('email',$email)->first(); 
//OR
//$user = User::whereEmail($email)->first();

Import CSV file as a pandas DataFrame

pandas to the rescue:

import pandas as pd
print pd.read_csv('value.txt')

        Date    price  factor_1  factor_2
0  2012-06-11  1600.20     1.255     1.548
1  2012-06-12  1610.02     1.258     1.554
2  2012-06-13  1618.07     1.249     1.552
3  2012-06-14  1624.40     1.253     1.556
4  2012-06-15  1626.15     1.258     1.552
5  2012-06-16  1626.15     1.263     1.558
6  2012-06-17  1626.15     1.264     1.572

This returns pandas DataFrame that is similar to R's.

Converting an int or String to a char array on Arduino

None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed

byte str_len = str.length();

// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...

byte arrayPointer = 0;

while (str_len)
{
    // I was outputting the digits to the TX buffer

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
    {
        UDR0 = str[arrayPointer];
        --str_len;
        ++arrayPointer;
    }
}

Way to go from recursion to iteration

My examples are in Clojure, but should be fairly easy to translate to any language.

Given this function that StackOverflows for large values of n:

(defn factorial [n]
  (if (< n 2)
    1
    (*' n (factorial (dec n)))))

we can define a version that uses its own stack in the following manner:

(defn factorial [n]
  (loop [n n
         stack []]
    (if (< n 2)
      (return 1 stack)
      ;; else loop with new values
      (recur (dec n)
             ;; push function onto stack
             (cons (fn [n-1!]
                     (*' n n-1!))
                   stack)))))

where return is defined as:

(defn return
  [v stack]
  (reduce (fn [acc f]
            (f acc))
          v
          stack))

This works for more complex functions too, for example the ackermann function:

(defn ackermann [m n]
  (cond
    (zero? m)
    (inc n)

    (zero? n)
    (recur (dec m) 1)

    :else
    (recur (dec m)
           (ackermann m (dec n)))))

can be transformed into:

(defn ackermann [m n]
  (loop [m m
         n n
         stack []]
    (cond
      (zero? m)
      (return (inc n) stack)

      (zero? n)
      (recur (dec m) 1 stack)

      :else
      (recur m
             (dec n)
             (cons #(ackermann (dec m) %)
                   stack)))))

How can I set a UITableView to grouped style

Setting that is not that hard as mentioned in the question. Actually it's pretty simple. Try this on storyboard.

enter image description here

How to quit a java app from within the program

System.exit(0);

The "0" lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1);, or with another non-zero number corresponding to the specific error.

Also, as others have mentioned, clean up first! That involves closing files and other open resources.

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

The pageContext is an implicit object available in JSPs. The EL documentation says

The context for the JSP page. Provides access to various objects including:
servletContext: ...
session: ...
request: ...
response: ...

Thus this expression will get the current HttpServletRequest object and get the context path for the current request and append /JSPAddress.jsp to it to create a link (that will work even if the context-path this resource is accessed at changes).

The primary purpose of this expression would be to keep your links 'relative' to the application context and insulate them from changes to the application path.


For example, if your JSP (named thisJSP.jsp) is accessed at http://myhost.com/myWebApp/thisJSP.jsp, thecontext path will be myWebApp. Thus, the link href generated will be /myWebApp/JSPAddress.jsp.

If someday, you decide to deploy the JSP on another server with the context-path of corpWebApp, the href generated for the link will automatically change to /corpWebApp/JSPAddress.jsp without any work on your part.

Undefined symbols for architecture armv7

I received the 'Undefined symbols for architecture armv7:' error when trying to compile a project that had the target build setting for 'C++ Standard Library' set to 'libc++' (necessary as the project was using some features from C++ 11), and the project included a sub-project that had the same setting set to 'libstdc++' (or compiler default as it is currently).

Changing the sub-project's 'C++ Standard Library' setting to libc++ fixed it, but only after first setting the deployment target for the sub-project to 5.0 or above (5.0 is necessary for libc++).

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

Hey I was following the tutorial on tutorialpoint.com. Add after you complete Step 2 - Install Apache Common Logging API: You must import external jar libraries to the project from the files downloaded at this step. For me the file name was "commons-logging-1.1.1".

How can I store HashMap<String, ArrayList<String>> inside a list?

Try the following:

List<Map<String, ArrayList<String>>> mapList = 
    new ArrayList<Map<String, ArrayList<String>>>();
mapList.add(map);

If your list must be of type List<HashMap<String, ArrayList<String>>>, then declare your map variable as a HashMap and not a Map.

How do I set a VB.Net ComboBox default value

If ComboBox1.SelectedIndex = -1 Then
    ComboBox1.SelectedIndex = 0    
End If

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Hadoop "Unable to load native-hadoop library for your platform" warning

After a continuous research as suggested by KotiI got resolved the issue.

hduser@ubuntu:~$ cd /usr/local/hadoop

hduser@ubuntu:/usr/local/hadoop$ ls

bin  include  libexec      logs        README.txt  share
etc  lib      LICENSE.txt  NOTICE.txt  sbin

hduser@ubuntu:/usr/local/hadoop$ cd lib

hduser@ubuntu:/usr/local/hadoop/lib$ ls
native

hduser@ubuntu:/usr/local/hadoop/lib$ cd native/

hduser@ubuntu:/usr/local/hadoop/lib/native$ ls

libhadoop.a       libhadoop.so        libhadooputils.a  libhdfs.so
libhadooppipes.a  libhadoop.so.1.0.0  libhdfs.a         libhdfs.so.0.0.0

hduser@ubuntu:/usr/local/hadoop/lib/native$ sudo mv * ../

Cheers

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.

How to display table data more clearly in oracle sqlplus

You can set the line size as per the width of the window and set wrap off using the following command.

set linesize 160;
set wrap off;

I have used 160 as per my preference you can set it to somewhere between 100 - 200 and setting wrap will not your data and it will display the data properly.

Swift - How to hide back button in navigation item?

That worked for me in Swift 5 like a charm, just add it to your viewDidLoad()

self.navigationItem.setHidesBackButton(true, animated: true)

CSS center content inside div

Try using flexbox. As an example, the following code shows the CSS for the container div inside which the contents needs to be centered aligned:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;

}

set date in input type date

For me the shortest way to get locale date and in correct format for input type="date" is this :

var d = new Date(); 
var today = d.getFullYear()+"-"+("0"+(d.getMonth()+1)).slice(-2)+"-"+("0"+d.getDate()).slice(-2);

Or this :

var d = new Date().toLocaleDateString().split('/');
var today = d[2]+"-"+("0"+d[0]).slice(-2)+"-"+("0"+d[1]).slice(-2);

Then just set the date input value :

$('#datePicker').val(today);

What does character set and collation mean exactly?

I suggest to use utf8mb4_unicode_ci, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

If we need to move from one component to another service then we have to define that service into app.module providers array.

How can we dynamically allocate and grow an array

You allocate a new Array (double the capacity, for instance), and move all elements to it.

Basically you need to check if the wordCount is about to hit the wordList.size(), when it does, create a new array with twice the length of the previous one, and copy all elements to it (create an auxiliary method to do this), and assign wordList to your new array.

To copy the contents over, you could use System.arraycopy, but I'm not sure that's allowed with your restrictions, so you can simply copy the elements one by one:

public String[] createNewArray(String[] oldArray){
    String[] newArray = new String[oldArray.length * 2];
    for(int i = 0; i < oldArray.length; i++) {
        newArray[i] = oldArray[i];
    }

    return newArray;
}

Proceed.

Can't bind to 'routerLink' since it isn't a known property

I'll add another case where I was getting the same error but just being a dummy. I had added [routerLinkActiveOptions]="{exact: true}" without yet adding routerLinkActive="active".

My incorrect code was

<a class="nav-link active" routerLink="/dashboard" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>

when it should have been

<a class="nav-link active" routerLink="/dashboard" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>

Without having routerLinkActive, you can't have routerLinkActiveOptions.

Bootstrap 3 select input form inline

It requires a minor CSS addition to make it work with Bootstrap 3:

_x000D_
_x000D_
.input-group-btn:last-child > .form-control {_x000D_
  margin-left: -1px;_x000D_
  width: auto;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
  <div class="input-group">_x000D_
    <input class="form-control" name="q" type="text" placeholder="Search">_x000D_
    _x000D_
    <div class="input-group-btn">_x000D_
      <select class="form-control" name="category">_x000D_
        <option>select</option>_x000D_
        <option>1</option>_x000D_
        <option>2</option>_x000D_
        <option>3</option>_x000D_
      </select>_x000D_
    </div>_x000D_
    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sanitizing strings to make them URL and filename safe?

There are already several solutions provided for this question but I have read and tested most of the code here and I ended up with this solution which is a mix of what I learned here:

The function

The function is bundled here in a Symfony2 bundle but it can be extracted to be used as plain PHP, it only has a dependency with the iconv function that must be enabled:

Filesystem.php:

<?php

namespace COil\Bundle\COilCoreBundle\Component\HttpKernel\Util;

use Symfony\Component\HttpKernel\Util\Filesystem as BaseFilesystem;

/**
 * Extends the Symfony filesystem object.
 */
class Filesystem extends BaseFilesystem
{
    /**
     * Make a filename safe to use in any function. (Accents, spaces, special chars...)
     * The iconv function must be activated.
     *
     * @param string  $fileName       The filename to sanitize (with or without extension)
     * @param string  $defaultIfEmpty The default string returned for a non valid filename (only special chars or separators)
     * @param string  $separator      The default separator
     * @param boolean $lowerCase      Tells if the string must converted to lower case
     *
     * @author COil <https://github.com/COil>
     * @see    http://stackoverflow.com/questions/2668854/sanitizing-strings-to-make-them-url-and-filename-safe
     *
     * @return string
     */
    public function sanitizeFilename($fileName, $defaultIfEmpty = 'default', $separator = '_', $lowerCase = true)
    {
    // Gather file informations and store its extension
    $fileInfos = pathinfo($fileName);
    $fileExt   = array_key_exists('extension', $fileInfos) ? '.'. strtolower($fileInfos['extension']) : '';

    // Removes accents
    $fileName = @iconv('UTF-8', 'us-ascii//TRANSLIT', $fileInfos['filename']);

    // Removes all characters that are not separators, letters, numbers, dots or whitespaces
    $fileName = preg_replace("/[^ a-zA-Z". preg_quote($separator). "\d\.\s]/", '', $lowerCase ? strtolower($fileName) : $fileName);

    // Replaces all successive separators into a single one
    $fileName = preg_replace('!['. preg_quote($separator).'\s]+!u', $separator, $fileName);

    // Trim beginning and ending seperators
    $fileName = trim($fileName, $separator);

    // If empty use the default string
    if (empty($fileName)) {
        $fileName = $defaultIfEmpty;
    }

    return $fileName. $fileExt;
    }
}

The unit tests

What is interesting is that I have created PHPUnit tests, first to test edge cases and so you can check if it fits your needs: (If you find a bug, feel free to add a test case)

FilesystemTest.php:

<?php

namespace COil\Bundle\COilCoreBundle\Tests\Unit\Helper;

use COil\Bundle\COilCoreBundle\Component\HttpKernel\Util\Filesystem;

/**
 * Test the Filesystem custom class.
 */
class FilesystemTest extends \PHPUnit_Framework_TestCase
{
    /**
     * test sanitizeFilename()
     */
    public function testFilesystem()
    {
    $fs = new Filesystem();

    $this->assertEquals('logo_orange.gif', $fs->sanitizeFilename('--logö  _  __   ___   ora@@ñ--~gé--.gif'), '::sanitizeFilename() handles complex filename with specials chars');
    $this->assertEquals('coilstack', $fs->sanitizeFilename('cOiLsTaCk'), '::sanitizeFilename() converts all characters to lower case');
    $this->assertEquals('cOiLsTaCk', $fs->sanitizeFilename('cOiLsTaCk', 'default', '_', false), '::sanitizeFilename() lower case can be desactivated, passing false as the 4th argument');
    $this->assertEquals('coil_stack', $fs->sanitizeFilename('coil stack'), '::sanitizeFilename() convert a white space to a separator');
    $this->assertEquals('coil-stack', $fs->sanitizeFilename('coil stack', 'default', '-'), '::sanitizeFilename() can use a different separator as the 3rd argument');
    $this->assertEquals('coil_stack', $fs->sanitizeFilename('coil          stack'), '::sanitizeFilename() removes successive white spaces to a single separator');
    $this->assertEquals('coil_stack', $fs->sanitizeFilename('       coil stack'), '::sanitizeFilename() removes spaces at the beginning of the string');
    $this->assertEquals('coil_stack', $fs->sanitizeFilename('coil   stack         '), '::sanitizeFilename() removes spaces at the end of the string');
    $this->assertEquals('coilstack', $fs->sanitizeFilename('coil,,,,,,stack'), '::sanitizeFilename() removes non-ASCII characters');
    $this->assertEquals('coil_stack', $fs->sanitizeFilename('coil_stack  '), '::sanitizeFilename() keeps separators');
    $this->assertEquals('coil_stack', $fs->sanitizeFilename(' coil________stack'), '::sanitizeFilename() converts successive separators into a single one');
    $this->assertEquals('coil_stack.gif', $fs->sanitizeFilename('cOil Stack.GiF'), '::sanitizeFilename() lower case filename and extension');
    $this->assertEquals('copy_of_coil.stack.exe', $fs->sanitizeFilename('Copy of coil.stack.exe'), '::sanitizeFilename() keeps dots before the extension');
    $this->assertEquals('default.doc', $fs->sanitizeFilename('____________.doc'), '::sanitizeFilename() returns a default file name if filename only contains special chars');
    $this->assertEquals('default.docx', $fs->sanitizeFilename('     ___ -  --_     __%%%%__¨¨¨***____      .docx'), '::sanitizeFilename() returns a default file name if filename only contains special chars');
    $this->assertEquals('logo_edition_1314352521.jpg', $fs->sanitizeFilename('logo_edition_1314352521.jpg'), '::sanitizeFilename() returns the filename untouched if it does not need to be modified');
    $userId = rand(1, 10);
    $this->assertEquals('user_doc_'. $userId. '.doc', $fs->sanitizeFilename('?????.doc', 'user_doc_'. $userId), '::sanitizeFilename() returns the default string (the 2nd argument) if it can\'t be sanitized');
    }
}

The test results: (checked on Ubuntu with PHP 5.3.2 and MacOsX with PHP 5.3.17:

All tests pass:

phpunit -c app/ src/COil/Bundle/COilCoreBundle/Tests/Unit/Helper/FilesystemTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from /var/www/strangebuzz.com/app/phpunit.xml.dist

.

Time: 0 seconds, Memory: 5.75Mb

OK (1 test, 17 assertions)

addEventListener for keydown on Canvas

encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.

New to unit testing, how to write great tests?

My tests just seems so tightly bound to the method (testing all codepath, expecting some inner methods to be called a number of times, with certain arguments), that it seems that if I ever refactor the method, the tests will fail even if the final behavior of the method did not change.

I think you are doing it wrong.

A unit test should:

  • test one method
  • provide some specific arguments to that method
  • test that the result is as expected

It should not look inside the method to see what it is doing, so changing the internals should not cause the test to fail. You should not directly test that private methods are being called. If you are interested in finding out whether your private code is being tested then use a code coverage tool. But don't get obsessed by this: 100% coverage is not a requirement.

If your method calls public methods in other classes, and these calls are guaranteed by your interface, then you can test that these calls are being made by using a mocking framework.

You should not use the method itself (or any of the internal code it uses) to generate the expected result dynamically. The expected result should be hard-coded into your test case so that it does not change when the implementation changes. Here's a simplified example of what a unit test should do:

testAdd()
{
    int x = 5;
    int y = -2;
    int expectedResult = 3;
    Calculator calculator = new Calculator();
    int actualResult = calculator.Add(x, y);
    Assert.AreEqual(expectedResult, actualResult);
}

Note that how the result is calculated is not checked - only that the result is correct. Keep adding more and more simple test cases like the above until you have have covered as many scenarios as possible. Use your code coverage tool to see if you have missed any interesting paths.

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

You are off slightly on a few things here, so hopefully the following helps.

Firstly, you don't need to select ranges to access their properties, you can just specify their address etc. Secondly, unless you are manipulating the values within the range, you don't actually need to set them to a variant. If you do want to manipulate the values, you can leave out the bounds of the array as it will be set when you define the range.

It's also good practice to use Option Explicit at the top of your modules to force variable declaration.

The following will do what you are after:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
    Next
End Sub

If you do want to manipulate the values within the array then do this:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer
    Dim anARRAY as Variant

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       anARRAY= Range("C4:G4").Value

       'You can loop through the array and manipulate it here

       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
    Next
End Sub

bundle install returns "Could not locate Gemfile"

You must be in the same directory of Gemfile

Moment JS - check if a date is today or in the future

if firstDate is same or after(future) secondDate return true else return false. Toda is firstDate = new Date();

  static isFirstDateSameOrAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isSameOrBefore(date2,'day');
    }
    return false;
  }

There is isSame, isBefore and isAfter for day compare moment example;

  static isFirstDateSameSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if (date1 && date2) {
      return date1.isSame(date2,'day');
    }
    return false;
  }

  static isFirstDateAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isAfter(date2,'day');
    }
    return false;
  }

  static isFirstDateBeforeSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isBefore(date2,'day');
    }
    return false;
  }

col align right

For Bootstrap 4 I find the following very handy because:

  • the column on the right takes exactly the space it needs and will pull right
  • while the left col always gets the maximum amount of space!.

It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)

<div class="row">
    <div class="col">Left</div>
    <div class="col-auto">Right</div>
</div>

Ideal for aligning words, icons, buttons,... to the right.

An example to have this responsive on small devices:

<div class="row">
    <div class="col">Left</div>
    <div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>

Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/

Handling ExecuteScalar() when no results are returned

Always have a check before reading row.

if (SqlCommand.ExecuteScalar() == null)
{ 

}

AngularJS - Passing data between pages

What you should do is create a service to share data between controllers.

Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk

window.open(url, '_blank'); not working on iMac/Safari

You can't rely on window.open because browsers may have different policies. I had the same issue and I used the code below instead.

let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = <your_url>;
a.download = <your_fileName>;
a.click();
document.body.removeChild(a);

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

How would I extract a single file (or changes to a file) from a git stash?

You can get the diff for a stash with "git show stash@{0}" (or whatever the number of the stash is; see "git stash list"). It's easy to extract the section of the diff for a single file.

How to loop through file names returned by find?

If you can assume the file names don't contain newlines, you can read the output of find into a Bash array using the following command:

readarray -t x < <(find . -name '*.txt')

Note:

  • -t causes readarray to strip newlines.
  • It won't work if readarray is in a pipe, hence the process substitution.
  • readarray is available since Bash 4.

Bash 4.4 and up also supports the -d parameter for specifying the delimiter. Using the null character, instead of newline, to delimit the file names works also in the rare case that the file names contain newlines:

readarray -d '' x < <(find . -name '*.txt' -print0)

readarray can also be invoked as mapfile with the same options.

Reference: https://mywiki.wooledge.org/BashFAQ/005#Loading_lines_from_a_file_or_stream

How to prevent scrollbar from repositioning web page?

I don't know if this is an old post, but i had the same problem and if you want to scroll vertically only you should try overflow-y:scroll

PowerShell equivalent to grep -f

Maybe?

[regex]$regex = (get-content <regex file> |
foreach {
          '(?:{0})' -f $_
        }) -join '|'

Get-Content <filespec> -ReadCount 10000 |
 foreach {
           if ($_ -match $regex)
             {
              $true
              break
             }
         }

Replace a character at a specific index in a string?

You can overwrite a string, as follows:

String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);  

Note that the string myName occurs on both lines, and on both sides of the second line.

Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.

symfony 2 No route found for "GET /"

Using symfony 2.3 with php 5.5 and using the built in server with

app/console server:run

which should output something like:

Server running on http://127.0.0.1:8000
Quit the server with CONTROL-C.

then go to http://127.0.0.1:8000/app_dev.php/app/example

this should give you the default, which you can also find the default route by viewing src/AppBundle/Controller/DefaultController.php

How can I check for IsPostBack in JavaScript?

Create a global variable in and apply the value

<script>
       var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>

Then you can reference it from elsewhere

How to use onClick with divs in React.js

Whilst this can be done with react, be aware that using onClicks with divs (instead of Buttons or Anchors, and others which already have behaviours for click events) is bad practice and should be avoided whenever it can be.

Image, saved to sdcard, doesn't appear in Android's Gallery app

The system scans the SD card when it is mounted to find any new image (and other) files. If you are programmatically adding a file, then you can use this class:

http://developer.android.com/reference/android/media/MediaScannerConnection.html

Counting the number of True Booleans in a Python List

If you are only concerned with the constant True, a simple sum is fine. However, keep in mind that in Python other values evaluate as True as well. A more robust solution would be to use the bool builtin:

>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3

UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:

>>> sum(1 for x in l if x)
3

P.S. Python trivia: True could be true without being 1. Warning: do not try this at work!

>>> True = 2
>>> if True: print('true')
... 
true
>>> l = [True, True, False, True]
>>> sum(l)
6
>>> sum(bool(x) for x in l)
3
>>> sum(1 for x in l if x)
3

Much more evil:

True = False

How to import a jar in Eclipse

  1. Right Click on the Project.
  2. Click on Build Path.
  3. Click On Configure Build Path.
  4. Under Libraries, Click on Add Jar or Add External Jar.

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

Alter Table Add Column Syntax

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;

Python extract pattern matches

You need to capture from regex. search for the pattern, if found, retrieve the string using group(index). Assuming valid checks are performed:

>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1)     # group(1) will return the 1st capture (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'

Failed to load JavaHL Library

Try this:

  1. Select Window >> Preferences
  2. Expand Team >> SVN
  3. Under SVN interface set Client to SVNKit (Pure Java) SVNKit....

Create Table from View

To create a table on the fly us this syntax:

SELECT *
INTO A
FROM dbo.myView

Disable future dates after today in Jquery Ui Datepicker

Change maxDate to current date

maxDate: new Date()

It will set current date as maximum value.

How can I create database tables from XSD files?

I use XSLT to do that. Write up your XSD then pass your data models through a hand written XSLT that outputs SQL commands. Writing an XSLT is way faster and reusable than a custom program /script you may write.

At least thats how I do it at work, and thanks to that I got time to hang out on SO :)

How to deal with a slow SecureRandom generator?

I had a similar problem with calls to SecureRandom blocking for about 25 seconds at a time on a headless Debian server. I installed the haveged daemon to ensure /dev/random is kept topped up, on headless servers you need something like this to generate the required entropy. My calls to SecureRandom now perhaps take milliseconds.

Extending the User model with custom fields in Django

Currently as of Django 2.2, the recommended way when starting a new project is to create a custom user model that inherits from AbstractUser, then point AUTH_USER_MODEL to the model.

Source: https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

How to get a table cell value using jQuery?

a less-jquerish approach:

$('#mytable tr').each(function() {
    if (!this.rowIndex) return; // skip first row
    var customerId = this.cells[0].innerHTML;
});

this can obviously be changed to work with not-the-first cells.

Why is "using namespace std;" considered bad practice?

If you import the right header files you suddenly have names like hex, left, plus or count in your global scope. This might be surprising if you are not aware that std:: contains these names. If you also try to use these names locally it can lead to quite some confusion.

If all the standard stuff is in its own namespace you don't have to worry about name collisions with your code or other libraries.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

Difference between FetchType LAZY and EAGER in Java Persistence API?

Book.java

        import java.io.Serializable;
        import javax.persistence.Column;
        import javax.persistence.Entity;
        import javax.persistence.GeneratedValue;
        import javax.persistence.GenerationType;
        import javax.persistence.Id;
        import javax.persistence.ManyToOne;
        import javax.persistence.Table;

        @Entity
        @Table(name="Books")
        public class Books implements Serializable{

        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="book_id")
        private int id;
        @Column(name="book_name")
        private String name;

        @Column(name="author_name")
        private String authorName;

        @ManyToOne
        Subject subject;

        public Subject getSubject() {
            return subject;
        }
        public void setSubject(Subject subject) {
            this.subject = subject;
        }

        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAuthorName() {
            return authorName;
        }
        public void setAuthorName(String authorName) {
            this.authorName = authorName;
        }

        }

Subject.java

    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue; 
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;

    @Entity
    @Table(name="Subject")
    public class Subject implements Serializable{

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="subject_id")
    private int id;
    @Column(name="subject_name")
    private String name;
    /**
    Observe carefully i have mentioned fetchType.EAGER. By default its is fetchType.LAZY for @OneToMany i have mentioned it but not required. Check the Output by changing it to fetchType.EAGER
    */

    @OneToMany(mappedBy="subject",cascade=CascadeType.ALL,fetch=FetchType.LAZY,
orphanRemoval=true)
    List<Books> listBooks=new ArrayList<Books>();

    public List<Books> getListBooks() {
        return listBooks;
    }
    public void setListBooks(List<Books> listBooks) {
        this.listBooks = listBooks;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    }

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {

 private static SessionFactory sessionFactory ;
 static {
    Configuration configuration = new Configuration();
    configuration.addAnnotatedClass (Com.OneToMany.Books.class);
    configuration.addAnnotatedClass (Com.OneToMany.Subject.class);
    configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
    configuration.setProperty("hibernate.connection.username", "root");     
    configuration.setProperty("hibernate.connection.password", "root");
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");
    configuration.setProperty(" hibernate.cache.use_second_level_cache", "true");
    configuration.setProperty(" hibernate.cache.use_query_cache", "true");
    configuration.setProperty(" cache.provider_class", "org.hibernate.cache.EhCacheProvider");
    configuration.setProperty("hibernate.cache.region.factory_class" ,"org.hibernate.cache.ehcache.EhCacheRegionFactory");

   // configuration
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
} 

Main.java

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;

    public class Main {

    public static void main(String[] args) {
        SessionFactory factory=HibernateUtil.getSessionFactory();
        save(factory);
        retrieve(factory);

    }

     private static void retrieve(SessionFactory factory) {
        Session session=factory.openSession();
        try{
            session.getTransaction().begin();
            Subject subject=(Subject)session.get(Subject.class, 1);
            System.out.println("subject associated collection is loading lazily as @OneToMany is lazy loaded");

            Books books=(Books)session.get(Books.class, 1);
            System.out.println("books associated collection is loading eagerly as by default @ManyToOne is Eagerly loaded");
            /*Books b1=(Books)session.get(Books.class, new Integer(1));

            Subject sub=session.get(Subject.class, 1);
            sub.getListBooks().remove(b1);
            session.save(sub);
            session.getTransaction().commit();*/
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            session.close();
        }

        }

       private static void save(SessionFactory factory){
        Subject subject=new Subject();
        subject.setName("C++");

        Books books=new Books();
        books.setAuthorName("Bala");
        books.setName("C++ Book");
        books.setSubject(subject);

        subject.getListBooks().add(books);
        Session session=factory.openSession();
        try{
        session.beginTransaction();

        session.save(subject);

        session.getTransaction().commit();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            session.close();
        }
    }

    }

Check the retrieve() method of Main.java. When we get Subject, then its collection listBooks, annotated with @OneToMany, will be loaded lazily. But, on the other hand, Books related association of collection subject, annotated with @ManyToOne, loads eargerly (by [default][1] for @ManyToOne, fetchType=EAGER). We can change the behaviour by placing fetchType.EAGER on @OneToMany Subject.java or fetchType.LAZY on @ManyToOne in Books.java.

How to find index of all occurrences of element in array?

This worked for me:

let array1 = [5, 12, 8, 130, 44, 12, 45, 12, 56];
let numToFind = 12
let indexesOf12 = [] // the number whose occurrence in the array we want to find

array1.forEach(function(elem, index, array) {
    if (elem === numToFind) {indexesOf12.push(index)}
    return indexesOf12
})

console.log(indexesOf12) // outputs [1, 5, 7]

Android: show/hide a view using an animation

Try this.

view.animate()
    .translationY(0)
    .alpha(0.0f)
    .setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            view.setVisibility(View.GONE);
        }
    });

How to match any non white space character except a particular one?

This worked for me using sed [Edit: comment below points out sed doesn't support \s]

[^ ]

while

[^\s] 

didn't

# Delete everything except space and 'g'
echo "ghai ghai" | sed "s/[^\sg]//g"
gg

echo "ghai ghai" | sed "s/[^ g]//g"
g g

HttpContext.Current.Session is null when routing requests

None of these solutions worked for me. I added the following method into global.asax.cs then Session was not null:

protected void Application_PostAuthorizeRequest()
{
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

Given a URL to a text file, what is the simplest way to read the contents of the text file?

Another way in Python 3 is to use the urllib3 package.

import urllib3

http = urllib3.PoolManager()
response = http.request('GET', target_url)
data = response.data.decode('utf-8')

This can be a better option than urllib since urllib3 boasts having

  • Thread safety.
  • Connection pooling.
  • Client-side SSL/TLS verification.
  • File uploads with multipart encoding.
  • Helpers for retrying requests and dealing with HTTP redirects.
  • Support for gzip and deflate encoding.
  • Proxy support for HTTP and SOCKS.
  • 100% test coverage.

DOUBLE vs DECIMAL in MySQL

From your comments,

the tax amount rounded to the 4th decimal and the total price rounded to the 2nd decimal.

Using the example in the comments, I might foresee a case where you have 400 sales of $1.47. Sales-before-tax would be $588.00, and sales-after-tax would sum to $636.51 (accounting for $48.51 in taxes). However, the sales tax of $0.121275 * 400 would be $48.52.

This was one way, albeit contrived, to force a penny's difference.

I would note that there are payroll tax forms from the IRS where they do not care if an error is below a certain amount (if memory serves, $0.50).

Your big question is: does anybody care if certain reports are off by a penny? If the your specs say: yes, be accurate to the penny, then you should go through the effort to convert to DECIMAL.

I have worked at a bank where a one-penny error was reported as a software defect. I tried (in vain) to cite the software specifications, which did not require this degree of precision for this application. (It was performing many chained multiplications.) I also pointed to the user acceptance test. (The software was verified and accepted.)

Alas, sometimes you just have to make the conversion. But I would encourage you to A) make sure that it's important to someone and then B) write tests to show that your reports are accurate to the degree specified.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Personally, to deal with empty responses, I use in my Integration Tests the MockMvcResponse object like this :

MockMvcResponse response = RestAssuredMockMvc.given()
                .webAppContextSetup(webApplicationContext)
                .when()
                .get("/v1/ticket");

    assertThat(response.mockHttpServletResponse().getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value());

and in my controller I return empty response in a specific case like this :

return ResponseEntity.noContent().build();

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

How to check if a stored procedure exists before creating it

Here is the script that I use. With it, I avoid unnecessarily dropping and recreating the stored procs.

IF NOT EXISTS (
    SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'[dbo].[uspMyProcedure]')
    )
BEGIN
  EXEC sp_executesql N'CREATE PROCEDURE [dbo].[uspMyProcedure] AS select 1'
END
GO

ALTER PROCEDURE [dbo].[uspMyProcedure] 
    @variable1 INTEGER  
AS
BEGIN
   -- Stored procedure logic
END

Return outside function error in Python

It basically occours when you return from a loop you can only return from function

How to HTML encode/escape a string? Is there a built-in?

ERB::Util.html_escape can be used anywhere. It is available without using require in Rails.

How can I pass a parameter to a setTimeout() callback?

Note that the reason topicId was "not defined" per the error message is that it existed as a local variable when the setTimeout was executed, but not when the delayed call to postinsql happened. Variable lifetime is especially important to pay attention to, especially when trying something like passing "this" as an object reference.

I heard that you can pass topicId as a third parameter to the setTimeout function. Not much detail is given but I got enough information to get it to work, and it's successful in Safari. I don't know what they mean about the "millisecond error" though. Check it out here:

http://www.howtocreate.co.uk/tutorials/javascript/timers

How can I get the max (or min) value in a vector?

If you want to use an iterator, you can do a placement-new with an array.

std::array<int, 10> icloud = new (cloud) std::array<int,10>;

Note the lack of a () at the end, that is important. This creates an array class that uses that memory as its storage, and has STL features like iterators.

(This is C++ TR1/C++11 by the way)

Can you explain the HttpURLConnection connection process?

Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().

http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection

Can't use System.Windows.Forms

To add the reference to "System.Windows.Forms", it seems to be a little different for Visual Studio Community 2017.

1) Go to solution explorer and select references

enter image description here

2) Right-click and select Add references enter image description here

3) In Assemblies, check System.Windows.Forms and press ok

enter image description here

4) That's it.

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How do I start PowerShell from Windows Explorer?

There's a Windows Explorer extension made by the dude who makes tools for SVN that will at least open a command prompt window.

I haven't tried it yet, so I don't know if it'll do PowerShell, but I wanted to share the love with my Stack Overflow brethren:

http://tools.tortoisesvn.net/StExBar

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • Transpose a range in VBA

    This gets you X and X' as variant arrays you can pass to another function.

    Dim X() As Variant
    Dim XT() As Variant
    X = ActiveSheet.Range("InRng").Value2
    XT = Application.Transpose(X)
    

    To have the transposed values as a range, you have to pass it via a worksheet as in this answer. Without seeing how your covariance function works it's hard to see what you need.

    Make body have 100% of the browser height

    A quick update

    html, body{
        min-height:100%;
        overflow:auto;
    }
    

    A better solution with today's CSS

    html, body{ 
      min-height: 100vh;
      overflow: auto;
    }
    

    Indirectly referenced from required .class file

    This issue happen because of few jars are getting references from other jar and reference jar is missing .

    Example : Spring framework

    Description Resource    Path    Location    Type
    The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project   SpringBatch     Unknown Java Problem
    

    In this case "org.springframework.beans.factory.annotation.Autowire" is missing.

    Spring-bean.jar is missing
    

    Once you add dependency in your class path issue will resolve.

    How do I sort a vector of pairs based on the second element of the pair?

    EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution

    std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
        return left.second < right.second;
    });
    

    Just use a custom comparator (it's an optional 3rd argument to std::sort)

    struct sort_pred {
        bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
            return left.second < right.second;
        }
    };
    
    std::sort(v.begin(), v.end(), sort_pred());
    

    If you're using a C++11 compiler, you can write the same using lambdas:

    std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    });
    

    EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:

    template <class T1, class T2, class Pred = std::less<T2> >
    struct sort_pair_second {
        bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
            Pred p;
            return p(left.second, right.second);
        }
    };
    

    then you can do this too:

    std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
    

    or even

    std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
    

    Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P

    AccessDenied for ListObjects for S3 bucket when permissions are s3:*

    I got the same error when using policy as below, although i have "s3:ListBucket" for s3:ListObjects operation.

    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::<bucketname>/*",
                "arn:aws:s3:::*-bucket/*"
            ],
            "Effect": "Allow"
        }
      ]
     }
    

    Then i fixed it by adding one line "arn:aws:s3:::bucketname"

    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectAcl"
            ],
            "Resource": [
                 "arn:aws:s3:::<bucketname>",
                "arn:aws:s3:::<bucketname>/*",
                "arn:aws:s3:::*-bucket/*"
            ],
            "Effect": "Allow"
        }
     ]
    }
    

    Which sort algorithm works best on mostly sorted data?

    As everyone else said, be careful of naive Quicksort - that can have O(N^2) performance on sorted or nearly sorted data. Nevertheless, with an appropriate algorithm for choice of pivot (either random or median-of-three - see Choosing a Pivot for Quicksort), Quicksort will still work sanely.

    In general, the difficulty with choosing algorithms such as insert sort is in deciding when the data is sufficiently out of order that Quicksort really would be quicker.

    Python - How to cut a string in Python?

    You need to split the string:

    >>> s = 'http://www.domain.com/?s=some&two=20'
    >>> s.split('&')
    ['http://www.domain.com/?s=some', 'two=20']
    

    That will return a list as you can see so you can do:

    >>> s2 = s.split('&')[0]
    >>> print s2
    http://www.domain.com/?s=some
    

    When are you supposed to use escape instead of encodeURI / encodeURIComponent?

    I've found that experimenting with the various methods is a good sanity check even after having a good handle of what their various uses and capabilities are.

    Towards that end I have found this website extremely useful to confirm my suspicions that I am doing something appropriately. It has also proven useful for decoding an encodeURIComponent'ed string which can be rather challenging to interpret. A great bookmark to have:

    http://www.the-art-of-web.com/javascript/escape/

    How to execute 16-bit installer on 64-bit Win7?

    Bottom line at the top: Get newer programs or get an older computer.

    The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

    Bootstrap 3 Flush footer to bottom. not fixed

    Use any class and make it's height fixed. It solved my issue.

    <div class="container"></div>
    <footer></footer>
    

    CSS:

    .container{
        min-height: 60vh;
    }
    

    Number of days between two dates in Joda-Time

    tl;dr

    java.time.temporal.ChronoUnit.DAYS.between( 
        earlier.toLocalDate(), 
        later.toLocalDate() 
    )
    

    …or…

    java.time.temporal.ChronoUnit.HOURS.between( 
        earlier.truncatedTo( ChronoUnit.HOURS )  , 
        later.truncatedTo( ChronoUnit.HOURS ) 
    )
    

    java.time

    FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

    The equivalent of Joda-Time DateTime is ZonedDateTime.

    ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
    ZonedDateTime now = ZonedDateTime.now( z ) ;
    

    Apparently you want to count the days by dates, meaning you want to ignore the time of day. For example, starting a minute before midnight and ending a minute after midnight should result in a single day. For this behavior, extract a LocalDate from your ZonedDateTime. The LocalDate class represents a date-only value without time-of-day and without time zone.

    LocalDate localDateStart = zdtStart.toLocalDate() ;
    LocalDate localDateStop = zdtStop.toLocalDate() ;
    

    Use the ChronoUnit enum to calculate elapsed days or other units.

    long days = ChronoUnit.DAYS.between( localDateStart , localDateStop ) ;
    

    Truncate

    As for you asking about a more general way to do this counting where you are interested the delta of hours as hour-of-the-clock rather than complete hours as spans-of-time of sixty minutes, use the truncatedTo method.

    Here is your example of 14:45 to 15:12 on same day.

    ZoneId z = ZoneId.of( "America/Montreal" ); 
    ZonedDateTime start = ZonedDateTime.of( 2017 , 1 , 17 , 14 , 45 , 0 , 0 , z );
    ZonedDateTime stop = ZonedDateTime.of( 2017 , 1 , 17 , 15 , 12 , 0 , 0 , z );
    
    long hours = ChronoUnit.HOURS.between( start.truncatedTo( ChronoUnit.HOURS ) , stop.truncatedTo( ChronoUnit.HOURS ) );
    

    1

    This does not work for days. Use toLocalDate() in this case.


    About java.time

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

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

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

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

    Where to obtain the java.time classes?

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

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

    What's the simplest way to list conflicted files in Git?

    you may hit git ls-files -u on your command line it lists down files with conflicts

    How do I delete multiple rows with different IDs?

    Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions

    if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection

    how the query could look like:

    -- not tested
    -- @ids will contain a varchar with your ids e.g.'9 12 27 37'
    DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))
    

    here is the function:

    ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
       RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
                           number  int NOT NULL) AS
    
       -- funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
       -- dient zum übergeben einer liste von elementen
    
    BEGIN
        -- Deklaration der Variablen
        DECLARE @startpos int,
                @endpos   int,
                @textpos  int,
                @chunklen smallint,
                @str      nvarchar(4000),
                @tmpstr   nvarchar(4000),
                @leftover nvarchar(4000)
    
        -- Startwerte festlegen
       SET @textpos = 1
       SET @leftover = ''
    
       -- Loop 1
        WHILE @textpos <= datalength(@list) / 2
        BEGIN
    
            --
            SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)
    
            --
            SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings
    
            --hochzählen der TestPosition
            SET @textpos = @textpos + @chunklen
    
            --start position 0 setzen
            SET @startpos = 0
    
            -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
            SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)
    
            -- Loop 2
            WHILE @endpos > 0
            BEGIN
                --str ist der string welcher zwischen den [LEERZEICHEN] steht
                SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1) 
    
                --wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
                IF @str <> ''
                    INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)
    
                -- start wird auf das letzte bekannte end gesetzt
                SET @startpos = @endpos
    
                -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
                SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
            END
            -- Loop 2
    
            -- dient dafür den letzten teil des strings zu selektieren
            SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
        END
        -- Loop 1
    
        --wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
        IF ltrim(rtrim(@leftover)) <> ''
            INSERT @tbl (number) VALUES(convert(int, @leftover))
    
        RETURN
    END
    
    
        -- ############################ WICHTIG ############################
        -- das is ein Beispiel wie man die Funktion benutzt
        --
        --CREATE    PROCEDURE get_product_names_iter 
        --      @ids varchar(50) AS
        --SELECT    P.ProductName, P.ProductID
        --FROM      Northwind.Products P
        --JOIN      iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
        --go
        --EXEC get_product_names_iter '9 12 27 37'
        --
        -- Funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
        -- dient zum übergeben einer Liste von Id's
        -- ############################ WICHTIG ############################
    

    Remove lines that contain certain string

    The else is only connected to the last if. You want elif:

    if 'bad' in line:
        pass
    elif 'naughty' in line:
        pass
    else:
        newopen.write(line)
    

    Also note that I removed the line substitution, as you don't write those lines anyway.

    Single huge .css file vs. multiple smaller specific .css files?

    You want both worlds.

    You want multiple CSS files because your sanity is a terrible thing to waste.

    At the same time, it's better to have a single, large file.

    The solution is to have some mechanism that combines the multiple files in to a single file.

    One example is something like

    <link rel="stylesheet" type="text/css" href="allcss.php?files=positions.css,buttons.css,copy.css" />
    

    Then, the allcss.php script handles concatenating the files and delivering them.

    Ideally, the script would check the mod dates on all the files, creates a new composite if any of them changes, then returns that composite, and then checks against the If-Modified HTTP headers so as to not send redundant CSS.

    This gives you the best of both worlds. Works great for JS as well.

    How to find the last field using 'cut'

    This is the only solution possible for using nothing but cut:

    echo "s.t.r.i.n.g." | cut -d'.' -f2- [repeat_following_part_forever_or_until_out_of_memory:] | cut -d'.' -f2-

    Using this solution, the number of fields can indeed be unknown and vary from time to time. However as line length must not exceed LINE_MAX characters or fields, including the new-line character, then an arbitrary number of fields can never be part as a real condition of this solution.

    Yes, a very silly solution but the only one that meets the criterias I think.

    libpng warning: iCCP: known incorrect sRGB profile

    Extending the friederbluemle solution, download the pngcrush and then use the code like this if you are running it on multiple png files

    path =r"C:\\project\\project\\images" # path to all .png images
    import os
    
    png_files =[]
    
    for dirpath, subdirs, files in os.walk(path):
        for x in files:
            if x.endswith(".png"):
                png_files.append(os.path.join(dirpath, x))
    
    file =r'C:\\Users\\user\\Downloads\\pngcrush_1_8_9_w64.exe' #pngcrush file 
    
    
    for name in png_files:
        cmd = r'{} -ow -rem allb -reduce {}'.format(file,name)
        os.system(cmd)
    

    here all the png file related to projects are in 1 folder.

    How do I convert an object to an array?

    //My Function is worked. Hope help full for you :)
          $input = [
                '1' => (object) [1,2,3],
                '2' => (object) [4,5,6,
                    (object) [6,7,8,
                    [9, 10, 11,
                        (object) [12, 13, 14]]]
                ],
                '3' =>[15, 16, (object)[17, 18]]
            ];
    
            echo "<pre>";
            var_dump($input);
            var_dump(toAnArray($input));
    
          public function toAnArray(&$input) {
    
            if (is_object($input)) {
                $input = get_object_vars($input);
            }
            foreach ($input as &$item) {
                if (is_object($item) || is_array($item)) {
                    if (is_object($item)) {
                        $item = get_object_vars($item);
                    }
                    self::toAnArray($item);
                }
            }
        }
    

    Adding up BigDecimals using Streams

    You can sum up the values of a BigDecimal stream using a reusable Collector named summingUp:

    BigDecimal sum = bigDecimalStream.collect(summingUp());
    

    The Collector can be implemented like this:

    public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
        return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
    }
    

    Optional args in MATLAB functions

    A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

    It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

    function [ output_args ] = input_example( a, b, c )
    if nargin < 1
      error('input_example :  a is a required input')
    end
    
    if nargin < 2
      b = 20
    end
    
    if nargin < 3
      c = 30
    end
    end
    

    How to add reference to a method parameter in javadoc?

    The correct way of referring to a method parameter is like this:

    enter image description here

    How do I create an empty array/matrix in NumPy?

    To create an empty multidimensional array in NumPy (e.g. a 2D array m*n to store your matrix), in case you don't know m how many rows you will append and don't care about the computational cost Stephen Simmons mentioned (namely re-buildinging the array at each append), you can squeeze to 0 the dimension to which you want to append to: X = np.empty(shape=[0, n]).

    This way you can use for example (here m = 5 which we assume we didn't know when creating the empty matrix, and n = 2):

    import numpy as np
    
    n = 2
    X = np.empty(shape=[0, n])
    
    for i in range(5):
        for j  in range(2):
            X = np.append(X, [[i, j]], axis=0)
    
    print X
    

    which will give you:

    [[ 0.  0.]
     [ 0.  1.]
     [ 1.  0.]
     [ 1.  1.]
     [ 2.  0.]
     [ 2.  1.]
     [ 3.  0.]
     [ 3.  1.]
     [ 4.  0.]
     [ 4.  1.]]
    

    Convert YYYYMMDD string date to a datetime value

    You should have to use DateTime.TryParseExact.

    var newDate = DateTime.ParseExact("20111120", 
                                      "yyyyMMdd", 
                                       CultureInfo.InvariantCulture);
    

    OR

    string str = "20111021";
    string[] format = {"yyyyMMdd"};
    DateTime date;
    
    if (DateTime.TryParseExact(str, 
                               format, 
                               System.Globalization.CultureInfo.InvariantCulture,
                               System.Globalization.DateTimeStyles.None, 
                               out date))
    {
         //valid
    }
    

    Why can't non-default arguments follow default arguments?

    SyntaxError: non-default argument follows default argument
    

    If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.

    In Python 3 however, you may do the following:

    def fun1(a="who is you", b="True", *, x, y):
        pass
    

    which makes x and y keyword only so you can do this:

    fun1(x=2, y=2)
    

    This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2) (that would set the default arguments).

    Scrolling a flexbox with overflowing content

    I've spoken to Tab Atkins (author of the flexbox spec) about this, and this is what we came up with:

    HTML:

    <div class="content">
        <div class="box">
            <div class="column">Column 1</div>
            <div class="column">Column 2</div>
            <div class="column">Column 3</div>
        </div>
    </div>
    

    CSS:

    .content {
        flex: 1;
        display: flex;
        overflow: auto;
    }
    
    .box {
        display: flex;
        min-height: min-content; /* needs vendor prefixes */
    }
    

    Here are the pens:

    1. Short columns being stretched.
    2. Longer columns overflowing and scrolling.

    The reason this works is because align-items: stretch doesn't shrink its items if they have an intrinsic height, which is accomplished here by min-content.

    Sql script to find invalid email addresses

    Here is a quick and easy solution:

    CREATE FUNCTION dbo.vaValidEmail(@EMAIL varchar(100))
    
    RETURNS bit as
    BEGIN     
      DECLARE @bitRetVal as Bit
      IF (@EMAIL <> '' AND @EMAIL NOT LIKE '_%@__%.__%')
         SET @bitRetVal = 0  -- Invalid
      ELSE 
        SET @bitRetVal = 1   -- Valid
      RETURN @bitRetVal
    END 
    

    Then you can find all rows by using the function:

    SELECT * FROM users WHERE dbo.vaValidEmail(email) = 0
    

    If you are not happy with creating a function in your database, you can use the LIKE-clause directly in your query:

    SELECT * FROM users WHERE email NOT LIKE '_%@__%.__%'
    

    Source

    to_string is not a member of std, says g++ (mingw)

    #include <string>
    #include <sstream>
    
    namespace patch
    {
        template < typename T > std::string to_string( const T& n )
        {
            std::ostringstream stm ;
            stm << n ;
            return stm.str() ;
        }
    }
    
    #include <iostream>
    
    int main()
    {
        std::cout << patch::to_string(1234) << '\n' << patch::to_string(1234.56) << '\n' ;
    }
    

    do not forget to include #include <sstream>

    How can I check the current status of the GPS receiver?

    With LocationManager you can getLastKnownLocation() after you getBestProvider(). This gives you a Location object, which has the methods getAccuracy() in meters and getTime() in UTC milliseconds

    Does this give you enough info?

    Or perhaps you could iterate over the LocationProviders and find out if each one meetsCriteria( ACCURACY_COARSE )

    C++ - struct vs. class

    The other difference is that

    template<class T> ...
    

    is allowed, but

    template<struct T> ...
    

    is not.

    What's the source of Error: getaddrinfo EAI_AGAIN?

    I had a same problem with AWS and Serverless. I tried with eu-central-1 region and it didn't work so I had to change it to us-east-2 for the example.

    How to get the squared symbol (²) to display in a string

    No need to get too complicated. If all you need is ² then use the unicode representation.

    http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts

    (which is how I assume you got the ² to appear in your question. )

    PostgreSQL - max number of parameters in "IN" clause?

    If you have query like:

    SELECT * FROM user WHERE id IN (1, 2, 3, 4 -- and thousands of another keys)
    

    you may increase performace if rewrite your query like:

    SELECT * FROM user WHERE id = ANY(VALUES (1), (2), (3), (4) -- and thousands of another keys)
    

    comma separated string of selected values in mysql

    Use group_concat() function of mysql.

    SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;
    

    It'll give you concatenated string like :

    5,6,9,10,12,14,15,17,18,779 
    

    Generating an MD5 checksum of a file

    There is a way that's pretty memory inefficient.

    single file:

    import hashlib
    def file_as_bytes(file):
        with file:
            return file.read()
    
    print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()
    

    list of files:

    [(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
    

    Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:

    [(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
    

    If you only want 128 bits worth of digest you can do .digest()[:16].

    This will give you a list of tuples, each tuple containing the name of its file and its hash.

    Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.

    Here is a way that is more complex, but memory efficient:

    import hashlib
    
    def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
        for block in bytesiter:
            hasher.update(block)
        return hasher.hexdigest() if ashexstr else hasher.digest()
    
    def file_as_blockiter(afile, blocksize=65536):
        with afile:
            block = afile.read(blocksize)
            while len(block) > 0:
                yield block
                block = afile.read(blocksize)
    
    
    [(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
        for fname in fnamelst]
    

    And, again, since MD5 is broken and should not really ever be used anymore:

    [(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
        for fname in fnamelst]
    

    Again, you can put [:16] after the call to hash_bytestr_iter(...) if you only want 128 bits worth of digest.

    "make clean" results in "No rule to make target `clean'"

    It seems your makefile's name is not 'Makefile' or 'makefile'. In case it is different say 'abc' try running 'make -f abc clean'

    Javascript: set label text

    you are doing several things wrong. The explanation follows the corrected code:

    <label id="LblTextCount"></label>
    <textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
    </textarea>
    

    Note the quotes around the id.

    function checkLength(object, maxlength, label) {
        charsleft = (maxlength - object.value.length);
    
        // never allow to exceed the specified limit
        if( charsleft < 0 ) {
            object.value = object.value.substring(0, maxlength-1);
        }
    
        // set the value of charsleft into the label
        document.getElementById(label).innerHTML = charsleft;
    }
    

    First, on your key press event you need to send the label id as a string for it to read correctly. Second, InnerHTML has a lowercase i. Lastly, because you sent the function the string id you can get the element by that id.

    Let me know how that works out for you

    EDIT Not that by not declaring charsleft as a var, you are implicitly creating a global variable. a better way would be to do the following when declaring it in the function:

    var charsleft = ....
    

    How to get the path of a running JAR file?

    To obtain the File for a given Class, there are two steps:

    1. Convert the Class to a URL
    2. Convert the URL to a File

    It is important to understand both steps, and not conflate them.

    Once you have the File, you can call getParentFile to get the containing folder, if that is what you need.

    Step 1: Class to URL

    As discussed in other answers, there are two major ways to find a URL relevant to a Class.

    1. URL url = Bar.class.getProtectionDomain().getCodeSource().getLocation();

    2. URL url = Bar.class.getResource(Bar.class.getSimpleName() + ".class");

    Both have pros and cons.

    The getProtectionDomain approach yields the base location of the class (e.g., the containing JAR file). However, it is possible that the Java runtime's security policy will throw SecurityException when calling getProtectionDomain(), so if your application needs to run in a variety of environments, it is best to test in all of them.

    The getResource approach yields the full URL resource path of the class, from which you will need to perform additional string manipulation. It may be a file: path, but it could also be jar:file: or even something nastier like bundleresource://346.fwk2106232034:4/foo/Bar.class when executing within an OSGi framework. Conversely, the getProtectionDomain approach correctly yields a file: URL even from within OSGi.

    Note that both getResource("") and getResource(".") failed in my tests, when the class resided within a JAR file; both invocations returned null. So I recommend the #2 invocation shown above instead, as it seems safer.

    Step 2: URL to File

    Either way, once you have a URL, the next step is convert to a File. This is its own challenge; see Kohsuke Kawaguchi's blog post about it for full details, but in short, you can use new File(url.toURI()) as long as the URL is completely well-formed.

    Lastly, I would highly discourage using URLDecoder. Some characters of the URL, : and / in particular, are not valid URL-encoded characters. From the URLDecoder Javadoc:

    It is assumed that all characters in the encoded string are one of the following: "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "*". The character "%" is allowed but is interpreted as the start of a special escaped sequence.

    ...

    There are two possible ways in which this decoder could deal with illegal strings. It could either leave illegal characters alone or it could throw an IllegalArgumentException. Which approach the decoder takes is left to the implementation.

    In practice, URLDecoder generally does not throw IllegalArgumentException as threatened above. And if your file path has spaces encoded as %20, this approach may appear to work. However, if your file path has other non-alphameric characters such as + you will have problems with URLDecoder mangling your file path.

    Working code

    To achieve these steps, you might have methods like the following:

    /**
     * Gets the base location of the given class.
     * <p>
     * If the class is directly on the file system (e.g.,
     * "/path/to/my/package/MyClass.class") then it will return the base directory
     * (e.g., "file:/path/to").
     * </p>
     * <p>
     * If the class is within a JAR file (e.g.,
     * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
     * path to the JAR (e.g., "file:/path/to/my-jar.jar").
     * </p>
     *
     * @param c The class whose location is desired.
     * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}.
     */
    public static URL getLocation(final Class<?> c) {
        if (c == null) return null; // could not load the class
    
        // try the easy way first
        try {
            final URL codeSourceLocation =
                c.getProtectionDomain().getCodeSource().getLocation();
            if (codeSourceLocation != null) return codeSourceLocation;
        }
        catch (final SecurityException e) {
            // NB: Cannot access protection domain.
        }
        catch (final NullPointerException e) {
            // NB: Protection domain or code source is null.
        }
    
        // NB: The easy way failed, so we try the hard way. We ask for the class
        // itself as a resource, then strip the class's path from the URL string,
        // leaving the base path.
    
        // get the class's raw resource path
        final URL classResource = c.getResource(c.getSimpleName() + ".class");
        if (classResource == null) return null; // cannot find class resource
    
        final String url = classResource.toString();
        final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
        if (!url.endsWith(suffix)) return null; // weird URL
    
        // strip the class's path from the URL string
        final String base = url.substring(0, url.length() - suffix.length());
    
        String path = base;
    
        // remove the "jar:" prefix and "!/" suffix, if present
        if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2);
    
        try {
            return new URL(path);
        }
        catch (final MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    } 
    
    /**
     * Converts the given {@link URL} to its corresponding {@link File}.
     * <p>
     * This method is similar to calling {@code new File(url.toURI())} except that
     * it also handles "jar:file:" URLs, returning the path to the JAR file.
     * </p>
     * 
     * @param url The URL to convert.
     * @return A file path suitable for use with e.g. {@link FileInputStream}
     * @throws IllegalArgumentException if the URL does not correspond to a file.
     */
    public static File urlToFile(final URL url) {
        return url == null ? null : urlToFile(url.toString());
    }
    
    /**
     * Converts the given URL string to its corresponding {@link File}.
     * 
     * @param url The URL to convert.
     * @return A file path suitable for use with e.g. {@link FileInputStream}
     * @throws IllegalArgumentException if the URL does not correspond to a file.
     */
    public static File urlToFile(final String url) {
        String path = url;
        if (path.startsWith("jar:")) {
            // remove "jar:" prefix and "!/" suffix
            final int index = path.indexOf("!/");
            path = path.substring(4, index);
        }
        try {
            if (PlatformUtils.isWindows() && path.matches("file:[A-Za-z]:.*")) {
                path = "file:/" + path.substring(5);
            }
            return new File(new URL(path).toURI());
        }
        catch (final MalformedURLException e) {
            // NB: URL is not completely well-formed.
        }
        catch (final URISyntaxException e) {
            // NB: URL is not completely well-formed.
        }
        if (path.startsWith("file:")) {
            // pass through the URL as-is, minus "file:" prefix
            path = path.substring(5);
            return new File(path);
        }
        throw new IllegalArgumentException("Invalid URL: " + url);
    }
    

    You can find these methods in the SciJava Common library:

    .NET console application as Windows service

    Firstly I embed the console application solution into the windows service solution and reference it.

    Then I make the console application Program class public

    /// <summary>
    /// Hybrid service/console application
    /// </summary>
    public class Program
    {
    }
    

    I then create two functions within the console application

        /// <summary>
        /// Used to start as a service
        /// </summary>
        public void Start()
        {
            Main();
        }
    
        /// <summary>
        /// Used to stop the service
        /// </summary>
        public void Stop()
        {
           if (Application.MessageLoop)
                Application.Exit();   //windows app
            else
                Environment.Exit(1);  //console app
        }
    

    Then within the windows service itself I instantiate the Program and call the Start and Stop functions added within the OnStart and OnStop. See below

    class WinService : ServiceBase
    {
        readonly Program _application = new Program();
    
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] servicesToRun = { new WinService() };
            Run(servicesToRun);
        }
    
        /// <summary>
        /// Set things in motion so your service can do its work.
        /// </summary>
        protected override void OnStart(string[] args)
        {
            Thread thread = new Thread(() => _application.Start());
            thread.Start();
        }
    
        /// <summary>
        /// Stop this service.
        /// </summary>
        protected override void OnStop()
        {
            Thread thread = new Thread(() => _application.Stop());
            thread.Start();
        }
    }
    

    This approach can also be used for a windows application / windows service hybrid

    Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

    The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.

    If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.

    You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.

    See Unable to send emails to external domain using SMTP for an example of how to send the credentials.

    In java how to get substring from a string till a character c?

    You can just split the string..

    public String[] split(String regex)
    

    Note that java.lang.String.split uses delimiter's regular expression value. Basically like this...

    String filename = "abc.def.ghi";     // full file name
    String[] parts = filename.split("\\."); // String array, each element is text between dots
    
    String beforeFirstDot = parts[0];    // Text before the first dot
    

    Of course, this is split into multiple lines for clairity. It could be written as

    String beforeFirstDot = filename.split("\\.")[0];
    

    What is the difference between C++ and Visual C++?

    VC++ is not actually a language but is commonly referred to like one. When VC++ is referred to as a language, it usually means Microsoft's implementation of C++, which contains various knacks that do not exist in regular C++, such as the __super keyword. It is similar to the various GNU extensions to the C language that are implemented in GCC.

    Table is marked as crashed and should be repaired

    Here is where the repair button is:

    alt text

    SQL Server command line backup statement

    if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...

    Locating child nodes of WebElements in selenium

    I also found myself in a similar position a couple of weeks ago. You can also do this by creating a custom ElementLocatorFactory (or simply passing in divA into the DefaultElementLocatorFactory) to see if it's a child of the first div - you would then call the appropriate PageFactory initElements method.

    In this case if you did the following:

    PageFactory.initElements(new DefaultElementLocatorFactory(divA), pageObjectInstance));
    // The Page Object instance would then need a WebElement 
    // annotated with something like the xpath above or @FindBy(tagName = "input")
    

    How to process POST data in Node.js?

    For anyone wondering how to do this trivial task without installing a web framework I managed to plop this together. Hardly production ready but it seems to work.

    function handler(req, res) {
        var POST = {};
        if (req.method == 'POST') {
            req.on('data', function(data) {
                data = data.toString();
                data = data.split('&');
                for (var i = 0; i < data.length; i++) {
                    var _data = data[i].split("=");
                    POST[_data[0]] = _data[1];
                }
                console.log(POST);
            })
        }
    }
    

    How to pass a vector to a function?

    Anytime you're tempted to pass a collection (or pointer or reference to one) to a function, ask yourself whether you couldn't pass a couple of iterators instead. Chances are that by doing so, you'll make your function more versatile (e.g., make it trivial to work with data in another type of container when/if needed).

    In this case, of course, there's not much point since the standard library already has perfectly good binary searching, but when/if you write something that's not already there, being able to use it on different types of containers is often quite handy.

    Running Bash commands in Python

    Also you can use 'os.popen'. Example:

    import os
    
    command = os.popen('ls -al')
    print(command.read())
    print(command.close())
    

    Output:

    total 16
    drwxr-xr-x 2 root root 4096 ago 13 21:53 .
    drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
    -rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
    -rw-r--r-- 1 root root   77 ago 13 21:53 test.py
    
    None
    

    Can't Find Theme.AppCompat.Light for New Android ActionBar Support

    I did the following in Eclipse with the Android Support Library (APL) project and the Main Project (MP):

    1. Ensured both APL and MP had the same minSdkVersion and targetSdkVersion.

    2. Added APL as a build dependency for MP:

      1. Going into "Properties > Java Build Path" of MP, and then

      2. Selecting the "Projects" tab and adding APL.

    3. In the properties of MP, under "Android", added a reference to APL under library.

    1 and 2 got the references to Java classes working fine...however I still saw the error in the manifest.xml for MP when trying to reference @style/Theme.AppCompat.Light from APL. This only went away when I performed step 3.

    Strings and character with printf

    If you want to display a single character then you can also use name[0] instead of using pointer.

    It will serve your purpose but if you want to display full string using %c, you can try this:

    #include<stdio.h>
    void main()
    { 
        char name[]="siva";
        int i;
        for(i=0;i<4;i++)
        {
            printf("%c",*(name+i));
        }
    } 
    

    Inherit CSS class

    As said in previous responses, their is no OOP-like inheritance in CSS. But if you want to reuse a rule-set to apply it to descentants of something, changing properties, and if you can use LESS, try Mixins. To resume on OOP features, it looks like composition.

    For instance, you want to apply the .paragraph class which is in a file "text.less" to all p children of paragraphsContainer, and redefine the color property from red to black

    text.less file

    .paragraph {
        font: arial;
        color: red
    }
    

    Do this in an alternativeText.less file

    @import (reference) 'text.less';    
    div#paragraphsContainer > p {
        .paragraph;
        color: black
    }
    

    your.html file

    <div id='paragraphsContainer'>
       <p>paragraph 1</p>
       <p>paragraph 2</p>
       <p>paragraph 3</p>
    </div>
    

    Please read this answer about defining same css property multiple times

    Override hosts variable of Ansible playbook from the command line

    An other solution is to use the special variable ansible_limit which is the contents of the --limit CLI option for the current execution of Ansible.

    - hosts: "{{ ansible_limit | default(omit) }}"
    

    If the --limit option is omitted, then Ansible issues a warning, but does nothing since no host matched.

    [WARNING]: Could not match supplied host pattern, ignoring: None
    
    PLAY ****************************************************************
    skipping: no hosts matched
    

    When to use If-else if-else over switch statements and vice versa

    Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.

    Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.

    PHP Sort a multidimensional array by element containing date

    I came across to this post but I wanted to sort by time when returning the items inside my class and I got an error.

    So I research the php.net website and end up doing this:

    class MyClass {
       public function getItems(){
          usort( $this->items, array("MyClass", "sortByTime") );
          return $this->items;
       }
       public function sortByTime($a, $b){
          return $b["time"] - $a["time"];
       }
    }
    

    You can find very useful examples in the PHP.net website

    My array looked like this:

      'recent' => 
        array
          92 => 
            array
              'id' => string '92' (length=2)
              'quantity' => string '1' (length=1)
              'time' => string '1396514041' (length=10)
          52 => 
            array
              'id' => string '52' (length=2)
              'quantity' => string '8' (length=1)
              'time' => string '1396514838' (length=10)
          22 => 
            array
              'id' => string '22' (length=2)
              'quantity' => string '1' (length=1)
              'time' => string '1396514871' (length=10)
          81 => 
            array
              'id' => string '81' (length=2)
              'quantity' => string '2' (length=1)
              'time' => string '1396514988' (length=10)
    

    Error with multiple definitions of function

    You have #include "fun.cpp" in mainfile.cpp so compiling with:

    g++ -o hw1 mainfile.cpp
    

    will work, however if you compile by linking these together like

    g++ -g -std=c++11 -Wall -pedantic   -c -o fun.o fun.cpp
    g++ -g -std=c++11 -Wall -pedantic   -c -o mainfile.o mainfile.cpp
    

    As they mention above, adding #include "fun.hpp" will need to be done or it won't work. However, your case with the funct() function is slightly different than my problem.

    I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.

    How to return a custom object from a Spring Data JPA GROUP BY query

    I know this is an old question and it has already been answered, but here's another approach:

    @Query("select new map(count(v) as cnt, v.answer) from Survey v group by v.answer")
    public List<?> findSurveyCount();
    

    Why are unnamed namespaces used and what are their benefits?

    Having something in an anonymous namespace means it's local to this translation unit (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the One Definition Rule (ODR).

    This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than static in C++).

    All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:

    namespace __unique_compiler_generated_identifer0x42 {
        ...
    }
    using namespace __unique_compiler_generated_identifer0x42;
    

    Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

    I have the same question.

    You should add some dependencies in build.gradle, just looks like this

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile project(':libcocos2dx')
        compile 'com.google.firebase:firebase-ads:11.6.0'
    // the key point line
        compile 'com.google.android.gms:play-services-auth:11.6.0'
    }
    

    Reflection: How to Invoke Method with parameters

    You have a bug right there

    result = methodInfo.Invoke(methodInfo, parametersArray);
    

    it should be

    result = methodInfo.Invoke(classInstance, parametersArray);
    

    Call to undefined function oci_connect()

    • Download xampp and uncomment oracle 12c extension or 11c 'extension=oci8_11g' for xampp 7.2.9
    • Download instant client 32 bit and set its path
    • Download instant client 32 bit SDK package and set its path
    • Copy instant clients and SDK dll files to xamp\php\ext, xampp\php\ and xampp\appache\bin\
    • Download php-oci of same php version of tread safe x86 then copy its files to php\ext*.dll, php version is written on top of phpinfo tab of xampp admin.
    • OCI8 will appear on phpadmin page or apache admin then phpadmin tab. It means phpOCI has been installed.

    SaveFileDialog setting default path and file type?

    The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

    1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

    2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

    Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

    SaveFileDialog savefile = new SaveFileDialog(); 
    // set a default file name
    savefile.FileName = "unknown.txt";
    // set filters - this can be done in properties as well
    savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
    
    if (savefile.ShowDialog() == DialogResult.OK)
    {
        using (StreamWriter sw = new StreamWriter(savefile.FileName))
            sw.WriteLine ("Hello World!");
    }
    

    Java code for getting current time

    System.currentTimeMillis()

    everything else works off that.. eg new Date() calls System.currentTimeMillis().

    How to set column widths to a jQuery datatable?

    In java script calculate width using following code

    var scrollX = $(window).width()*58/100;
    var oTable = $('#reqAllRequestsTable').dataTable({
        "sScrollX": scrollX
        } );
    

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

    Very old question, but in case someone else stumbles across it, I would recommend trying:

    $j("html, body").stop(true, true).animate({
            scrollTop: $j('#main').offset().top 
    }, 300);
    

    iOS9 Untrusted Enterprise Developer with no option to trust

    Device: iPad Mini

    OS: iOS 9 Beta 3

    App downloaded from: Hockey App

    Provisioning profile with Trust issues: Enterprise

    In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.

    Settings>General>Profile

    Here are the steps that I followed:

    1. Connect the Device
    2. Open Xcode
    3. Navigate to Window > Devices
    4. Right click on the Device and select Show Provisioning Profiles...
    5. Delete your Enterprise provisioning profile. Hit Done. Window>Device>Provisioning Profile
    6. Open HockeyApp. Install your app.
    7. Once the app finished installing, go back to Settings>General>Profiles. You should now be able to see your Enterprise provisioning profile. enter image description here
    8. Click Trust enter image description here

    That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)

    How to solve java.lang.NullPointerException error?

    Just a shot in the dark(since you did not share the compiler initialization code with us): the way you retrieve the compiler causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE.

    Adding a regression line on a ggplot

    As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.

    You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data).

    It would look like this:

    # read dataset
    df = mtcars
    
    # create multiple linear model
    lm_fit <- lm(mpg ~ cyl + hp, data=df)
    summary(lm_fit)
    
    # save predictions of the model in the new data frame 
    # together with variable you want to plot against
    predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)
    
    # this is the predicted line of multiple linear regression
    ggplot(data = df, aes(x = mpg, y = hp)) + 
      geom_point(color='blue') +
      geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))
    

    Multiple LR

    # this is predicted line comparing only chosen variables
    ggplot(data = df, aes(x = mpg, y = hp)) + 
      geom_point(color='blue') +
      geom_smooth(method = "lm", se = FALSE)
    

    Single LR

    How to pick element inside iframe using document.getElementById

    You need to make sure the frame is fully loaded the best way to do it is to use onload:

    <iframe id="nesgt" src="" onload="custom()"></iframe>
    
    function custom(){
        document.getElementById("nesgt").contentWindow.document;
        }
    

    this function will run automatically when the iframe is fully loaded.

    it could be done with setTimeout but we can't get the exact time of the frame load.

    hope this helps someone.

    Drawing an image from a data URL to a canvas

    Perhaps this fiddle would help ThumbGen - jsFiddle It uses File API and Canvas to dynamically generate thumbnails of images.

    (function (doc) {
        var oError = null;
        var oFileIn = doc.getElementById('fileIn');
        var oFileReader = new FileReader();
        var oImage = new Image();
        oFileIn.addEventListener('change', function () {
            var oFile = this.files[0];
            var oLogInfo = doc.getElementById('logInfo');
            var rFltr = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i
            try {
                if (rFltr.test(oFile.type)) {
                    oFileReader.readAsDataURL(oFile);
                    oLogInfo.setAttribute('class', 'message info');
                    throw 'Preview for ' + oFile.name;
                } else {
                    oLogInfo.setAttribute('class', 'message error');
                    throw oFile.name + ' is not a valid image';
                }
            } catch (err) {
                if (oError) {
                    oLogInfo.removeChild(oError);
                    oError = null;
                    $('#logInfo').fadeOut();
                    $('#imgThumb').fadeOut();
                }
                oError = doc.createTextNode(err);
                oLogInfo.appendChild(oError);
                $('#logInfo').fadeIn();
            }
        }, false);
        oFileReader.addEventListener('load', function (e) {
            oImage.src = e.target.result;
        }, false);
        oImage.addEventListener('load', function () {
            if (oCanvas) {
                oCanvas = null;
                oContext = null;
                $('#imgThumb').fadeOut();
            }
            var oCanvas = doc.getElementById('imgThumb');
            var oContext = oCanvas.getContext('2d');
            var nWidth = (this.width > 500) ? this.width / 4 : this.width;
            var nHeight = (this.height > 500) ? this.height / 4 : this.height;
            oCanvas.setAttribute('width', nWidth);
            oCanvas.setAttribute('height', nHeight);
            oContext.drawImage(this, 0, 0, nWidth, nHeight);
            $('#imgThumb').fadeIn();
        }, false);
    })(document);