Programs & Examples On #Wscf

How to navigate through a vector using iterators? (C++)

Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[].

To access arbitrary elements in a vector vec, you can use the following:

vec.begin()                  // 1st
vec.begin()+1                // 2nd
// ...
vec.begin()+(i-1)            // ith
// ...
vec.begin()+(vec.size()-1)   // last

The following is an example of a typical access pattern (earlier versions of C++):

int sum = 0;
using Iter = std::vector<int>::const_iterator;
for (Iter it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

The advantage of using iterator is that you can apply the same pattern with other containers:

sum = 0;
for (Iter it = lst.begin(); it!=lst.end(); ++it) {
    sum += *it;
}

For this reason, it is really easy to create template code that will work the same regardless of the container type. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).

Another option using std::for_each and lambdas:

sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });

Since C++11 you can use auto to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):

sum = 0;
for (auto it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

And, in addition, there is a simpler for-each variant:

sum = 0;
for (auto value : vec) {
    sum += value;
}

And finally there is also std::accumulate where you have to be careful whether you are adding integer or floating point numbers.

How to close Android application?

@Override
    protected void onPause() {
        super.onPause();
        System.exit(0);
    }

If Radio Button is selected, perform validation on Checkboxes

You need to use == or === for comparison. = assigns a new value.

Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).

How do you iterate through every file/directory recursively in standard C++?

You don't. Standard C++ doesn't expose to concept of a directory. Specifically it doesn't give any way to list all the files in a directory.

A horrible hack would be to use system() calls and to parse the results. The most reasonable solution would be to use some kind of cross-platform library such as Qt or even POSIX.

Circular (or cyclic) imports in Python

There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.

Imports are pretty straightforward really. Just remember the following:

'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.

Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.

Take that lot together and you shouldn't get any surprises when importing modules.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This can also happen when you disabled MFA. There will be an old long term entry in the AWS credentials.

Edit the file manually with editor of choice, here using vi (please backup before):

vi ~/.aws/credentials

Then remove the [default-long-term] section. As result in a minimal setup there should be one section [default] left with the actual credentials.

[default-long-term]
aws_access_key_id = ...
aws_secret_access_key = ...
aws_mfa_device = ...

Print array to a file

Either var_export or set print_r to return the output instead of printing it.

Example from PHP manual

$b = array (
    'm' => 'monkey', 
    'foo' => 'bar', 
    'x' => array ('x', 'y', 'z'));

$results = print_r($b, true); // $results now contains output from print_r

You can then save $results with file_put_contents. Or return it directly when writing to file:

file_put_contents('filename.txt', print_r($b, true));

Passing data between controllers in Angular JS?

Solution without creating Service, using $rootScope:

To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.

The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.

var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = true;
}]);

app.controller('Ctrl2', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = false;
}]);

Using $rootScope in a template (Access properties with $root):

<div ng-controller="Ctrl1">
    <div class="banner" ng-show="$root.showBanner"> </div>
</div>

Onclick on bootstrap button

<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>

$('#fire').on('click', function (e) {

     //your awesome code here

})

gradle build fails on lint task

In Android Studio v1.2, it tells you how to fix it:

enter image description here

Import SQL file into mysql

If you are using wamp you can try this. Just type use your_Database_name first.

  1. Click your wamp server icon then look for MYSQL > MSQL Console then run it.

  2. If you dont have password, just hit enter and type :

    mysql> use database_name;
    mysql> source location_of_your_file;
    

    If you have password, you will promt to enter a password. Enter you password first then type:

    mysql> use database_name;
    mysql> source location_of_your_file;
    

location_of_your_file should look like C:\mydb.sql

so the commend is mysql>source C:\mydb.sql;

This kind of importing sql dump is very helpful for BIG SQL FILE.

I copied my file mydb.sq to directory C: .It should be capital C: in order to run

and that's it.

Why are you not able to declare a class as static in Java?

Everything we code in java goes into a class. Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have the same set of copy to all objects.

So, if Java would have allowed the top class to be static whenever you run a program it creates an Object and keeps overriding on to the same Memory Location.

If You are just replacing the object every time you run it whats the point of creating it?

So that is the reason Java got rid of the static for top-Level Class.

There might be more concrete reasons but this made much logical sense to me.

Difference between virtual and abstract methods

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.

So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.

public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}

Setting different color for each series in scatter plot on matplotlib

An easy fix

If you have only one type of collections (e.g. scatter with no error bars) you can also change the colours after that you have plotted them, this sometimes is easier to perform.

import matplotlib.pyplot as plt
from random import randint
import numpy as np

#Let's generate some random X, Y data X = [ [frst group],[second group] ...]
X = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
Y = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
labels = range(1,len(X)+1)

fig = plt.figure()
ax = fig.add_subplot(111)
for x,y,lab in zip(X,Y,labels):
        ax.scatter(x,y,label=lab)

The only piece of code that you need:

#Now this is actually the code that you need, an easy fix your colors just cut and paste not you need ax.
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired  
colorst = [colormap(i) for i in np.linspace(0, 0.9,len(ax.collections))]       
for t,j1 in enumerate(ax.collections):
    j1.set_color(colorst[t])


ax.legend(fontsize='small')

The output gives you differnent colors even when you have many different scatter plots in the same subplot.

enter image description here

Generate a random letter in Python

>>> import random
>>> import string    
>>> random.choice(string.ascii_lowercase)
'b'

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

Javascript String to int conversion

If you are sure id.substring(indexPos) is a number, you can do it like so:

var number = Number(id.substring(indexPos)) + 1;

Otherwise I suggest checking if the Number function evaluates correctly.

Razor Views not seeing System.Web.Mvc.HtmlHelper

I tried all the solutions here but none of them worked for me. Again, my site runs fine but I don't have intellisense and get red wavy lines under a lot of things in my views that Visual Studio does not recognize, one of them being Html.BeginForm(), as well as anything having to do with ViewBag.

I'm working with a new MVC 5 project. After hours of comparing web.config lines, I finally found what fixed it for me.

My web.config in my root had the following line:

<system.web>
  <compilation debug="true" targetFramework="4.5" />

  <!-- ... -->
</system.web>

I compared to a previous project not using MVC 5, and copied over a block I noticed was missing from the new one, which was the following:

<system.web>
  <compilation debug="true" targetFramework="4.5">
    <assemblies>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </assemblies>
  </compilation>

  <!-- ... -->
</system.web>

I copied the above block over to my new project's web.config in the root, changing the versions to match the numbers for each assembly found in my project references (right-clicking each reference mentioned and selecting "Properties", "Version" is given at the bottom of the properties window for the selected reference).

After implementing the above, I now have intellisense and don't get any unknown red lines under things like Html.BeginForm, ViewBag.Title, etc.

How to download and save a file from Internet using Java?

There are many elegant and efficient answers here. But the conciseness can make us lose some useful information. In particular, one often does not want to consider a connection error an Exception, and one might want to treat differently some kind of network-related errors - for example, to decide if we should retry the download.

Here's a method that does not throw Exceptions for network errors (only for truly exceptional problems, as malformed url or problems writing to the file)

/**
 * Downloads from a (http/https) URL and saves to a file. 
 * Does not consider a connection error an Exception. Instead it returns:
 *  
 *    0=ok  
 *    1=connection interrupted, timeout (but something was read)
 *    2=not found (FileNotFoundException) (404) 
 *    3=server error (500...) 
 *    4=could not connect: connection timeout (no internet?) java.net.SocketTimeoutException
 *    5=could not connect: (server down?) java.net.ConnectException
 *    6=could not resolve host (bad host, or no internet - no dns)
 * 
 * @param file File to write. Parent directory will be created if necessary
 * @param url  http/https url to connect
 * @param secsConnectTimeout Seconds to wait for connection establishment
 * @param secsReadTimeout Read timeout in seconds - trasmission will abort if it freezes more than this 
 * @return See above
 * @throws IOException Only if URL is malformed or if could not create the file
 */
public static int saveUrl(final Path file, final URL url, 
  int secsConnectTimeout, int secsReadTimeout) throws IOException {
    Files.createDirectories(file.getParent()); // make sure parent dir exists , this can throw exception
    URLConnection conn = url.openConnection(); // can throw exception if bad url
    if( secsConnectTimeout > 0 ) conn.setConnectTimeout(secsConnectTimeout * 1000);
    if( secsReadTimeout > 0 ) conn.setReadTimeout(secsReadTimeout * 1000);
    int ret = 0;
    boolean somethingRead = false;
    try (InputStream is = conn.getInputStream()) {
        try (BufferedInputStream in = new BufferedInputStream(is); OutputStream fout = Files
                .newOutputStream(file)) {
            final byte data[] = new byte[8192];
            int count;
            while((count = in.read(data)) > 0) {
                somethingRead = true;
                fout.write(data, 0, count);
            }
        }
    } catch(java.io.IOException e) { 
        int httpcode = 999;
        try {
            httpcode = ((HttpURLConnection) conn).getResponseCode();
        } catch(Exception ee) {}
        if( somethingRead && e instanceof java.net.SocketTimeoutException ) ret = 1;
        else if( e instanceof FileNotFoundException && httpcode >= 400 && httpcode < 500 ) ret = 2; 
        else if( httpcode >= 400 && httpcode < 600 ) ret = 3; 
        else if( e instanceof java.net.SocketTimeoutException ) ret = 4; 
        else if( e instanceof java.net.ConnectException ) ret = 5; 
        else if( e instanceof java.net.UnknownHostException ) ret = 6;  
        else throw e;
    }
    return ret;
}

How can I throw a general exception in Java?

It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.

Extract filename and extension in Bash

Here is a sed solution that extracts path components in a variety of forms and can handle most edge cases:

## Enter the input path and field separator character, for example:
## (separatorChar must not be present in inputPath)

inputPath="/path/to/Foo.bar"
separatorChar=":"

## sed extracts the path components and assigns them to output variables

oldIFS="$IFS"
IFS="$separatorChar"
read dirPathWithSlash dirPath fileNameWithExt fileName fileExtWithDot fileExt <<<"$(sed -En '
s/^[[:space:]]+//
s/[[:space:]]+$//
t l1
:l1
s/^([^/]|$)//
t
s/[/]+$//
t l2
:l2
s/^$/filesystem\/\
filesystem/p
t
h
s/^(.*)([/])([^/]+)$/\1\2\
\1\
\3/p
g
t l3
:l3
s/^.*[/]([^/]+)([.])([a-zA-Z0-9]+)$/\1\
\2\3\
\3/p
t
s/^.*[/](.+)$/\1/p
' <<<"$inputPath" | tr "\n" "$separatorChar")"
IFS="$oldIFS"

## Results (all use separatorChar=":")

## inputPath        = /path/to/Foo.bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = Foo.bar
## fileName         = Foo
## fileExtWithDot   = .bar
## fileExt          = bar

## inputPath        = /path/to/Foobar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = Foobar
## fileName         = Foobar
## fileExtWithDot   =
## fileExt          =

## inputPath        = /path/to/...bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = ...bar
## fileName         = ..
## fileExtWithDot   = .bar
## fileExt          = bar

## inputPath        = /path/to/..bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = ..bar
## fileName         = .
## fileExtWithDot   = .bar
## fileExt          = bar

## inputPath        = /path/to/.bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = .bar
## fileName         = .bar
## fileExtWithDot   = 
## fileExt          = 

## inputPath        = /path/to/...
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = ...
## fileName         = ...
## fileExtWithDot   =
## fileExt          =

## inputPath        = /path/to/Foo.
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = Foo.
## fileName         = Foo.
## fileExtWithDot   =
## fileExt          =

## inputPath        = / (the root directory)
## dirPathWithSlash = filesystem/
## dirPath          = filesystem
## fileNameWithExt  =
## fileName         =
## fileExtWithDot   =
## fileExt          =

## inputPath        =  (invalid because empty)
## dirPathWithSlash =
## dirPath          =
## fileNameWithExt  =
## fileName         =
## fileExtWithDot   =
## fileExt          =

## inputPath        = Foo/bar (invalid because doesn't start with a forward slash)
## dirPathWithSlash =
## dirPath          =
## fileNameWithExt  =
## fileName         =
## fileExtWithDot   =
## fileExt          =

Here's how it works:

sed parses the input path and prints the following path components in order on separate lines:

  • directory path with a trailing slash character
  • directory path without a trailing slash character
  • file name with extension
  • file name without extension
  • file extension with a leading dot character
  • file extension without a leading dot character

tr converts the sed output into a separator character-delimited string of the above path components.

read uses the separator character as the field separator (IFS="$separatorChar") and assigns each of the path components to its respective variable.

Here's how the sed construct works:

  • s/^[[:space:]]+// and s/[[:space:]]+$// strip any leading and/or trailing whitespace characters
  • t l1 and :l1 refreshes the t function for the next s function
  • s/^([^/]|$)// and t tests for an invalid input path (one that does not begin with a forward slash), in which case it leaves all output lines blank and quits the sed command
  • s/[/]+$// strips any trailing slashes
  • t l2 and :l2 refreshes the t function for the next s function
  • s/^$/filesystem\/\\[newline]filesystem/p and t tests for the special case where the input path consists of the root directory /, in which case it prints filesystem/ and filesystem for the dirPathWithSlash and dirPath output lines, leaves all other output lines blank, and quits the sed command
  • h saves the input path in the hold space
  • s/^(.*)([/])([^/]+)$/\1\2\\[newline]\1\\[newline]\3/p prints the dirPathWithSlash, dirPath, and fileNameWithExt output lines
  • g retrieves the input path from the hold space
  • t l3 and :l3 refreshes the t function for the next s function
  • s/^.*\[/]([^/]+)([.])([a-zA-Z0-9]+)$/\1\\[newline]\2\3\\[newline]\3/p and t prints the fileName, fileExtWithDot, and fileExt output lines for the case where a file extension exists, (assumed to consist of alphanumeric characters only), then quits the sed command
  • s/^.*\[/](.+)$/\1/p prints the fileName but not the fileExtWithDot, and fileExt output lines for the case where a file extension does not exist, then quits the sed command.

How do I disable text selection with CSS or JavaScript?

I'm not sure if you can turn it off, but you can change the colors of it :)

myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
    background:#000;
    color:#fff;
}

Then just match the colors to your "darky" design and see what happens :)

Java8: sum values from specific field of the objects in a list

You can try

int sum = list.stream().filter(o->o.field>10).mapToInt(o->o.field).sum();

Like explained here

javascript: optional first argument in function

There is a nice read on Default parameters in ES6 on the MDN website here.
In ES6 you can now do the following:

secondDefaultValue = 'indirectSecondDefaultValue';

function MyObject( param1 = 'firstDefaultValue', param2 = secondDefaultValue ){
    this.first = param1;
    this.second = param2;
}

You can use this also as follows:

var object = new MyObject( undefined, options );

Which will set default value 'firstDefaultValue' for first param1 and your options for second param2.

Here a demonstration in a fiddle

Haskell: Converting Int to String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

Excel how to fill all selected blank cells with text

If all the cells are under one column, you could just filter the column and then select "(blank)" and then insert any value into the cells. But be careful, press "alt + 4" to make sure you are inserting value into the visible cells only.

What does <> mean?

It means not equal to. The same as != seen in C style languages, as well as actionscript.

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

How to detect when an @Input() value changes in Angular?

The safest bet is to go with a shared service instead of a @Input parameter. Also, @Input parameter does not detect changes in complex nested object type.

A simple example service is as follows:

Service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class SyncService {

    private thread_id = new Subject<number>();
    thread_id$ = this.thread_id.asObservable();

    set_thread_id(thread_id: number) {
        this.thread_id.next(thread_id);
    }

}

Component.ts

export class ConsumerComponent implements OnInit {

  constructor(
    public sync: SyncService
  ) {
     this.sync.thread_id$.subscribe(thread_id => {
          **Process Value Updates Here**
      }
    }
  
  selectChat(thread_id: number) {  <--- How to update values
    this.sync.set_thread_id(thread_id);
  }
}

You can use a similar implementation in other components and all your compoments will share the same shared values.

Where is the WPF Numeric UpDown control?

Go to NugetPackage manager of you project-> Browse and search for mahApps.Metro -> install package into you project. You will see Reference added: MahApps.Metro. Then in you XAML code add:

"xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"

Where you want to use your object add:

<mah:NumericUpDown x:Name="NumericUpDown" ... /> 

Enjoy the full extensibility of the object (Bindings, triggers and so on...).

A top-like utility for monitoring CUDA activity on a GPU

If you just want to find the process which is running on gpu, you can simply using the following command:

lsof /dev/nvidia*

For me nvidia-smi and watch -n 1 nvidia-smi are enough in most cases. Sometimes nvidia-smi shows no process but the gpu memory is used up so i need to use the above command to find the processes.

How to stop Python closing immediately when executed in Microsoft Windows

Very simple:

  1. Open command prompt as an administrator.
  2. Type python.exe (provided you have given path of it in environmental variables)

Then, In the same command prompt window the python interpreter will start with >>>

This worked for me.

Problems with entering Git commit message with Vim

Typically, git commit brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR environment variable) for you to edit your commit message in. When you save and exit, the commit completes.

You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.

Spring JUnit: How to Mock autowired component in autowired component

I created blog post on the topic. It contains also link to Github repository with working example.

The trick is using test configuration, where you override original spring bean with fake one. You can use @Primary and @Profile annotations for this trick.

How to remove padding around buttons in Android?

That's not padding, it's the shadow around the button in its background drawable. Create your own background and it will disappear.

Eloquent Collection: Counting and Detect Empty

You can do

$result = Model::where(...)->count(); 

to count the results.

You can also use

if ($result->isEmpty()){}

to check whether or not the result is empty.

Case insensitive comparison NSString

- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString

Bootstrap Modal sitting behind backdrop

I was missing the follow html

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

added it and worked without problems

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

GlobalConfiguration class is part of Microsoft.AspNet.WebApi.WebHost nuget package...Have you upgraded this package to Web API 2?

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Finish an activity from another activity

  1. Make your activity A in manifest file: launchMode = "singleInstance"

  2. When the user clicks new, do FirstActivity.fa.finish(); and call the new Intent.

  3. When the user clicks modify, call the new Intent or simply finish activity B.

FIRST WAY

In your first activity, declare one Activity object like this,

public static Activity fa;
onCreate()
{
    fa = this;
}

now use that object in another Activity to finish first-activity like this,

onCreate()
{
    FirstActivity.fa.finish();
}

SECOND WAY

While calling your activity FirstActivity which you want to finish as soon as you move on, You can add flag while calling FirstActivity

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

But using this flag the activity will get finished evenif you want it not to. and sometime onBack if you want to show the FirstActivity you will have to call it using intent.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

It seems Laravel is trying to use category_posts table (because of many-to-many relationship). But you don't have this table, because you've created category_post table. Change name of the table to category_posts.

Stop Chrome Caching My JS Files

Things that did not work for me:

  • clicking the refresh icon (with or without shift)
  • SHIFT-F5, CTRL-F5
  • opening the page in an incognito window
  • F12 (to open Dev tools) / (Dev tools) Settings / Disable cache (while dev tools is open)

What I mean by not working is: In the file system the .js file has been updated, but Chrome does not pick up the change. It means the page script executes with the old logic, Dev tools Scripts / ... / Compiled / ... shows the old .js content.

What does work for me:

  • Close Chrome and re-open the page. After this Dev tools Scripts / ... / Compiled / ... shows updated .js content (matching the file system), and page scripts excute with updated logic.

Chrome version 86.0.4240.193 (Official Build) (64-bit)

Add image to layout in ruby on rails

When using the new ruby, the image folder will go to asset folder on folder app

after placing your images in image folder, use

<%=image_tag("example_image.png", alt: "Example Image")%>

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Given that neither time is going to be very accurate, one way to use setTimeout to be a little more accurate is to calculate how long the delay was since the last iteration, and then adjust the next iteration as appropriate. For example:

var myDelay = 1000;
var thisDelay = 1000;
var start = Date.now();

function startTimer() {    
    setTimeout(function() {
        // your code here...
        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

So the first time it'll wait (at least) 1000 ms, when your code gets executed, it might be a little late, say 1046 ms, so we subtract 46 ms from our delay for the next cycle and the next delay will be only 954 ms. This won't stop the timer from firing late (that's to be expected), but helps you to stop the delays from pilling up. (Note: you might want to check for thisDelay < 0 which means the delay was more than double your target delay and you missed a cycle - up to you how you want to handle that case).

Of course, this probably won't help you keep several timers in sync, in which case you might want to figure out how to control them all with the same timer.

So looking at your code, all your delays are a multiple of 500, so you could do something like this:

var myDelay = 500;
var thisDelay = 500;
var start = Date.now();
var beatCount = 0;

function startTimer() {    
    setTimeout(function() {
        beatCount++;
        // your code here...
        //code for the bass playing goes here  

        if (count%2 === 0) {
            //code for the chords playing goes here (every 1000 ms)
        }

        if (count%16) {
            //code for the drums playing goes here (every 8000 ms)
        }

        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

Node.js/Express.js App Only Works on Port 3000

In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.

Compare two Byte Arrays? (Java)

You can use both Arrays.equals() and MessageDigest.isEqual(). These two methods have some differences though.

MessageDigest.isEqual() is a time-constant comparison method and Arrays.equals() is non time-constant and it may bring some security issues if you use it in a security application.

The details for the difference can be read at Arrays.equals() vs MessageDigest.isEqual()

IntelliJ and Tomcat.. Howto..?

NOTE: Community Edition doesn't support JEE.

First, you will need to install a local Tomcat server. It sounds like you may have already done this.

Next, on the toolbar at the top of IntelliJ, click the down arrow just to the left of the Run and Debug icons. There will be an option to Edit Configurations. In the resulting popup, click the Add icon, then click Tomcat and Local.

From that dialog, you will need to click the Configure... button next to Application Server to tell IntelliJ where Tomcat is installed.

Passing bash variable to jq

I resolved this issue by escaping the inner double quotes

projectID=$(cat file.json | jq -r ".resource[] | select(.username==\"$EMAILID\") | .id")

How to handle back button in activity

A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button

Regular expression for decimal number

As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.

double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))

Not relevant to the original question asked but confirming that TryParse() indeed is a good option.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Mongoose, update values in array of objects

Having tried other solutions which worked fine, but the pitfall of their answers is that only fields already existing would update adding upsert to it would do nothing, so I came up with this.

 Person.update({'items.id': 2}, {$set: {
    'items': { "item1",  "item2",  "item3",  "item4" } }, {upsert: 
true })

C# equivalent of the IsNull() function in SQL Server

You Write Two Function

    //When Expression is Number
    public static double? isNull(double? Expression, double? Value)
    {
        if (Expression ==null)
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }


    //When Expression is string (Can not send Null value in string Expression
    public static string isEmpty(string Expression, string Value)
    {
        if (Expression == "")
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }

They Work Very Well

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

How to create a numeric vector of zero length in R

If you read the help for vector (or numeric or logical or character or integer or double, 'raw' or complex etc ) then you will see that they all have a length (or length.out argument which defaults to 0

Therefore

numeric()
logical()
character()
integer()
double()
raw()
complex() 
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')

All return 0 length vectors of the appropriate atomic modes.

# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')

Get AVG ignoring Null or Zero values

NULL is already ignored so you can use NULLIF to turn 0 to NULL. Also you don't need DISTINCT and your WHERE on ActualTime is not sargable.

SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1,
       AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2,
       AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT))    AS Average3
FROM   Table1 a
WHERE  a.ActualTime >= '20130401'
       AND a.ActualTime < '20130501' 

PS I have no idea what Table2 b is in the original query for as there is no join condition for it so have omitted it from my answer.

Element count of an array in C++

Since C++17 you can also use the standardized free function: std::size(container) which will return the amount of elements in that container.

example:

std::vector<int> vec = { 1, 2, 3, 4, 8 };
std::cout << std::size(vec) << "\n\n";    // 5

int A[] = {40,10,20};
std::cout << std::size(A) << '\n';      // 3

Deleting Objects in JavaScript

Just found a jsperf you may consider interesting in light of this matter. (it could be handy to keep it around to complete the picture)

It compares delete, setting null and setting undefined.

But keep in mind that it tests the case when you delete/set property many times.

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

Create directories using make file

This would do it - assuming a Unix-like environment.

MKDIR_P = mkdir -p

.PHONY: directories

all: directories program

directories: ${OUT_DIR}

${OUT_DIR}:
        ${MKDIR_P} ${OUT_DIR}

This would have to be run in the top-level directory - or the definition of ${OUT_DIR} would have to be correct relative to where it is run. Of course, if you follow the edicts of Peter Miller's "Recursive Make Considered Harmful" paper, then you'll be running make in the top-level directory anyway.

I'm playing with this (RMCH) at the moment. It needed a bit of adaptation to the suite of software that I am using as a test ground. The suite has a dozen separate programs built with source spread across 15 directories, some of it shared. But with a bit of care, it can be done. OTOH, it might not be appropriate for a newbie.


As noted in the comments, listing the 'mkdir' command as the action for 'directories' is wrong. As also noted in the comments, there are other ways to fix the 'do not know how to make output/debug' error that results. One is to remove the dependency on the the 'directories' line. This works because 'mkdir -p' does not generate errors if all the directories it is asked to create already exist. The other is the mechanism shown, which will only attempt to create the directory if it does not exist. The 'as amended' version is what I had in mind last night - but both techniques work (and both have problems if output/debug exists but is a file rather than a directory).

Java 8: Lambda-Streams, Filter by Method with Exception

Extending @marcg solution, you can normally throw and catch a checked exception in Streams; that is, compiler will ask you to catch/re-throw as is you were outside streams!!

@FunctionalInterface
public interface Predicate_WithExceptions<T, E extends Exception> {
    boolean test(T t) throws E;
}

/**
 * .filter(rethrowPredicate(t -> t.isActive()))
 */
public static <T, E extends Exception> Predicate<T> rethrowPredicate(Predicate_WithExceptions<T, E> predicate) throws E {
    return t -> {
        try {
            return predicate.test(t);
        } catch (Exception exception) {
            return throwActualException(exception);
        }
    };
}

@SuppressWarnings("unchecked")
private static <T, E extends Exception> T throwActualException(Exception exception) throws E {
    throw (E) exception;
}

Then, your example would be written as follows (adding tests to show it more clearly):

@Test
public void testPredicate() throws MyTestException {
    List<String> nonEmptyStrings = Stream.of("ciao", "")
            .filter(rethrowPredicate(s -> notEmpty(s)))
            .collect(toList());
    assertEquals(1, nonEmptyStrings.size());
    assertEquals("ciao", nonEmptyStrings.get(0));
}

private class MyTestException extends Exception { }

private boolean notEmpty(String value) throws MyTestException {
    if(value==null) {
        throw new MyTestException();
    }
    return !value.isEmpty();
}

@Test
public void testPredicateRaisingException() throws MyTestException {
    try {
        Stream.of("ciao", null)
                .filter(rethrowPredicate(s -> notEmpty(s)))
                .collect(toList());
        fail();
    } catch (MyTestException e) {
        //OK
    }
}

jQuery function to get all unique elements from an array?

    // for numbers
    a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
    $.unique(a)
    [7, 6, 1, 8, 3, 2, 5, 4]

    // for string
    a = ["a", "a", "b"]
    $.unique(a)
    ["b", "a"]

And for dom elements there is no example is needed here I guess because you already know that!

Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/

Round number to nearest integer

Use round(x, y). It will round up your number up to your desired decimal place.

For example:

>>> round(32.268907563, 3)
32.269

Change column type in pandas

Starting pandas 1.0.0, we have pandas.DataFrame.convert_dtypes. You can even control what types to convert!

In [40]: df = pd.DataFrame(
    ...:     {
    ...:         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
    ...:         "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
    ...:         "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
    ...:         "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
    ...:         "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
    ...:         "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    ...:     }
    ...: )

In [41]: dff = df.copy()

In [42]: df 
Out[42]: 
   a  b      c    d     e      f
0  1  x   True    h  10.0    NaN
1  2  y  False    i   NaN  100.5
2  3  z    NaN  NaN  20.0  200.0

In [43]: df.dtypes
Out[43]: 
a      int32
b     object
c     object
d     object
e    float64
f    float64
dtype: object

In [44]: df = df.convert_dtypes()

In [45]: df.dtypes
Out[45]: 
a      Int32
b     string
c    boolean
d     string
e      Int64
f    float64
dtype: object

In [46]: dff = dff.convert_dtypes(convert_boolean = False)

In [47]: dff.dtypes
Out[47]: 
a      Int32
b     string
c     object
d     string
e      Int64
f    float64
dtype: object

How to increase apache timeout directive in .htaccess?

This solution is for Litespeed Server (Apache as well)

Add the following code in .htaccess

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

Litespeed reference

How to find the day, month and year with moment.js

I am getting day, month and year using dedicated functions moment().date(), moment().month() and moment().year() of momentjs.

_x000D_
_x000D_
let day = moment('2014-07-28', 'YYYY/MM/DD').date();_x000D_
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();_x000D_
let year = moment('2014-07-28', 'YYYY/MM/DD').year();_x000D_
_x000D_
console.log(day);_x000D_
console.log(month);_x000D_
console.log(year);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

I don't know why there are 48 upvotes for @Chris Schmitz answer which is not 100% correct.

Month is in form of array and starts from 0 so to get exact value we should use 1 + moment().month()

Defining a `required` field in Bootstrap

Update 2018

Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.

<input type="email" class="form-control" id="exampleInputEmail1" required>

or in compliant HTML5:

<input type="email" class="form-control" id="exampleInputEmail1" required="true">

Read more on Bootstrap 4 validation


In Bootstrap 3, you can apply a "validation state" class to the parent element: http://getbootstrap.com/css/#forms-control-validation

For example has-error will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.

Demo: http://bootply.com/90564


MSSQL Error 'The underlying provider failed on Open'

Make sure that each element value in the connection string being supplied is correct. In my case, I was getting the same error because the name of the catalog (database name) specified in the connection string was incorrect.

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

Trigger a Travis-CI rebuild without pushing a commit?

I just triggered the tests on a pull request to be re-run by clicking 'update branch' here: github check tests component

Running interactive commands in Paramiko

You can use this method to send whatever confirmation message you want like "OK" or the password. This is my solution with an example:

def SpecialConfirmation(command, message, reply):
    net_connect.config_mode()    # To enter config mode
    net_connect.remote_conn.sendall(str(command)+'\n' )
    time.sleep(3)
    output = net_connect.remote_conn.recv(65535).decode('utf-8')
    ReplyAppend=''
    if str(message) in output:
        for i in range(0,(len(reply))):
            ReplyAppend+=str(reply[i])+'\n'
        net_connect.remote_conn.sendall(ReplyAppend)
        output = net_connect.remote_conn.recv(65535).decode('utf-8') 
    print (output)
    return output

CryptoPkiEnroll=['','','no','no','yes']

output=SpecialConfirmation ('crypto pki enroll TCA','Password' , CryptoPkiEnroll )
print (output)

Free tool to Create/Edit PNG Images?

Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.

Setting Curl's Timeout in PHP

There is a quirk with this that might be relevant for some people... From the PHP docs comments.

If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:

"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."

What this means to PHP developers is "You can't use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"

The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.

The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts:

if (!isset($_GET['foo'])) {
    // Client
    $ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_errno > 0) {
        echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
        echo "Data received: $data\n";
    }
} else {
    // Server
    sleep(10);
    echo "Done.";
}

From http://www.php.net/manual/en/function.curl-setopt.php#104597

Log.INFO vs. Log.DEBUG

Also remember that all info(), error(), and debug() logging calls provide internal documentation within any application.

Concatenate two slices in Go

Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:

func append

func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

Get position/offset of element relative to a parent container?

Warning: jQuery, not standard JavaScript

element.offsetLeft and element.offsetTop are the pure javascript properties for finding an element's position with respect to its offsetParent; being the nearest parent element with a position of relative or absolute

Alternatively, you can always use Zepto to get the position of an element AND its parent, and simply subtract the two:

var childPos = obj.offset();
var parentPos = obj.parent().offset();
var childOffset = {
    top: childPos.top - parentPos.top,
    left: childPos.left - parentPos.left
}

This has the benefit of giving you the offset of a child relative to its parent even if the parent isn't positioned.

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

This is the post I read from apple Swift blog, might be helpful:

App Compatibility:

If you write a Swift app you can trust that your app will work well into the future. In fact, you can target back to OS X Mavericks or iOS 7 with that same app. This is possible because Xcode embeds a small Swift runtime library within your app's bundle. Because the library is embedded, your app uses a consistent version of Swift that runs on past, present, and future OS releases.

Binary Compatibility and Frameworks:

While your app's runtime compatibility is ensured, the Swift language itself will continue to evolve, and the binary interface will also change. To be safe, all components of your app should be built with the same version of Xcode and the Swift compiler to ensure that they work together.

This means that frameworks need to be managed carefully. For instance, if your project uses frameworks to share code with an embedded extension, you will want to build the frameworks, app, and extensions together. It would be dangerous to rely upon binary frameworks that use Swift — especially from third parties. As Swift changes, those frameworks will be incompatible with the rest of your app. When the binary interface stabilizes in a year or two, the Swift runtime will become part of the host OS and this limitation will no longer exist.

How can one create an overlay in css?

I'm late to the party, but if you want to do this to an arbitrary element using only CSS, without messing around with positioning, overlay divs etc., you can use an inset box shadow:

box-shadow: inset 0px 0px 0 2000px rgba(0,0,0,0.5);

This will work on any element smaller than 4000 pixels long or wide.

example: http://jsfiddle.net/jTwPc/

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

This problem occurs if there are different jar versions. Especially versions of httpcore and httpclient. Use same versions of httpcore and httpclient.

Applying function with multiple arguments to create a new pandas column

One more dict style clean syntax:

df["new_column"] = df.apply(lambda x: x["A"] * x["B"], axis = 1)

or,

df["new_column"] = df["A"] * df["B"]

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date as argument2, and the result (expected) format as argument 3.

Refer to this link to understand various formats: Available Date Formats

public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {

    String result = "";
    SimpleDateFormat sdf;
    SimpleDateFormat sdf1;

    try {
        sdf = new SimpleDateFormat(givenformat);
        sdf1 = new SimpleDateFormat(resultformat);
        result = sdf1.format(sdf.parse(date));
    }
    catch(Exception e) {
        e.printStackTrace();
        return "";
    }
    finally {
        sdf=null;
        sdf1=null;
    }
    return result;
}

Rename multiple files in cmd

@echo off
for %%f in (*.txt) do (
    ren "%%~nf%%~xf" "%%~nf 1.1%%~xf"
)

How do I pre-populate a jQuery Datepicker textbox with today's date?

var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
        myDate.getFullYear();
$("#date_pretty").val(prettyDate);

seemed to work, but there might be a better way out there..

How to see the actual Oracle SQL statement that is being executed

I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.

List attributes of an object

All previous answers are correct, you have three options for what you are asking

  1. dir()

  2. vars()

  3. __dict__

>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
>>> vars(a)
{'multi': 4, 'str': '2'}
>>> a.__dict__
{'multi': 4, 'str': '2'}

How to check if spark dataframe is empty?

In Scala you can use implicits to add the methods isEmpty() and nonEmpty() to the DataFrame API, which will make the code a bit nicer to read.

object DataFrameExtensions {
  implicit def extendedDataFrame(dataFrame: DataFrame): ExtendedDataFrame = 
    new ExtendedDataFrame(dataFrame: DataFrame)

  class ExtendedDataFrame(dataFrame: DataFrame) {
    def isEmpty(): Boolean = dataFrame.head(1).isEmpty // Any implementation can be used
    def nonEmpty(): Boolean = !isEmpty
  }
}

Here, other methods can be added as well. To use the implicit conversion, use import DataFrameExtensions._ in the file you want to use the extended functionality. Afterwards, the methods can be used directly as so:

val df: DataFrame = ...
if (df.isEmpty) {
  // Do something
}

How to Apply Mask to Image in OpenCV?

You can use the mask to copy only the region of interest of an original image to a destination one:

cvCopy(origImage,destImage,mask);

where mask should be an 8-bit single channel array.

See more at the OpenCV docs

Align printf output in Java

You can refer to this blog for printing formatted coloured text on console

https://javaforqa.wordpress.com/java-print-coloured-table-on-console/

public class ColourConsoleDemo {
/**
*
* @param args
*
* "\033[0m BLACK" will colour the whole line
*
* "\033[37m WHITE\033[0m" will colour only WHITE.
* For colour while Opening --> "\033[37m" and closing --> "\033[0m"
*
*
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("\033[0m BLACK");
System.out.println("\033[31m RED");
System.out.println("\033[32m GREEN");
System.out.println("\033[33m YELLOW");
System.out.println("\033[34m BLUE");
System.out.println("\033[35m MAGENTA");
System.out.println("\033[36m CYAN");
System.out.println("\033[37m WHITE\033[0m");

//printing the results
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";

System.out.format("|---------Test Cases with Steps Summary -------------|%n");
System.out.format("+----------------------+---------+---------+---------+%n");
System.out.format("| Test Cases           |Passed   |Failed   |Skipped  |%n");
System.out.format("+----------------------+---------+---------+---------+%n");

String formattedMessage = "TEST_01".trim();

leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.print("\033[31m"); // Open print red
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
System.out.print("\033[0m"); // Close print red
System.out.format("+----------------------+---------+---------+---------+%n");
}

google maps v3 marker info window on mouseover

var icon1 = "imageA.png";
var icon2 = "imageB.png";

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: icon1,
    title: "some marker"
});

google.maps.event.addListener(marker, 'mouseover', function() {
    marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
    marker.setIcon(icon1);
});

Return multiple values to a method caller

Some answers suggest using out parameters but I recommend not using this due to they don’t work with async methods. See this for more information.

Other answers stated using Tuple, which I would recommend too but using the new feature introduced in C# 7.0.

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

Further information can be found here.

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

right click context menu for datagridview

  • Put a context menu on your form, name it, set captions etc. using the built-in editor
  • Link it to your grid using the grid property ContextMenuStrip
  • For your grid, create an event to handle CellContextMenuStripNeeded
  • The Event Args e has useful properties e.ColumnIndex, e.RowIndex.

I believe that e.RowIndex is what you are asking for.

Suggestion: when user causes your event CellContextMenuStripNeeded to fire, use e.RowIndex to get data from your grid, such as the ID. Store the ID as the menu event's tag item.

Now, when user actually clicks your menu item, use the Sender property to fetch the tag. Use the tag, containing your ID, to perform the action you need.

Facebook Android Generate Key Hash

If you are releasing, use the keystore you used to export your app with and not the debug.keystore.

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Update: This process is the same for upgrading 9.5 through at least 11.5; simply modify the commands to reflect versions 9.6 and 10, where 9.6 is the old version and 10 is the new version. Be sure to adjust the "old" and "new" directories accordingly, too.


I just upgraded PostgreSQL 9.5 to 9.6 on Ubuntu and thought I'd share my findings, as there are a couple of OS/package-specific nuances of which to be aware.

(I didn't want to have to dump and restore data manually, so several of the other answers here were not viable.)

In short, the process consists of installing the new version of PostgreSQL alongside the old version (e.g., 9.5 and 9.6), and then running the pg_upgrade binary, which is explained in (some) detail at https://www.postgresql.org/docs/9.6/static/pgupgrade.html .

The only "tricky" aspect of pg_upgrade is that failure to pass the correct value for an argument, or failure to be logged-in as the correct user or cd to the correct location before executing a command, may lead to cryptic error messages.

On Ubuntu (and probably Debian), provided you are using the "official" repo, deb http://apt.postgresql.org/pub/repos/apt/ xenial-pgdg main, and provided you haven't changed the default filesystem paths or runtime options, the following procedure should do the job.

Install the new version (note that we specify the 9.6, explicitly):

sudo apt install postgresql-9.6

Once installation succeeds, both versions will be running side-by-side, but on different ports. The installation output mentions this, at the bottom, but it's easy to overlook:

Creating new cluster 9.6/main ...
  config /etc/postgresql/9.6/main
  data   /var/lib/postgresql/9.6/main
  locale en_US.UTF-8
  socket /var/run/postgresql
  port   5433

Stop both server instances (this will stop both at the same time):

sudo systemctl stop postgresql

Switch to the dedicated PostgreSQL system user:

su postgres

Move into his home directory (failure to do this will cause errors):

cd ~

pg_upgrade requires the following inputs (pg_upgrade --help tells us this):

When you run pg_upgrade, you must provide the following information:
  the data directory for the old cluster  (-d DATADIR)
  the data directory for the new cluster  (-D DATADIR)
  the "bin" directory for the old version (-b BINDIR)
  the "bin" directory for the new version (-B BINDIR)

These inputs may be specified with "long names", to make them easier to visualize:

  -b, --old-bindir=BINDIR       old cluster executable directory
  -B, --new-bindir=BINDIR       new cluster executable directory
  -d, --old-datadir=DATADIR     old cluster data directory
  -D, --new-datadir=DATADIR     new cluster data directory

We must also pass the --new-options switch, because failure to do so results in the following:

connection to database failed: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/lib/postgresql/.s.PGSQL.50432"?

This occurs because the default configuration options are applied in the absence of this switch, which results in incorrect connection options being used, hence the socket error.

Execute the pg_upgrade command from the new PostgreSQL version:

/usr/lib/postgresql/9.6/bin/pg_upgrade --old-bindir=/usr/lib/postgresql/9.5/bin --new-bindir=/usr/lib/postgresql/9.6/bin --old-datadir=/var/lib/postgresql/9.5/main --new-datadir=/var/lib/postgresql/9.6/main --old-options=-cconfig_file=/etc/postgresql/9.5/main/postgresql.conf --new-options=-cconfig_file=/etc/postgresql/9.6/main/postgresql.conf

Logout of the dedicated system user account:

exit

The upgrade is now complete, but, the new instance will bind to port 5433 (the standard default is 5432), so keep this in mind if attempting to test the new instance before "cutting-over" to it.

Start the server as normal (again, this will start both the old and new instances):

systemctl start postgresql

If you want to make the new version the default, you will need to edit the effective configuration file, e.g., /etc/postgresql/9.6/main/postgresql.conf, and ensure that the port is defined as such:

port = 5432

If you do this, either change the old version's port number to 5433 at the same time (before starting the services), or, simply remove the old version (this will not remove your actual database content; you would need to use apt --purge remove postgresql-9.5 for that to happen):

apt remove postgresql-9.5

The above command will stop all instances, so you'll need to start the new instance one last time with:

systemctl start postgresql

As a final point of note, don't forget to consider pg_upgrade's good advice:

Upgrade Complete
----------------
Optimizer statistics are not transferred by pg_upgrade so,
once you start the new server, consider running:
    ./analyze_new_cluster.sh

Running this script will delete the old cluster's data files:
    ./delete_old_cluster.sh

Show constraints on tables command

afaik to make a request to information_schema you need privileges. If you need simple list of keys you can use this command:

SHOW INDEXES IN <tablename>

Passing arguments to AsyncTask, and returning results

Change your method to look like this:

String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list

And change your async task implementation

public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(baraj_mapa.this);
        dialog.setTitle("Calculating...");
        dialog.setMessage("Please wait...");
        dialog.setIndeterminate(true);
        dialog.show();
    }

    protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
        ArrayList<String> result = new ArrayList<String>();
        ArrayList<String> passed = passing[0]; //get passed arraylist

        //Some calculations...

        return result; //return result
    }

    protected void onPostExecute(ArrayList<String> result) {
        dialog.dismiss();
        String minim = result.get(0);
        int min = Integer.parseInt(minim);
        String glons = result.get(1);
        String glats = result.get(2);
        double glon = Double.parseDouble(glons);
        double glat = Double.parseDouble(glats);
        GeoPoint g = new GeoPoint(glon, glat);
        String korisni_linii = result.get(3);
    }

UPD:

If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:

new calc_stanica() {
    protected void onPostExecute(ArrayList<String> result) {
      // here you have access to the context in which execute was called in first place. 
      // You'll have to mark all the local variables final though..
     }
}.execute(passing);

Spring Boot yaml configuration for a list of strings

My guess is, that the @Value can not cope with "complex" types. You can go with a prop class like this:

@Component
@ConfigurationProperties('ignore')
class IgnoreSettings {
    List<String> filenames
}

Please note: This code is Groovy - not Java - to keep the example short! See the comments for tips how to adopt.

See the complete example https://github.com/christoph-frick/so-springboot-yaml-string-list

NameError: uninitialized constant (rails)

I started having this issue after upgrading from Rails 5.1 to 5.2
It got solved with:

spring stop
spring binstub --all
spring start
rails s

Python list subtraction operation

Use set difference

>>> z = list(set(x) - set(y))
>>> z
[0, 8, 2, 4, 6]

Or you might just have x and y be sets so you don't have to do any conversions.

What is newline character -- '\n'

sed can be put into multi-line search & replace mode to match newline characters \n.

To do so sed first has to read the entire file or string into the hold buffer ("hold space") so that it then can treat the file or string contents as a single line in "pattern space".

To replace a single newline portably (with respect to GNU and FreeBSD sed) you can use an escaped "real" newline.

# cf. http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
echo 'California
Massachusetts
Arizona' | 
sed -n -e '
# if the first line copy the pattern to the hold buffer
1h
# if not the first line then append the pattern to the hold buffer
1!H
# if the last line then ...
$ {
# copy from the hold to the pattern buffer
g
# double newlines
s/\n/\
\
/g
s/$/\
/
p
}'

# output
# California
#
# Massachusetts
#
# Arizona
#

There is, however, a much more convenient was to achieve the same result:

echo 'California
Massachusetts
Arizona' | 
   sed G

How to change background Opacity when bootstrap modal is open

you could utilize bootstrap events:: as

//when modal opens
$('#yourModal').on('shown.bs.modal', function (e) {
  $("#pageContent").css({ opacity: 0.5 });
})

//when modal closes
$('#yourModal').on('hidden.bs.modal', function (e) {
  $("#pageContent").css({ opacity: 1 });
})

No such keg: /usr/local/Cellar/git

Os X Mojave 10.14 has:

Error: The Command Line Tools header package must be installed on Mojave.

Solution. Go to

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

location and install the package manually. And brew will start working and we can run:

brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git

How to not wrap contents of a div?

A combination of both float: left; white-space: nowrap; worked for me.

Each of them independently didn't accomplish the desired result.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.

EDIT::

I am thinking of

int &x = y;

as almost equivalent of

int* __px = &y;
#define x (*__px)

where __px is a fresh name, and the #define x works only inside the block containing the declaration of x reference.

FileProvider - IllegalArgumentException: Failed to find configured root

What I did to solve this -

AndroidManifest.xml

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.mydomain.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"/>
        </provider>

filepaths.xml (Allowing the FileProvider to share all the files that are inside the app's external files directory)

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="files"
        path="/" />
</paths>

and in java class -

Uri fileProvider = FileProvider.getUriForFile(getContext(),"com.mydomain.fileprovider",newFile);

Object comparison in JavaScript

If you work without the JSON library, maybe this will help you out:

Object.prototype.equals = function(b) {
    var a = this;
    for(i in a) {
        if(typeof b[i] == 'undefined') {
            return false;
        }
        if(typeof b[i] == 'object') {
            if(!b[i].equals(a[i])) {
                return false;
            }
        }
        if(b[i] != a[i]) {
            return false;
        }
    }
    for(i in b) {
        if(typeof a[i] == 'undefined') {
            return false;
        }
        if(typeof a[i] == 'object') {
            if(!a[i].equals(b[i])) {
                return false;
            }
        }
        if(a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false

How to trim whitespace from a Bash variable?

I've seen scripts just use variable assignment to do the job:

$ xyz=`echo -e 'foo \n bar'`
$ echo $xyz
foo bar

Whitespace is automatically coalesced and trimmed. One has to be careful of shell metacharacters (potential injection risk).

I would also recommend always double-quoting variable substitutions in shell conditionals:

if [ -n "$var" ]; then

since something like a -o or other content in the variable could amend your test arguments.

Saving numpy array to txt file row wise

The numpy.savetxt() method has several parameters which are worth noting:

fmt : str or sequence of strs, optional
    it is used to format the numbers in the array, see the doc for details on formating

delimiter : str, optional
    String or character separating columns

newline : str, optional
    String or character separating lines.

Let's take an example. I have an array of size (M, N), which consists of integer numbers in the range (0, 255). To save the array row-wise and show it nicely, we can use the following code:

import numpy as np

np.savetxt("my_array.txt", my_array, fmt="%4d", delimiter=",", newline="\n")

Creating a random string with A-Z and 0-9 in Java

You can easily do that with a for loop,

public static void main(String[] args) {
  String aToZ="ABCD.....1234"; // 36 letter.
  String randomStr=generateRandom(aToZ);

}

private static String generateRandom(String aToZ) {
    Random rand=new Random();
    StringBuilder res=new StringBuilder();
    for (int i = 0; i < 17; i++) {
       int randIndex=rand.nextInt(aToZ.length()); 
       res.append(aToZ.charAt(randIndex));            
    }
    return res.toString();
}

How to make java delay for a few seconds?

Use Thread.sleep(2000); //2000 for 2 seconds

Error on renaming database in SQL Server 2008 R2

1.database set 1st single user mode

ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE

2.RENAME THE DATABASE

ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]

3.DATABAE SET MULIUSER MODE

ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER WITH ROLLBACK IMMEDIATE

In JavaScript can I make a "click" event fire programmatically for a file input element?

$(document).one('mousemove', function() { $(element).trigger('click') } );

Worked for me when I ran into similar problem, it's a regular eRube Goldberg.

Is there a JavaScript function that can pad a string to get to a determined length?

String.prototype.padLeft = function(pad) {
        var s = Array.apply(null, Array(pad)).map(function() { return "0"; }).join('') + this;
        return s.slice(-1 * Math.max(this.length, pad));
    };

usage:

  1. "123".padLeft(2) returns: "123"
  2. "12".padLeft(2) returns: "12"
  3. "1".padLeft(2) returns: "01"

How to detect Adblock on my website?

Just created my own "plugin" for solving this and it works really well:

adBuddy + jsBuddy:

ADBuddy JSBuddy GitHub

I added mobile compatibility and jsBlocking detection among other things... (Like an overlay that is shown to the users asking them to disable the adBlocking/jsBlocking software); Also made it responsive friendly.

It's opensourced under the Coffeeware License.

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Reverse HashMap keys and values in Java

They all are unique, yes

If you're sure that your values are unique you can iterate over the entries of your old map .

Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
    myNewHashMap.put(entry.getValue(), entry.getKey());
}

Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse() method :

BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");

BiMap<String, Character> myBiMapInversed = myBiMap.inverse();

As is out, you can also do it this way :

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, String> mapInversed = 
    map.entrySet()
       .stream()
       .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))

Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:

Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();

What is the easiest way to get the current day of the week in Android?

Use the Java Calendar class.

Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK); 

switch (day) {
    case Calendar.SUNDAY:
        // Current day is Sunday
        break;
    case Calendar.MONDAY:
        // Current day is Monday
        break;
    case Calendar.TUESDAY:
        // etc.
        break;
}

Remove HTML Tags from an NSString on the iPhone

I've extended the answer by m.kocikowski and tried to make it a bit more efficient by using an NSMutableString. I've also structured it for use in a static Utils class (I know a Category is probably the best design though), and removed the autorelease so it compiles in an ARC project.

Included here in case anybody finds it useful.

.h

+ (NSString *)stringByStrippingHTML:(NSString *)inputString;

.m

+ (NSString *)stringByStrippingHTML:(NSString *)inputString 
{
  NSMutableString *outString;

  if (inputString)
  {
    outString = [[NSMutableString alloc] initWithString:inputString];

    if ([inputString length] > 0)
    {
      NSRange r;

      while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
      {
        [outString deleteCharactersInRange:r];
      }      
    }
  }

  return outString; 
}

What is the equivalent of "none" in django templates?

You could try this:

{% if not profile.user.first_name.value %}
  <p> -- </p>
{% else %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}

This way, you're essentially checking to see if the form field first_name has any value associated with it. See {{ field.value }} in Looping over the form's fields in Django Documentation.

I'm using Django 3.0.

How to convert all tables from MyISAM into InnoDB?

Try this shell script

DBENGINE='InnoDB' ;
DBUSER='your_db_user' ;
DBNAME='your_db_name' ;
DBHOST='your_db_host'
DBPASS='your_db_pass' ;
mysqldump --add-drop-table -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME > mtest.sql; mysql -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME -Nse "SHOW TABLES;" | while read TABLE ; do mysql -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME -Nse "ALTER TABLE $TABLE ENGINE=$DBENGINE;" ; done

Warning about `$HTTP_RAW_POST_DATA` being deprecated

I experienced the same issue on nginx server (DigitalOcean) - all I had to do is to log in as root and modify the file /etc/php5/fpm/php.ini.

To find the line with the always_populate_raw_post_data I first run grep:

grep -n 'always_populate_raw_post_data' php.ini

That returned the line 704

704:;always_populate_raw_post_data = -1

Then simply open php.ini on that line with vi editor:

vi +704 php.ini

Remove the semi colon to uncomment it and save the file :wq

Lastly reboot the server and the error went away.

Hibernate Group by Criteria Object

You can use the approach @Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:

    session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));

List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

Letter Count on a string

You have a number of problems:

  • There's a problem with your indentation as others already pointed out.
  • There's no need to have nested loops. Just one loop is enough.
  • You're using char to mean two different things, but the char variable in the for loop will overwrite the data from the parameter.

This code fixes all these errors:

def count_letters(word, char):
    count = 0
    for c in word:
        if char == c:
            count += 1
    return count

A much more concise way to write this is to use a generator expression:

def count_letters(word, char):
    return sum(char == c for c in word)

Or just use the built-in method count that does this for you:

print 'abcbac'.count('c')

"Line contains NULL byte" in CSV reader (Python)

Turning my linux environment into a clean complete UTF-8 environment made the trick for me. Try the following in your command line:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

Spark Dataframe distinguish columns with duplicated name

This is how we can join two Dataframes on same column names in PySpark.

df = df1.join(df2, ['col1','col2','col3'])

If you do printSchema() after this then you can see that duplicate columns have been removed.

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

Version 1.3.0 has flaw IMO.
Downgrade to version 1.2.3 fixes my problem.

I'm on

  • Laravel 5.1
  • PHP 5.6.40

Downgrade to Version 1.2.3

How can I get a resource content from a static context?

Shortcut

I use App.getRes() instead of App.getContext().getResources() (as @Cristian answered)

It is very simple to use anywhere in your code!

So here is a unique solution by which you can access resources from anywhere like Util class .

(1) Create or Edit your Application class.

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getRes() {
        return res;
    }

}

(2) Add name field to your manifest.xml <application tag. (or Skip this if already there)

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go.

Use App.getRes().getString(R.string.some_id) anywhere in code.

How to make an Android device vibrate? with different frequency?

Grant Vibration Permission

Before you start implementing any vibration code, you have to give your application the permission to vibrate:

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

Make sure to include this line in your AndroidManifest.xml file.

Import the Vibration Library

Most IDEs will do this for you, but here is the import statement if yours doesn't:

 import android.os.Vibrator;

Make sure this in the activity where you want the vibration to occur.

How to Vibrate for a Given Time

In most circumstances, you'll be wanting to vibrate the device for a short, predetermined amount of time. You can achieve this by using the vibrate(long milliseconds) method. Here is a quick example:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 400 milliseconds
v.vibrate(400);

That's it, simple!

How to Vibrate Indefinitely

It may be the case that you want the device to continue vibrating indefinitely. For this, we use the vibrate(long[] pattern, int repeat) method:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};

// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, 0);

When you're ready to stop the vibration, just call the cancel() method:

v.cancel();

How to use Vibration Patterns

If you want a more bespoke vibration, you can attempt to create your own vibration patterns:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start without a delay
// Each element then alternates between vibrate, sleep, vibrate, sleep...
long[] pattern = {0, 100, 1000, 300, 200, 100, 500, 200, 100};

// The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
v.vibrate(pattern, -1);

More Complex Vibrations

There are multiple SDKs that offer a more comprehensive range of haptic feedback. One that I use for special effects is Immersion's Haptic Development Platform for Android.

Troubleshooting

If your device won't vibrate, first make sure that it can vibrate:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Output yes if can vibrate, no otherwise
if (v.hasVibrator()) {
    Log.v("Can Vibrate", "YES");
} else {
    Log.v("Can Vibrate", "NO");
}

Secondly, please ensure that you've given your application the permission to vibrate! Refer back to the first point.

Slack clean all messages (~8K) in a channel

Here is a great chrome extension to bulk delete your slack channel/group/im messages - https://slackext.com/deleter , where you can filter the messages by star, time range, or users. BTW, it also supports load all messages in recent version, then you can load your ~8k messages as you need.

Setting custom UITableViewCells height

Thanks to all the posts on this topic, there are some really helpful ways to adjust the rowHeight of a UITableViewCell.

Here is a compilation of some of the concepts from everyone else that really helps when building for the iPhone and iPad. You can also access different sections and adjust them according to the varying sizes of views.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 16;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 20;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
else
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 24;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 40;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
return 0;
} 

An "and" operator for an "if" statement in Bash

Try this:

if [ $STATUS -ne 200 -a "$STRING" != "$VALUE" ]; then

How can I use interface as a C# generic type constraint?

To follow up on Robert's answer, this is even later, but you can use a static helper class to make the runtime check once only per type:

public bool Foo<T>() where T : class
{
    FooHelper<T>.Foo();
}

private static class FooHelper<TInterface> where TInterface : class
{
    static FooHelper()
    {
        if (!typeof(TInterface).IsInterface)
            throw // ... some exception
    }
    public static void Foo() { /*...*/ }
}

I also note that your "should work" solution does not, in fact, work. Consider:

public bool Foo<T>() where T : IBase;
public interface IBase { }
public interface IActual : IBase { string S { get; } }
public class Actual : IActual { public string S { get; set; } }

Now there's nothing stopping you from calling Foo thus:

Foo<Actual>();

The Actual class, after all, satisfies the IBase constraint.

Can I pass a JavaScript variable to another browser window?

Passing variables between the windows (if your windows are on the same domain) can be easily done via:

  1. Cookies
  2. localStorage. Just make sure your browser supports localStorage, and do the variable maintenance right (add/delete/remove) to keep localStorage clean.

Update multiple values in a single statement

Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:

update 
    MasterTbl
set
    TotalX = Sum(DetailTbl.X),
    TotalY = Sum(DetailTbl.Y),
    TotalZ = Sum(DetailTbl.Z)
from
    DetailTbl
where
    DetailTbl.MasterID = MasterID

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

Who sets response content-type in Spring MVC (@ResponseBody)

Note that in Spring MVC 3.1 you can use the MVC namespace to configure message converters:

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

Or code-based configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  private static final Charset UTF8 = Charset.forName("UTF-8");

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
    converters.add(stringConverter);

    // Add other converters ...
  }
}

Python in Xcode 4+?

Procedure to get Python Working in XCode 7

Step 1: Setup your Project with a External Build System

enter image description here

Step 1.1: Edit the Project Scheme

enter image description here

Step 2: Specify Python as the executable for the project (shift-command-g) the path should be /usr/bin/python

enter image description here

Step 3: Specify your custom working directory

enter image description here

Step 4: Specify your command line arguments to be the name of your python file. (in this example "test.py")

enter image description here

enter image description here

Step 5: Thankfully thats it!

(debugging can't be added until OSX supports a python debugger?)

How to generate access token using refresh token through google drive API?

If you using Java then follow below code snippet :

GoogleCredential refreshTokenCredential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setRefreshToken(yourOldToken);
refreshTokenCredential.refreshToken(); //do not forget to call this
String newAccessToken = refreshTokenCredential.getAccessToken();

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

Comparing HTTP and FTP for transferring files

Both of them uses TCP as a transport protocol, but HTTP uses a persistent connection, which makes the performance of the TCP better.

Call external javascript functions from java code

try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }

How to load local file in sc.textFile, instead of HDFS

This has happened to me with Spark 2.3 with Hadoop also installed under the common "hadoop" user home directory.Since both Spark and Hadoop was installed under the same common directory, Spark by default considers the scheme as hdfs, and starts looking for the input files under hdfs as specified by fs.defaultFS in Hadoop's core-site.xml. Under such cases, we need to explicitly specify the scheme as file:///<absoloute path to file>.

Check which element has been clicked with jQuery

Hope this useful for you.

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});

Python pip install module is not found. How to link python to pip location?

I also had this problem. I noticed that all of the subdirectories and files under /usr/local/lib/python2.7/dist-packages/ had no read or write permission for group and other, and they were owned by root. This means that only the root user could access them, and so any user that tried to run a Python script that used any of these modules got an import error:

$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named selenium
>>> 

I granted read permission on the files and search permission on the subdirectories for group and other like so:

$ sudo chmod -R go+rX /usr/local/lib/python2.7/dist-packages

And that resolved the problem for me:

$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
>>> 

I installed these packages with pip (run as root with sudo). I am not sure why it installed them without granting read/search permissions. This seems like a bug in pip to me, or possibly in the package configuration, but I am not very familiar with Python and its module packaging, so I don't know for sure. FWIW, all packages under dist-packages had this issue. Anyhow, hope that helps.

Regards.

Can we instantiate an abstract class?

Extending a class doesn't mean that you are instantiating the class. Actually, in your case you are creating an instance of the subclass.

I am pretty sure that abstract classes do not allow initiating. So, I'd say no: you can't instantiate an abstract class. But, you can extend it / inherit it.

You can't directly instantiate an abstract class. But it doesn't mean that you can't get an instance of class (not actully an instance of original abstract class) indirectly. I mean you can not instantiate the orginial abstract class, but you can:

  1. Create an empty class
  2. Inherit it from abstract class
  3. Instantiate the dervied class

So you get access to all the methods and properties in an abstract class via the derived class instance.

RegEx for valid international mobile phone number

After stripping all characters except '+' and digits from your input, this should do it:

^\+[1-9]{1}[0-9]{3,14}$

If you want to be more exact with the country codes see this question on List of phone number country codes

However, I would try to be not too strict with my validation. Users get very frustrated if they are told their valid numbers are not acceptable.

Count the number of Occurrences of a Word in a String

I've got another approach here:

String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";

// Split description using "hello", which will return 
//string array of words other than hello
String[] words = description.split("hello");

// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
    lengthOfNonMatchingWords += word.length();
}

// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " + 
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());

Error "can't load package: package my_prog: found packages my_prog and main"

Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

Using group by on two fields and count in SQL

I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

This is how, I have been using a random user agent from a list of nearlly 1000 fake user agents

from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, OperatingSystem
software_names = [SoftwareName.ANDROID.value]
operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value, OperatingSystem.MAC.value]   

user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=1000)

# Get list of user agents.
user_agents = user_agent_rotator.get_user_agents()

user_agent_random = user_agent_rotator.get_random_user_agent()

Example

print(user_agent_random)

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36

For more details visit this link

How may I sort a list alphabetically using jQuery?

improvement based on Jeetendra Chauhan's answer

$('ul.menu').each(function(){
    $(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
});

why i consider it an improvement:

  1. using each to support running on more than one ul

  2. using children('li') instead of ('ul li') is important because we only want to process direct children and not descendants

  3. using the arrow function (a,b)=> just looks better (IE not supported)

  4. using vanilla innerText instead of $(a).text() for speed improvement

  5. using vanilla localeCompare improves speed in case of equal elements (rare in real life usage)

  6. using appendTo(this) instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

How to stick text to the bottom of the page?

This is how I've done it.

_x000D_
_x000D_
#copyright {_x000D_
 float: left;_x000D_
 padding-bottom: 10px;_x000D_
 padding-top: 10px;_x000D_
 text-align: center;_x000D_
 bottom: 0px;_x000D_
 width: 100%;_x000D_
}
_x000D_
  <div id="copyright">_x000D_
  Copyright 2018 &copy; Steven Clough_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Are loops really faster in reverse?

It can be explained by JavaScript (and all languages) eventually being turned into opcodes to run on the CPU. CPUs always have a single instruction for comparing against zero, which is damn fast.

As an aside, if you can guarantee count is always >= 0, you could simplify to:

for (var i = count; i--;)
{
  // whatever
}

How can I display just a portion of an image in HTML/CSS?

adjust the background-position to move background images in different positions of the div

div { 
       background-image: url('image url')
       background-position: 0 -250px; 
    }

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

multiple conditions for filter in spark data frames

Another way is to use function expr with where clause

import org.apache.spark.sql.functions.expr

df2 = df1.where(expr("col1 = 'value1' and col2 = 'value2'"))

It works the same.

Creating a static class with no instances

Seems that you need classmethod:

class World(object):

    allAirports = []

    @classmethod
    def initialize(cls):

        if not cls.allAirports:
            f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
            file_reader = csv.reader(f)

            for col in file_reader:
                cls.allAirports.append(Airport(col[0],col[2],col[3]))

        return cls.allAirports

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

std::string length() and size() member functions

As per the documentation, these are just synonyms. size() is there to be consistent with other STL containers (like vector, map, etc.) and length() is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length() is there to make things more readable.

How to write to Console.Out during execution of an MSTest test

The Console output is not appearing is because the backend code is not running in the context of the test.

You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.

This topic from MSDN shows a way of doing this.


According to Marty Neal's and Dave Anderson's comments:

using System;
using System.Diagnostics;

...

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

How to convert map to url query string?

You can use a Stream for this, but instead of appending query parameters myself I'd use a Uri.Builder. For example:

final Map<String, String> map = new HashMap<>();
map.put("param1", "cat");
map.put("param2", "12");

final Uri uri = 
    map.entrySet().stream().collect(
        () -> Uri.parse("relativeUrl").buildUpon(),
        (builder, e) -> builder.appendQueryParameter(e.getKey(), e.getValue()),
        (b1, b2) -> { throw new UnsupportedOperationException(); }
    ).build();

//Or, if you consider it more readable...
final Uri.Builder builder = Uri.parse("relativeUrl").buildUpon();
map.entrySet().forEach(e -> builder.appendQueryParameter(e.getKey(), e.getValue())
final Uri uri = builder.build();

//...    

assertEquals(Uri.parse("relativeUrl?param1=cat&param2=12"), uri);

How do I make the first letter of a string uppercase in JavaScript?

I would just use a regular expression:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

Modifying local variable from inside lambda

I had a slightly different problem. Instead of incrementing a local variable in the forEach, I needed to assign an object to the local variable.

I solved this by defining a private inner domain class that wraps both the list I want to iterate over (countryList) and the output I hope to get from that list (foundCountry). Then using Java 8 "forEach", I iterate over the list field, and when the object I want is found, I assign that object to the output field. So this assigns a value to a field of the local variable, not changing the local variable itself. I believe that since the local variable itself is not changed, the compiler doesn't complain. I can then use the value that I captured in the output field, outside of the list.

Domain Object:

public class Country {

    private int id;
    private String countryName;

    public Country(int id, String countryName){
        this.id = id;
        this.countryName = countryName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Wrapper object:

private class CountryFound{
    private final List<Country> countryList;
    private Country foundCountry;
    public CountryFound(List<Country> countryList, Country foundCountry){
        this.countryList = countryList;
        this.foundCountry = foundCountry;
    }
    public List<Country> getCountryList() {
        return countryList;
    }
    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }
    public Country getFoundCountry() {
        return foundCountry;
    }
    public void setFoundCountry(Country foundCountry) {
        this.foundCountry = foundCountry;
    }
}

Iterate operation:

int id = 5;
CountryFound countryFound = new CountryFound(countryList, null);
countryFound.getCountryList().forEach(c -> {
    if(c.getId() == id){
        countryFound.setFoundCountry(c);
    }
});
System.out.println("Country found: " + countryFound.getFoundCountry().getCountryName());

You could remove the wrapper class method "setCountryList()" and make the field "countryList" final, but I did not get compilation errors leaving these details as-is.

How to copy data from one table to another new table in MySQL?

If you don't want to list the fields, and the structure of the tables is the same, you can do:

INSERT INTO `table2` SELECT * FROM `table1`;

or if you want to create a new table with the same structure:

CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl;

Reference for insert select; Reference for create table select

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

I'm using a popup to show the map in a new window. I'm using the following url

https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE

HTML snippet

<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>

How can I check if a string is a number?

If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.

string num = "123x";

foreach (char c in num.ToArray())
{
    if (!Char.IsDigit(c))
    {
        Console.WriteLine("character " + c + " is not a number");
        return;
    }
}

Check whether an array is empty

<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>

restart mysql server on windows 7

Open the command prompt and enter the following commands:

net stop MySQL   
net start MySQL

the MySQL service name maybe changes based on the version you installed. In my situation, MySQL version is MySQL Server 5.7. So I use the following command

net stop MySQL57   
net start MySQL57

How to find a parent with a known class in jQuery?

Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.

$(this).parent().closest('.a');

Thanks

test if event handler is bound to an element in jQuery

I wrote a plugin called hasEventListener which exactly does that :

http://github.com/sebastien-p/jquery.hasEventListener

Hope this helps.

What's the most efficient way to check if a record exists in Oracle?

The most efficient and safest way to determine if a row exists is by using a FOR-LOOP... You won't even have a difficult time if you are looking to insert a row or do something based on the row NOT being there but, this will certainly help you if you need to determine if a row exists. See example code below for the ins and outs...

If you are only interested in knowing that 1 record exists in your potential multiple return set, than you can exit your loop after it hits it for the first time.

The loop will not be entered into at all if no record exists. You will not get any complaints from Oracle or such if the row does not exist but you are bound to find out if it does regardless. Its what I use 90% of the time (of course dependent on my needs)...

EXAMPLE:

DECLARE

v_exist varchar2(20);

BEGIN
   FOR rec IN
   (SELECT LOT, COMPONENT 
   FROM TABLE
   WHERE REF_DES = (SELECT REF_DES FROM TABLE2 WHERE ORDER = '1234') 
   AND ORDER = '1234')
  LOOP

      v_exist := "IT_EXISTS"

   INSERT INTO EAT_SOME_SOUP_TABLE (LOT, COMPONENT) 
   VALUES (rec.LOT, rec.COMPONENT);**

   --Since I don't want to do this for more than one iteration (just in case there may have been more than one record returned, I will EXIT;

   EXIT;
   END LOOP;



IF v_exist  IS NULL

    THEN

            --do this

END IF;

END;

--This is outside the loop right here The IF-CHECK just above will run regardless, but then you will know if your variable is null or not right!?. If there was NO records returned, it will skip the loop and just go here to the code you would have next... If (in our case above), 4 records were returned, I would exit after the first iteration due to my EXIT;... If that wasn't there, the 4 records would iterate through and do an insert on all of them. Or at least try too.

By the way, I'm not saying this is the only way you should consider doing this... You can

SELECT COUNT(*) INTO v_counter WHERE ******* etc...

Then check it like

if v_counter > 0
      THEN
         --code goes here
   END IF;

There are more ways... Just determine it when your need arises. Keep performance in mind, and safety.

iPhone UITextField - Change placeholder text color

You can Change the Placeholder textcolor to any color which you want by using the below code.

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];

BackgroundWorker vs background Thread

You know, sometimes it's just easier to work with a BackgroundWorker regardless of if you're using Windows Forms, WPF or whatever technology. The neat part about these guys is you get threading without having to worry too much about where you're thread is executing, which is great for simple tasks.

Before using a BackgroundWorker consider first if you wish to cancel a thread (closing app, user cancellation) then you need to decide if your thread should check for cancellations or if it should be thrust upon the execution itself.

BackgroundWorker.CancelAsync() will set CancellationPending to true but won't do anything more, it's then the threads responsibility to continually check this, keep in mind also that you could end up with a race condition in this approach where your user cancelled, but the thread completed prior to testing for CancellationPending.

Thread.Abort() on the other hand will throw an exception within the thread execution which enforces cancellation of that thread, you must be careful about what might be dangerous if this exception was suddenly raised within the execution though.

Threading needs very careful consideration no matter what the task, for some further reading:

Parallel Programming in the .NET Framework Managed Threading Best Practices

html script src="" triggering redirection with button

your folder name is scripts..

and you are Referencing it like ../script/login.js

Also make sure that script folder is in your project directory

Thanks

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

Faced same issue, my understanding is(it could be wrong)
1. Make sure mongodb is up and running
2. For linux access as sudo and for windows if connecting localhost turning off firewall may help but its not necessary
3. Just type mongo, it will try to connect to localhost by default. You need to specify IP if you are connecting to a remote server. By default test db will be used.

How to vertically align text in input type="text"?

Put it in a div tag seems to be the only way to FORCE that:

<div style="vertical-align: middle"><div><input ... /></div></div>

May be other tags like span works as like div do.

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

What does "restore purchases" in In-App purchases mean?

You typically restore purchases with this code:

[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

Not all types of In-App purchases can be restored.

Div show/hide media query

It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

http://www.w3schools.com/css/css_rwd_viewport.asp

Typescript ReferenceError: exports is not defined

If you are just using interfaces for types, leave out the export keyword and ts can pick up on the types without needing to import. They key is you cannot use import/export anywhere.

export interface Person {
   name: string;
   age: number;
}

into

interface Person {
   name: string;
   age: number;
}

Differences between "java -cp" and "java -jar"?

There won't be any difference in terms of performance. Using java - cp we can specify the required classes and jar's in the classpath for running a java class file.

If it is a executable jar file . When java -jar command is used, jvm finds the class that it needs to run from /META-INF/MANIFEST.MF file inside the jar file.

How to cache data in a MVC application

I will say implementing Singleton on this persisting data issue can be a solution for this matter in case you find previous solutions much complicated

 public class GPDataDictionary
{
    private Dictionary<string, object> configDictionary = new Dictionary<string, object>();

    /// <summary>
    /// Configuration values dictionary
    /// </summary>
    public Dictionary<string, object> ConfigDictionary
    {
        get { return configDictionary; }
    }

    private static GPDataDictionary instance;
    public static GPDataDictionary Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GPDataDictionary();
            }
            return instance;
        }
    }

    // private constructor
    private GPDataDictionary() { }

}  // singleton

Insert into a MySQL table or update if exists

When using batch insert use the following syntax:

INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
    name = VALUES (name),
    ...

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

I just ran into this and I was running under Release build configuration instead of Debug build configuration. Once I switched back to Debug my variable showed in the watch again.