Programs & Examples On #Contentobserver

Receives call backs for changes to content. Must be implemented by objects which are added to a ContentObservable.

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

To send an mms for Android 4.0 api 14 or higher without permission to write apn settings, you can use this library: Retrieve mnc and mcc codes from android, then call

Carrier c = Carrier.getCarrier(mcc, mnc);
if (c != null) {
    APN a = c.getAPN();
    if (a != null) {
        String mmsc = a.mmsc;
        String mmsproxy = a.proxy; //"" if none
        int mmsport = a.port; //0 if none
    }
}

To use this, add Jsoup and droid prism jar to the build path, and import com.droidprism.*;

Check if $_POST exists

I would like to add my answer even though this thread is years old and it ranked high in Google for me.

My best method is to try:

if(sizeof($_POST) !== 0){
// Code...
}

As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.

You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.

$_POST always exists in itself being either empty or has array values. $_POST['value'] may not exist, thus throwing an "undefined index" error.

How do I migrate an SVN repository with history to a new Git repository?

For GitLab users I've put up a gist on how I migrated from SVN here:

https://gist.github.com/leftclickben/322b7a3042cbe97ed2af

Steps to migrate from SVN to GitLab

Setup

  • SVN is hosted at svn.domain.com.au.
  • SVN is accessible via http (other protocols should work).
  • GitLab is hosted at git.domain.com.au and:
    • A group is created with the namespace dev-team.
    • At least one user account is created, added to the group, and has an SSH key for the account being used for the migration (test using ssh [email protected]).
    • The project favourite-project is created in the dev-team namespace.
  • The file users.txt contains the relevant user details, one user per line, of the form username = First Last <[email protected]>, where username is the username given in SVN logs. (See first link in References section for details, in particular answer by user Casey).

Versions

  • subversion version 1.6.17 (r1128011)
  • git version 1.9.1
  • GitLab version 7.2.1 ff1633f
  • Ubuntu server 14.04

Commands

bash
git svn clone --stdlayout --no-metadata -A users.txt 
http://svn.domain.com.au/svn/repository/favourite-project
cd favourite-project
git remote add gitlab [email protected]:dev-team/favourite-project.git
git push --set-upstream gitlab master

That's it! Reload the project page in GitLab web UI and you will see all commits and files now listed.

Notes

  • If there are unknown users, the git svn clone command will stop, in which case, update users.txt, cd favourite-project and git svn fetch will continue from where it stopped.
  • The standard trunk-tags-branches layout for SVN repository is required.
  • The SVN URL given to the git svn clone command stops at the level immediately above trunk/, tags/ and branches/.
  • The git svn clone command produces a lot of output, including some warnings at the top; I ignored the warnings.

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

How can I wrap or break long text/word in a fixed width span?

Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.

By defining the the full span as display:inline-block you might have a hard time displaying images.

Therefore I prefer to define a span like so:

span {
  display:block;
  width:150px;
  word-wrap:break-word;      
}
p span, a span,
h1 span, h2 span, h3 span, h4 span, h5 span {
  display:inline-block;
}
img{
  display:block;
}

Swift - Split string over multiple lines

I used an extension on String to achieve multiline strings while avoiding the compiler hanging bug. It also allows you to specify a separator so you can use it a bit like Python's join function

extension String {
    init(sep:String, _ lines:String...){
        self = ""
        for (idx, item) in lines.enumerated() {
            self += "\(item)"
            if idx < lines.count-1 {
                self += sep
            }
        }
    }

    init(_ lines:String...){
        self = ""
        for (idx, item) in lines.enumerated() {
            self += "\(item)"
            if idx < lines.count-1 {
                self += "\n"
            }
        }
    }
}



print(
    String(
        "Hello",
        "World!"
    )
)
"Hello
World!"

print(
    String(sep:", ",
        "Hello",
        "World!"
    )
)
"Hello, World!"

"Exception has been thrown by the target of an invocation" error (mscorlib)

I just had this issue from a namespace mismatch. My XAML file was getting ported over and it had a different namespace from that in the code behind file.

Execute bash script from URL

Try just:

bash <(curl -s http://mywebsite.com/myscript.txt)

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

WorksheetFunction.CountA - not working post upgrade to Office 2010

This answer from another forum solved the problem.

(substitute your own range for the "I:I" shown here)

Re: CountA not working in VBA

Should be:

Nonblank = Application.WorksheetFunction.CountA(Range("I:I"))

You have to refer to ranges in the vba format, not the in-excel format.

How to use Select2 with JSON via Ajax request?

for select2 v4.0.0 slightly different

$(".itemSearch").select2({
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    ajax: {
        url: URL,
        dataType: "json",
        type: "GET",
        data: function (params) {

            var queryParameters = {
                term: params.term
            }
            return queryParameters;
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    }
});

How can I pipe stderr, and not stdout?

For those who want to redirect stdout and stderr permanently to files, grep on stderr, but keep the stdout to write messages to a tty:

# save tty-stdout to fd 3
exec 3>&1
# switch stdout and stderr, grep (-v) stderr for nasty messages and append to files
exec 2> >(grep -v "nasty_msg" >> std.err) >> std.out
# goes to the std.out
echo "my first message" >&1
# goes to the std.err
echo "a error message" >&2
# goes nowhere
echo "this nasty_msg won't appear anywhere" >&2
# goes to the tty
echo "a message on the terminal" >&3

FlutterError: Unable to load asset

After declaring correctly in pubspec.yaml, consider giving full path of the image ex.

'assets/images/about_us.png' 

instead of just images/..

worked for me after wasting 2 hours on such a trivial error.

What is Cache-Control: private?

Cache-Control: private

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache, such as a proxy server.

From RFC2616 section 14.9.1

HTML5 iFrame Seamless Attribute

You only need to write

seamless

in your code. There is not need for:

seamless ="seamless"

I just found this out myself.

EDIT - this does not remove scrollbars. Strangely

scrolling="no" still seems to work in html5. I have tried using the overflow function with an inline style as recommended by html5 but this doesn't work for me.

SQL Server - find nth occurrence in a string

Inspired by Alex K's reply One way (2k8), I have created a script for a Token Function for the SQL Server for returning a specific token from a string. I needed this for refacturing a SSIS-package to T-SQL without having to implement Alex' solution a number of times manually. My function has one disadvantage: It returns the token value as a table (one column, one row) instead of as a varchar value. If anyone has a solution for this, please let me know.

DROP FUNCTION [RDW].[token]
GO

create function [RDW].[token] (@string varchar(8000), @split varchar(50), @returnIndex int) 
returns table  
as 
    return with T(img, starts, pos, [index]) as ( 
        select @string, 1, charindex(@split, @string), 0 
        union all 
        select @string, pos + 1, charindex(@split, @string, pos + 1), [index]+1 
        from t 
        where pos > 0
    )
    select substring(img, starts, case when pos > 0 then pos - starts else len(img) end) token
    from T
    where [index] = @returnIndex 
GO

pandas read_csv and filter columns with usecols

The solution lies in understanding these two keyword arguments:

  • names is only necessary when there is no header row in your file and you want to specify other arguments (such as usecols) using column names rather than integer indices.
  • usecols is supposed to provide a filter before reading the whole DataFrame into memory; if used properly, there should never be a need to delete columns after reading.

So because you have a header row, passing header=0 is sufficient and additionally passing names appears to be confusing pd.read_csv.

Removing names from the second call gives the desired output:

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        header=0,
        index_col=["date", "loc"], 
        usecols=["date", "loc", "x"],
        parse_dates=["date"])

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

C: printf a float value

You need to use %2.6f instead of %f in your printf statement

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

For me, running the ad-hoc network on Windows 8.1, it was two things:

  • I had to set a static IP on my Android (under Advanced Options under where you type the Wifi password)
  • I had to use a password 8 characters long

Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.

I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.

.includes() not working in Internet Explorer

Or just put this in a Javascript file and have a good day :)

String.prototype.includes = function (str) {
  var returnValue = false;

  if (this.indexOf(str) !== -1) {
    returnValue = true;
  }

  return returnValue;
}

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

What does the PHP error message "Notice: Use of undefined constant" mean?

You should quote your array keys:

$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);

As is, it was looking for constants called department, name, email, message, etc. When it doesn't find such a constant, PHP (bizarrely) interprets it as a string ('department', etc). Obviously, this can easily break if you do defined such a constant later (though it's bad style to have lower-case constants).

How to perform case-insensitive sorting in JavaScript?

If you want to guarantee the same order regardless of the order of elements in the input array, here is a stable sorting:

myArray.sort(function(a, b) {
    /* Storing case insensitive comparison */
    var comparison = a.toLowerCase().localeCompare(b.toLowerCase());
    /* If strings are equal in case insensitive comparison */
    if (comparison === 0) {
        /* Return case sensitive comparison instead */
        return a.localeCompare(b);
    }
    /* Otherwise return result */
    return comparison;
});

Array to Hash Ruby

Enumerator includes Enumerable. Since 2.1, Enumerable also has a method #to_h. That's why, we can write :-

a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}

Because #each_slice without block gives us Enumerator, and as per the above explanation, we can call the #to_h method on the Enumerator object.

Create a CSS rule / class with jQuery at runtime

Bit of a lazy answer this, but the following article may help: http://www.javascriptkit.com/dhtmltutors/externalcss3.shtml

Also, try typing "modify css rules" into google

Not sure whatwould happen if you tried to wrap a document.styleSheets[0] with jQuery() though you could give it a try

Preferred way of loading resources in Java

I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).

public class ResourceLoader {

    public static URL getResource(String resource) {
        final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
        classLoaders.add(Thread.currentThread().getContextClassLoader());
        classLoaders.add(ResourceLoader.class.getClassLoader());

        for (ClassLoader classLoader : classLoaders) {
            final URL url = getResourceWith(classLoader, resource);
            if (url != null) {
                return url;
            }
        }

        final URL systemResource = ClassLoader.getSystemResource(resource);
        if (systemResource != null) {
            return systemResource;
        } else {
            try {
                return new File(resource).toURI().toURL();
            } catch (MalformedURLException e) {
                return null;
            }
        }
    }

    private static URL getResourceWith(ClassLoader classLoader, String resource) {
        if (classLoader != null) {
            return classLoader.getResource(resource);
        }
        return null;
    }

}

How to download a file from a website in C#

You may need to know the status during the file download or use credentials before making the request.

Here is an example that covers these options:

Uri ur = new Uri("http://remotehost.do/images/img.jpg");

using (WebClient client = new WebClient()) {
    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

And the callback's functions implemented as follows:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

(Ver 2) - Lambda notation: other possible option for handling the events

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
});

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
    Console.WriteLine("Download finished!");
});

(Ver 3) - We can do better

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{
    Console.WriteLine("Download finished!");
};

(Ver 4) - Or

client.DownloadProgressChanged += (o, e) =>
{
    Console.WriteLine($"Download status: {e.ProgressPercentage}%.");

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (o, e) => 
{
    Console.WriteLine("Download finished!");
};

Android: How can I pass parameters to AsyncTask's onPreExecute()?

You can either pass the parameter in the task constructor or when you call execute:

AsyncTask<Object, Void, MyTaskResult>

The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).

public class MyActivity extends AppCompatActivity {

    TextView textView1;
    TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);    
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        String input1 = "test";
        boolean input2 = true;
        int input3 = 100;
        long input4 = 100000000;

        new MyTask(input3, input4).execute(input1, input2);
    }

    private class MyTaskResult {
        String text1;
        String text2;
    }

    private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
        private String val1;
        private boolean val2;
        private int val3;
        private long val4;


        public MyTask(int in3, long in4) {
            this.val3 = in3;
            this.val4 = in4;

            // Do something ...
        }

        protected void onPreExecute() {
            // Do something ...
        }

        @Override
        protected MyTaskResult doInBackground(Object... params) {
            MyTaskResult res = new MyTaskResult();
            val1 = (String) params[0];
            val2 = (boolean) params[1];

            //Do some lengthy operation    
            res.text1 = RunProc1(val1);
            res.text2 = RunProc2(val2);

            return res;
        }

        @Override
        protected void onPostExecute(MyTaskResult res) {
            textView1.setText(res.text1);
            textView2.setText(res.text2);

        }
    }

}

Hive query output to file

  1. Create an external table
  2. Insert data into the table
  3. Optional drop the table later, which wont delete that file since it is an external table

Example:

Creating external table to store the query results at '/user/myName/projectA_additionaData/'

CREATE EXTERNAL TABLE additionaData
(
     ID INT,
     latitude STRING,
     longitude STRING
)
COMMENT 'Additional Data gathered by joining of the identified cities with latitude and longitude data' 
ROW FORMAT DELIMITED FIELDS
TERMINATED BY ',' STORED AS TEXTFILE location '/user/myName/projectA_additionaData/';

Feeding the query results into the temp table

 insert into additionaData 
     Select T.ID, C.latitude, C.longitude 
     from TWITER  
     join CITY C on (T.location_name = C.location);

Dropping the temp table

drop table additionaData

Using iText to convert HTML to PDF

I think this is exactly what you were looking for

http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

http://code.google.com/p/flying-saucer

Flying Saucer's primary purpose is to render spec-compliant XHTML and CSS 2.1 to the screen as a Swing component. Though it was originally intended for embedding markup into desktop applications (things like the iTunes Music Store), Flying Saucer has been extended work with iText as well. This makes it very easy to render XHTML to PDFs, as well as to images and to the screen. Flying Saucer requires Java 1.4 or higher.

Using Chrome's Element Inspector in Print Preview Mode?

Note: This answer covers several versions of Chrome, scroll to see v52, v48, v46, v43 and v42 each with their updated changes.

Chrome v52+:

  • Open the Developer Tools (Windows: F12 or Ctrl+Shift+I, Mac: Cmd+Opt+I)
  • Click the Customize and control DevTools hamburger menu button and choose More tools > Rendering settings (or Rendering in newer versions).
  • Check the Emulate print media checkbox at the Rendering tab and select the Print media type.

Chrome v52+

Chrome v48+ (Thanks Alex for noticing):

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (CTRLSHIFTM).
  • Make sure the console is shown by clicking Show console in menu at (1) (ESC key toggles the console if Developer Toolbar has focus).
  • Check Emulate print media at the rendering tab which can be opened by selecting Rendering in menu at (2).

Chrome v48+

Chrome v46+:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the console is shown by clicking the menu button (2) > Show console (3) or pressing the ESC key to toggle the console (only works when Developer Toolbar has the focus).
  • Open the Emulation (4) > Media (5) tabs, check CSS media and select print (3).

Chrome v46+ support

Chrome v43+:

  • The drawer icon at step 2 has changed.

Emulate print media query on Chrome v43

Chrome v42:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the drawer is shown by clicking the Show drawer button (2) or pressing the ESC key to toggle the drawer.
  • Under Emulation > Media check CSS media and select print (3).

Emulate print media query on Chrome v42

jQuery Ajax requests are getting cancelled without being sent

I have had the same problem, for me I was creating the iframe for temporary manner and I was removing the iframe before the ajax become completes, so the browser would cancel my ajax request.

How can I save a base64-encoded image to disk?

Easy way to convert base64 image into file and save as some random id or name.

// to create some random id or name for your image name
const imgname = new Date().getTime().toString();

// to declare some path to store your converted image
const path = yourpath.png    

// image takes from body which you uploaded
const imgdata = req.body.image;    

// to convert base64 format into random filename
const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
fs.writeFile(path, base64Data, 'base64', (err) => {
    console.log(err);
});

// assigning converted image into your database
req.body.coverImage = imgname

Using custom fonts using CSS?

I am working on Win 8, use this code. It works for IE and FF, Opera, etc. What I understood are : woff font is light et common on Google fonts.

Go here to convert your ttf font to woff before.

@font-face
{
    font-family:'Open Sans';
    src:url('OpenSans-Regular.woff');
}

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

I fixed

avast deletes your server.php in your directory so disable the antivirus

check the (server.php) file on your laravel folder

server.php

_x000D_
_x000D_
<?php_x000D_
_x000D_
/**_x000D_
 * Laravel - A PHP Framework For Web Artisans_x000D_
 *_x000D_
 * @package  Laravel_x000D_
 * @author   Taylor Otwell <[email protected]>_x000D_
 */_x000D_
_x000D_
$uri = urldecode(_x000D_
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)_x000D_
);_x000D_
_x000D_
// This file allows us to emulate Apache's "mod_rewrite" functionality from the_x000D_
// built-in PHP web server. This provides a convenient way to test a Laravel_x000D_
// application without having installed a "real" web server software here._x000D_
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {_x000D_
    return false;_x000D_
}_x000D_
_x000D_
require_once __DIR__.'/public/index.php';
_x000D_
_x000D_
_x000D_

How to set image width to be 100% and height to be auto in react native?

Solution April 2020:

So the above answers are cute but they all have (imo) a big flaw: they are calculating the height of the image, based on the width of the user's device.

To have a truly responsive (i.e. width: 100%, height: auto) implementation, what you really want to be doing, is calculating the height of the image, based on the width of the parent container.

Luckily for us, React Native provides us with a way to get the parent container width, thanks to the onLayout View method.

So all we need to do is create a View with width: "100%", then use onLayout to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.

 

Just show me the code...

The below solution could be improved upon further, by using RN's Image.getSize, to grab the image dimensions within the ResponsiveImage component itself.

JavaScript:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import { Image, StyleSheet, View } from "react-native";

const ResponsiveImage = props => {
  const [containerWidth, setContainerWidth] = useState(0);
  const _onViewLayoutChange = event => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>

 

TypeScript:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import {
  Image,
  ImageSourcePropType,
  LayoutChangeEvent,
  StyleSheet,
  View
} from "react-native";

interface ResponsiveImageProps {
  src: ImageSourcePropType;
  srcWidth: number;
  srcHeight: number;
}

const ResponsiveImage: React.FC<ResponsiveImageProps> = props => {
  const [containerWidth, setContainerWidth] = useState<number>(0);
  const _onViewLayoutChange = (event: LayoutChangeEvent) => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>

Converting a string to a date in a cell

The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here

Switch statement multiple cases in JavaScript

My situation was something akin to:

switch (text) {
  case SOME_CONSTANT || ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT || FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}

The default case always entered. If you're running into a similar multi-case switch statement issue, you're looking for this:

switch (text) {
  case SOME_CONSTANT:
  case ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT:
  case FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}

How to work with progress indicator in flutter?

You can use FutureBuilder widget instead. This takes an argument which must be a Future. Then you can use a snapshot which is the state at the time being of the async call when loging in, once it ends the state of the async function return will be updated and the future builder will rebuild itself so you can then ask for the new state.

FutureBuilder(
  future:  myFutureFunction(),
  builder: (context, AsyncSnapshot<List<item>> snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: CircularProgressIndicator(),
      );
    } else {
     //Send the user to the next page.
  },
);

Here you have an example on how to build a Future

Future<void> myFutureFunction() async{
 await callToApi();}

How to compare 2 dataTables

The OP, MAW74656, originally posted this answer in the question body in response to the accepted answer, as explained in this comment:

I used this and wrote a public method to call the code and return the boolean.

The OP's answer:

Code Used:

public bool tablesAreTheSame(DataTable table1, DataTable table2)
{
    DataTable dt;
    dt = getDifferentRecords(table1, table2);

    if (dt.Rows.Count == 0)
        return true;
    else
        return false;
}

//Found at http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html
private DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
    //Create Empty Table     
    DataTable ResultDataTable = new DataTable("ResultDataTable");

    //use a Dataset to make use of a DataRelation object     
    using (DataSet ds = new DataSet())
    {
        //Add tables     
        ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });

        //Get Columns for DataRelation     
        DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
        for (int i = 0; i < firstColumns.Length; i++)
        {
            firstColumns[i] = ds.Tables[0].Columns[i];
        }

        DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
        for (int i = 0; i < secondColumns.Length; i++)
        {
            secondColumns[i] = ds.Tables[1].Columns[i];
        }

        //Create DataRelation     
        DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
        ds.Relations.Add(r1);

        DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
        ds.Relations.Add(r2);

        //Create columns for return table     
        for (int i = 0; i < FirstDataTable.Columns.Count; i++)
        {
            ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
        }

        //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.     
        ResultDataTable.BeginLoadData();
        foreach (DataRow parentrow in ds.Tables[0].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r1);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }

        //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.     
        foreach (DataRow parentrow in ds.Tables[1].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r2);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }
        ResultDataTable.EndLoadData();
    }

    return ResultDataTable;
}

Dictionary of dictionaries in Python?

If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:

def addNameToDictionary(d, tup):
    if tup[0] not in d:
        d[tup[0]] = {}
    d[tup[0]][tup[1]] = [tup[2]]

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Try this

Sub Sample()
    Dim test As Worksheet
    Sheets(1).Copy After:=Sheets(Sheets.Count)
    Set test = ActiveSheet
    test.Name = "copied sheet!"
End Sub

How to use export with Python on Linux

Not that simple:

python -c "import os; os.putenv('MY_DATA','1233')"
$ echo $MY_DATA # <- empty

But:

python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
$ echo $MY_DATA #<- 123

How to make connection to Postgres via Node.js

One solution can be using pool of clients like the following:

const { Pool } = require('pg');
var config = {
    user: 'foo', 
    database: 'my_db', 
    password: 'secret', 
    host: 'localhost', 
    port: 5432, 
    max: 10, // max number of clients in the pool
    idleTimeoutMillis: 30000
};
const pool = new Pool(config);
pool.on('error', function (err, client) {
    console.error('idle client error', err.message, err.stack);
});
pool.query('SELECT $1::int AS number', ['2'], function(err, res) {
    if(err) {
        return console.error('error running query', err);
    }
    console.log('number:', res.rows[0].number);
});

You can see more details on this resource.

How to run Tensorflow on CPU

Just using the code below.

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

Update just one gem with bundler

The way to do this is to run the following command:

bundle update --source gem-name

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

If you use ASP.NET and IISExpress go to "C:\Users\\Documents\IISExpress\config\applicationhost.config", search for your Project and look if you have a faulty virtualDirectory entry.

customize Android Facebook Login button

In order to have completely custom facebook login button without using com.facebook.widget.LoginButton.

According to facebook sdk 4.x,

There new concept of login as from facebook

LoginManager and AccessToken - These new classes perform Facebook Login

So, Now you can access Facebook authentication without Facebook login button as

layout.xml

    <Button
            android:id="@+id/btn_fb_login"
            .../>

MainActivity.java

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(this.getApplicationContext());

        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Log.d("Success", "Login");

                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

        setContentView(R.layout.activity_main);

        Button btn_fb_login = (Button)findViewById(R.id.btn_fb_login);

        btn_fb_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends"));
            }
        });

    }

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackManager.onActivityResult(requestCode, resultCode, data); 
}

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

You do realize this is the default behavior, right? if you add /something the results would be different.

you can do a number of things to prevent default behavior.

href="#":

Will do nothing but anchor - not the best solution since it may jump to page top.

<a href="#">

href="javascript:void(0);"

Will do nothing at all and is perfectly legit.

<a href="javascript:void(0);"></a>

href="your-actual-intended-link" (Best)

obviously the best.

<a href="<your-actual-intended-link>"></a>

If you don't want an a tag to go somewhere, why use an a tag at all?

Using underscores in Java variables and method names

Personally, I think a language shouldn't make rules about coding style. It is a matter of preferences, usage, convenience, concept about readability.
Now, a project must set coding rules, for consistency across listings. You might not agree with these rules, but you should stick to them if you want to contribute (or work in a team).

At least, IDEs like Eclispe are agnostic, allowing to set rules like variable prefixes or suffixes, various styles of brace placement and space management, etc. So you can use it to reformat code along your guidelines.

Note: I am among those keeping their old habits from C/C++, coding Java with m_ prefixes for member variables (and s_ for static ones), prefixing booleans with an initial b, using an initial uppercase letter for function names and aligning braces... The horror for Java fundamentalists! ;-)
Funnily, that's the conventions used where I work... probably because the main initial developer comes from MFC world! :-D

QString to char* conversion

The easiest way to convert a QString to char* is qPrintable(const QString& str), which is a macro expanding to str.toLocal8Bit().constData().

How do I invoke a Java method when given the method name as a string?

To complete my colleague's answers, You might want to pay close attention to:

  • static or instance calls (in one case, you do not need an instance of the class, in the other, you might need to rely on an existing default constructor that may or may not be there)
  • public or non-public method call (for the latter,you need to call setAccessible on the method within an doPrivileged block, other findbugs won't be happy)
  • encapsulating into one more manageable applicative exception if you want to throw back the numerous java system exceptions (hence the CCException in the code below)

Here is an old java1.4 code which takes into account those points:

/**
 * Allow for instance call, avoiding certain class circular dependencies. <br />
 * Calls even private method if java Security allows it.
 * @param aninstance instance on which method is invoked (if null, static call)
 * @param classname name of the class containing the method 
 * (can be null - ignored, actually - if instance if provided, must be provided if static call)
 * @param amethodname name of the method to invoke
 * @param parameterTypes array of Classes
 * @param parameters array of Object
 * @return resulting Object
 * @throws CCException if any problem
 */
public static Object reflectionCall(final Object aninstance, final String classname, final String amethodname, final Class[] parameterTypes, final Object[] parameters) throws CCException
{
    Object res;// = null;
    try {
        Class aclass;// = null;
        if(aninstance == null)
        {
            aclass = Class.forName(classname);
        }
        else
        {
            aclass = aninstance.getClass();
        }
        //Class[] parameterTypes = new Class[]{String[].class};
    final Method amethod = aclass.getDeclaredMethod(amethodname, parameterTypes);
        AccessController.doPrivileged(new PrivilegedAction() {
    public Object run() {
                amethod.setAccessible(true);
                return null; // nothing to return
            }
        });
        res = amethod.invoke(aninstance, parameters);
    } catch (final ClassNotFoundException e) {
        throw new CCException.Error(PROBLEM_TO_ACCESS+classname+CLASS, e);
    } catch (final SecurityException e) {
        throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_SECURITY_ISSUE, e);
    } catch (final NoSuchMethodException e) {
        throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_NOT_FOUND, e);
    } catch (final IllegalArgumentException e) {
        throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ILLEGAL_ARGUMENTS+String.valueOf(parameters)+GenericConstants.CLOSING_ROUND_BRACKET, e);
    } catch (final IllegalAccessException e) {
        throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ACCESS_RESTRICTION, e);
    } catch (final InvocationTargetException e) {
    throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_INVOCATION_ISSUE, e);
    } 
    return res;
}

How to roundup a number to the closest ten?

You could also use CEILING which rounds up to an integer or desired multiple of significance

ie
=CEILING(A1,10)
rounds up to a multiple of 10

12340.0001 will become 12350

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

How do I combine two lists into a dictionary in Python?

I don't know about best (simplest? fastest? most readable?), but one way would be:

dict(zip([1, 2, 3, 4], [a, b, c, d]))

Cannot read property 'getContext' of null, using canvas

Put your JavaScript code after your tag <canvas></canvas>

CSS hexadecimal RGBA?

Charming Prince:

Only internet explorer allows the 4 byte hex color in the format of ARGB, where A is the Alpha channel. It can be used in gradient filters for example:

filter  : ~"progid:DXImageTransform.Microsoft.Gradient(GradientType=@{dir},startColorstr=@{color1},endColorstr=@{color2})";

Where dir can be: 1(horizontal) or 0(vertical) And the color strings can be hex colors(#FFAAD3) or argb hex colors(#88FFAAD3).

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I have encountered this error on "an empty branch" on my local gitlab server. Some people mentioned that "you can not push for the first time on an empty branch". I tried to create a simple README file on the gitlab via my browser. Then everything fixed amazingly and the problem sorted out!! I mention that I was the master and the branch was not protected.

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

Most efficient T-SQL way to pad a varchar on the left to a certain length?

probably overkill, I often use this UDF:

CREATE FUNCTION [dbo].[f_pad_before](@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))
RETURNS VARCHAR(255) AS  
BEGIN

-- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
 RETURN ltrim(rtrim(
        CASE
          WHEN LEN(@string) < @desired_length
            THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string
          ELSE @string
        END
        ))
END

So that you can do things like:

select dbo.f_pad_before('aaa', 10, '_')

Vue equivalent of setTimeout?

use this.animationStop, not use this.animationStop ( )

animationRun(){
    this.sliderClass.anim = true;
    setTimeout(this.animationStop, 500);
},

Convert Unicode data to int in python

int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).

Do this instead:

limit = int(limit)

Or when definiting limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])

How to print multiple lines of text with Python

You can use triple quotes (single ' or double "):

a = """
text
text
text
"""

print(a)

Mailto links do nothing in Chrome but work in Firefox?

This is browser settings specific, i.e. it will behave differently depending on the user's browser settings. The user can change how mailto: links behave in chrome by visiting chrome://settings/handlers, or Chrome Settings->Content Settings->Manage Handlers...

If "email" is not listed on that page, then see this answer regarding how to proceed.

Get int from String, also containing letters, in Java

You can also use Scanner :

Scanner s = new Scanner(MyString);
s.nextInt();

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

IOS - How to segue programmatically using swift

You can do this thing using performSegueWithIdentifier function.

Screenshot

Syntax :

func performSegueWithIdentifier(identifier: String, sender: AnyObject?)

Example :

 performSegueWithIdentifier("homeScreenVC", sender: nil)

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

Creating and returning Observable from Angular 2 Service

I'm a little late to the party, but I think my approach has the advantage that it lacks the use of EventEmitters and Subjects.

So, here's my approach. We can't get away from subscribe(), and we don't want to. In that vein, our service will return an Observable<T> with an observer that has our precious cargo. From the caller, we'll initialize a variable, Observable<T>, and it will get the service's Observable<T>. Next, we'll subscribe to this object. Finally, you get your "T"! from your service.

First, our people service, but yours doesnt pass parameters, that's more realistic:

people(hairColor: string): Observable<People> {
   this.url = "api/" + hairColor + "/people.json";

   return Observable.create(observer => {
      http.get(this.url)
          .map(res => res.json())
          .subscribe((data) => {
             this._people = data

             observer.next(this._people);
             observer.complete();


          });
   });
}

Ok, as you can see, we're returning an Observable of type "people". The signature of the method, even says so! We tuck-in the _people object into our observer. We'll access this type from our caller in the Component, next!

In the Component:

private _peopleObservable: Observable<people>;

constructor(private peopleService: PeopleService){}

getPeople(hairColor:string) {
   this._peopleObservable = this.peopleService.people(hairColor);

   this._peopleObservable.subscribe((data) => {
      this.people = data;
   });
}

We initialize our _peopleObservable by returning that Observable<people> from our PeopleService. Then, we subscribe to this property. Finally, we set this.people to our data(people) response.

Architecting the service in this fashion has one, major advantage over the typical service: map(...) and component: "subscribe(...)" pattern. In the real world, we need to map the json to our properties in our class and, sometimes, we do some custom stuff there. So this mapping can occur in our service. And, typically, because our service call will be used not once, but, probably, in other places in our code, we don't have to perform that mapping in some component, again. Moreover, what if we add a new field to people?....

HTML button to NOT submit form

It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)

Some reference material

git rebase merge conflict

Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase message in case of conflicts will be clearer.

See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt).
(Merged by Junio C Hamano -- gitster -- in commit 076eeec, 11 Aug 2017)

rebase: make resolve message clearer for inexperienced users

Before:

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"

After:

Resolve all conflicts manually, 
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".

You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')

The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.

In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient is deprecated in sdk 23.

You have to move on URLConnection or down sdk to 22

Still you need HttpClient with update gradle sdk 23

You have to add the dependencies of HttpClient in app/gradle as

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.0.1'

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    ...
}

HTTPS connections over proxy servers

The short answer is: It is possible, and can be done with either a special HTTP proxy or a SOCKS proxy.

First and foremost, HTTPS uses SSL/TLS which by design ensures end-to-end security by establishing a secure communication channel over an insecure one. If the HTTP proxy is able to see the contents, then it's a man-in-the-middle eavesdropper and this defeats the goal of SSL/TLS. So there must be some tricks being played if we want to proxy through a plain HTTP proxy.

The trick is, we turn an HTTP proxy into a TCP proxy with a special command named CONNECT. Not all HTTP proxies support this feature but many do now. The TCP proxy cannot see the HTTP content being transferred in clear text, but that doesn't affect its ability to forward packets back and forth. In this way, client and server can communicate with each other with help of the proxy. This is the secure way of proxying HTTPS data.

There is also an insecure way of doing so, in which the HTTP proxy becomes a man-in-the-middle. It receives the client-initiated connection, and then initiate another connection to the real server. In a well implemented SSL/TLS, the client will be notified that the proxy is not the real server. So the client has to trust the proxy by ignoring the warning for things to work. After that, the proxy simply decrypts data from one connection, reencrypts and feeds it into the other.

Finally, we can certainly proxy HTTPS through a SOCKS proxy, because the SOCKS proxy works at a lower level. You may think a SOCKS proxy as both a TCP and a UDP proxy.

How to use ArrayAdapter<myClass>

Here's a quick and dirty example of how to use an ArrayAdapter if you don't want to bother yourself with extending the mother class:

class MyClass extends Activity {
    private ArrayAdapter<String> mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mAdapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_dropdown_item_1line, android.R.id.text1);

        final ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(mAdapter);

        //Add Some Items in your list:
        for (int i = 1; i <= 10; i++) {
            mAdapter.add("Item " + i);
        }

        // And if you want selection feedback:
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do whatever you want with the selected item
                Log.d(TAG, mAdapter.getItem(position) + " has been selected!");
            }
        });
    }
}

What version of Java is running in Eclipse?

Eclipse uses the default Java on the system to run itself. This can also be changed in the eclipse.ini file in your eclipse install folder.

To find out the version of java that your eclipse project is using, see Project->properties->build path->Libraries tab and see the JRE system library thats being used. You can also check it out at Window->Preferences->Java->Installed JREs. This is a list of all JREs that eclipse knows about

To find out using code, use the System.getProperty(...) method. See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties() for supported properties.

How to sort a HashSet?

You can use TreeSet as mentioned in other answers.

Here's a little more elaboration on how to use it:

TreeSet<String> ts = new TreeSet<String>();
ts.add("b1");
ts.add("b3");
ts.add("b2");
ts.add("a1");
ts.add("a2");
System.out.println(ts);
for (String s: ts)
    System.out.println(s);

Output:

[a1, a2, a3, a4, a5]
a1
a2
b1
b2
b3

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

I recently (Jul 2014) had a similar issue and found on OS X (10.9.4) that there was a "DigiCert High Assurance EV Root CA" certificate had expired (although I had another unexpired one as well).

  1. Open Keychain Access
  2. search Certificates for "DigiCert"
  3. View menu > Show Expired Certificates

I found two certificates named "DigiCert High Assurance EV Root CA", one expiring Nov 2031 and the expired one at July 2014 (a few of days previously). Deleting the expired certificate resolved the issue for me.

Hope this helps.

iterating through Enumeration of hastable keys throws NoSuchElementException error

You are calling nextElement twice. Refactor like this:

while(e.hasMoreElements()){


String param = (String) e.nextElement();
System.out.println(param);
}

How to detect if user select cancel InputBox VBA Excel

The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.

For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:

Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then  'I also tried with sRange.address and vbNullString
    MsgBox ("Cancel pressed!")
    Exit Sub
End If
    MsgBox ("Your custom range is " & sRange.Address)
End Sub

The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:

Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
    MsgBox ("Cancel pressed")
End Sub

So, the question is how to detect either an error or StrPtr()=0 with an If statement?

Access restriction on class due to restriction on required library rt.jar?

In addition to Nels Beckman's solution, I have the following tips:

Under Configure Build Path, I had to rearrange the order of my entries under Order and Export.

Additionally, as an Eclipse PDE developer, I needed to rearrange the order of my dependencies in my MANIFEST.MF, adding the problematic package as first on the list.

Playing with these dials, along with running Project > Clean in between, I was able to resolve these warnings.

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Delaying function in swift

For adding argument to delay function.

First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.

let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]

NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)

Then in the called function

func functionHereWithArgument (timer : NSTimer)
{
    if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
    {
         let argumentInt : Int = (userInfo[argumentInt] as! Int)
    }
}

How to get the fragment instance from the FragmentActivity?

You can use use findFragmentById in FragmentManager.

Since you are using the Support library (you are extending FragmentActivity) you can use:

getSupportFragmentManager().findFragmentById(R.id.pageview)

If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):

getFragmentManager().findFragmentById(R.id.pageview)

Please consider that using the support library is recommended even on Honeycomb+.

Extract first item of each sublist

You could use zip:

>>> lst=[[1,2,3],[11,12,13],[21,22,23]]
>>> zip(*lst)[0]
(1, 11, 21)

Or, Python 3 where zip does not produce a list:

>>> list(zip(*lst))[0]
(1, 11, 21)

Or,

>>> next(zip(*lst))
(1, 11, 21)

Or, (my favorite) use numpy:

>>> import numpy as np
>>> a=np.array([[1,2,3],[11,12,13],[21,22,23]])
>>> a
array([[ 1,  2,  3],
       [11, 12, 13],
       [21, 22, 23]])
>>> a[:,0]
array([ 1, 11, 21])

How do I cancel an HTTP fetch() request?

As for now there is no proper solution, as @spro says.

However, if you have an in-flight response and are using ReadableStream, you can close the stream to cancel the request.

fetch('http://example.com').then((res) => {
  const reader = res.body.getReader();

  /*
   * Your code for reading streams goes here
   */

  // To abort/cancel HTTP request...
  reader.cancel();
});

How do I combine a background-image and CSS3 gradient on the same element?

Multiple backgrounds!

_x000D_
_x000D_
body {_x000D_
  background: #eb01a5;_x000D_
  background-image: url("IMAGE_URL"); /* fallback */_x000D_
  background-image: url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531); /* W3C */_x000D_
}
_x000D_
_x000D_
_x000D_

These 2 lines are the fallback for any browser that doesn't do gradients. See notes for stacking images only IE < 9 below.

  • Line 1 sets a flat background color.
  • Line 2 sets the background image fallback.

The final line sets a background image and gradient for browsers that can handle them.

  • Line 3 is for all relatively modern browsers.

Nearly all current browsers have support for multiple background images and css backgrounds. See http://caniuse.com/#feat=css-gradients for browser support. For a good post on why you don't need multiple browser prefixes, see http://codepen.io/thebabydino/full/pjxVWp/

Layer Stack

It should be noted that the first defined image will be topmost in the stack. In this case, the image is on TOP of the gradient.

For more information about background layering see http://www.w3.org/TR/css3-background/#layering.

Stacking images ONLY (no gradients in the declaration) For IE < 9

IE9 and up can stack images this same way. You could use this to create a gradient image for ie9, though personally, I wouldn't. However to be noted when using only images, ie < 9 will ignore the fallback statement and not show any image. This does not happen when a gradient is included. To use a single fallback image in this case I suggest using Paul Irish's wonderful Conditional HTML element along with your fallback code:

.lte9 #target{ background-image: url("IMAGE_URL"); }

Background position, sizing etc.

Other properties that would apply to a single image may also be comma separated. If only 1 value is supplied, that will be applied to all stacked images including the gradient. background-size: 40px; will constrain both the image and the gradient to 40px height and width. However using background-size: 40px, cover; will make the image 40px and the gradient will cover the element. To only apply a setting to one image, set the default for the other: background-position: 50%, 0 0; or for browsers that support it use initial: background-position: 50%, initial;

You may also use the background shorthand, however this removes the fallback color and image.

body{
    background: url("IMAGE_URL") no-repeat left top, linear-gradient(#eb01a5, #d13531);
}

The same applies to background-position, background-repeat, etc.

Handle spring security authentication exceptions with @ExceptionHandler

Customize the filter, and determine what kind of abnormality, there should be a better method than this

public class ExceptionFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    String msg = "";
    try {
        filterChain.doFilter(request, response);
    } catch (Exception e) {
        if (e instanceof JwtException) {
            msg = e.getMessage();
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON.getType());
        response.getWriter().write(JSON.toJSONString(Resp.error(msg)));
        return;
    }
}

}

How do I plot in real-time in a while loop using matplotlib?

None of the methods worked for me. But I have found this Real time matplotlib plot is not working while still in a loop

All you need is to add

plt.pause(0.0001)

and then you could see the new plots.

So your code should look like this, and it will work

import matplotlib.pyplot as plt
import numpy as np
plt.ion() ## Note this correction
fig=plt.figure()
plt.axis([0,1000,0,1])

i=0
x=list()
y=list()

while i <1000:
    temp_y=np.random.random();
    x.append(i);
    y.append(temp_y);
    plt.scatter(i,temp_y);
    i+=1;
    plt.show()
    plt.pause(0.0001) #Note this correction

How to get system time in Java without creating a new Date

You can use System.currentTimeMillis().

At least in OpenJDK, Date uses this under the covers.

The call in System is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

In actionPerformed(ActionEvent e) you call encrypt(), which is declared to throw Exception. However, actionPerformed neither catches this Exception (with try/catch around the call to encrypt()) nor declares that it throws Exception itself.

Your encrypt method, however, does not truly throw Exception. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)

Also, your encrypt method does the following:

public static byte[] encrypt(String toEncrypt) throws Exception {
  try{
    ....
    return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
  } catch(Exception e) {
  }
  // YOU DO NOT RETURN ANYTHING HERE
}

That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.

In Django, how do I check if a user is in a certain group?

You just need one line:

from django.contrib.auth.decorators import user_passes_test  

@user_passes_test(lambda u: u.groups.filter(name='companyGroup').exists())
def you_view():
    return HttpResponse("Since you're logged in, you can see this text!")

Casting interfaces for deserialization in JSON.NET

For what it's worth, I ended up having to handle this myself for the most part. Each object has a Deserialize(string jsonStream) method. A few snippets of it:

JObject parsedJson = this.ParseJson(jsonStream);
object thingyObjectJson = (object)parsedJson["thing"];
this.Thing = new Thingy(Convert.ToString(thingyObjectJson));

In this case, new Thingy(string) is a constructor that will call the Deserialize(string jsonStream) method of the appropriate concrete type. This scheme will continue to go downward and downward until you get to the base points that json.NET can just handle.

this.Name = (string)parsedJson["name"];
this.CreatedTime = DateTime.Parse((string)parsedJson["created_time"]);

So on and so forth. This setup allowed me to give json.NET setups it can handle without having to refactor a large part of the library itself or using unwieldy try/parse models that would have bogged down our entire library due to the number of objects involved. It also means that I can effectively handle any json changes on a specific object, and I do not need to worry about everything that object touches. It's by no means the ideal solution, but it works quite well from our unit and integration testing.

How to make inline plots in Jupyter Notebook larger?

A small but important detail for adjusting figure size on a one-off basis (as several commenters above reported "this doesn't work for me"):

You should do plt.figure(figsize=(,)) PRIOR to defining your actual plot. For example:

This should correctly size the plot according to your specified figsize:

values = [1,1,1,2,2,3]
_ = plt.figure(figsize=(10,6))
_ = plt.hist(values,bins=3)
plt.show()

Whereas this will show the plot with the default settings, seeming to "ignore" figsize:

values = [1,1,1,2,2,3]
_ = plt.hist(values,bins=3)
_ = plt.figure(figsize=(10,6))
plt.show()

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I had a similar use case where I wanted to test a Spring Boot configured repository in isolation (in my case without Spring Security autoconfiguration which was failing my test). @SpringApplicationConfiguration uses SpringApplicationContextLoader and that has a JavaDoc stating

Can be used to test non-web features (like a repository layer) or start an fully-configured embedded servlet container.

However, like yourself, I could not work out how you are meant to configure the test to only test the repository layer using the main configuration entry point i.e. using your approach of @SpringApplicationConfiguration(classes = Application.class).

My solution was to create a completely new application context exclusive for testing. So in src/test/java I have two files in a sub-package called repo

  1. RepoIntegrationTest.java
  2. TestRepoConfig.java

where RepoIntegrationTest.java has

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestRepoConfig.class)
public class RepoIntegrationTest {

and TestRepoConfig.java has

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class TestRepoConfig {

It got me out of trouble but it would be really useful if anyone from the Spring Boot team could provide an alternative recommended solution

How can I get the current network interface throughput statistics on Linux/UNIX?

If you want just to get the value, you can use simple shell oneliner like this:

S=10; F=/sys/class/net/eth0/statistics/rx_bytes; X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))"; echo $BPS

It will show you the average "received bytes per second" for period of 10 seconds (you can change period by changing S=10 parameter, and you can measure transmitted BPS instead of received BPS by using tx_bytes instead of rx_bytes). Don't forget to change eth0 to network device you want to monitor.

Of course, you are not limited to displaying the average rate (as mentioned in other answers, there are other tools that will show you much nicer output), but this solution is easily scriptable to do other things.

For example, the following shell script (split into multiple lines for readability) will execute offlineimap process only when 5-minute average transmit speed drops below 10kBPS (presumably, when some other bandwidth-consuming process finishes):

#!/bin/sh
S=300; F=/sys/class/net/eth0/statistics/tx_bytes
BPS=999999
while [ $BPS -gt 10000 ]
do
  X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))";
  echo BPS is currently $BPS
done
offlineimap

Note that /sys/class/... is Linux specific (which is ok as submitter did choose linux tag), and needs non-archaic kernel. Shell code itself is /bin/sh compatible (so not only bash, but dash and other /bin/sh implementations will work) and /bin/sh is something that is really always installed.

java.util.Date to XMLGregorianCalendar

For those that might end up here looking for the opposite conversion (from XMLGregorianCalendar to Date):

XMLGregorianCalendar xcal = <assume this is initialized>;
java.util.Date dt = xcal.toGregorianCalendar().getTime();

Can anonymous class implement interface?

Casting anonymous types to interfaces has been something I've wanted for a while but unfortunately the current implementation forces you to have an implementation of that interface.

The best solution around it is having some type of dynamic proxy that creates the implementation for you. Using the excellent LinFu project you can replace

select new
{
  A = value.A,
  B = value.C + "_" + value.D
};

with

 select new DynamicObject(new
 {
   A = value.A,
   B = value.C + "_" + value.D
 }).CreateDuck<DummyInterface>();

Secure FTP using Windows batch script

    ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121

S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ; 
RemoteServerName =>  abcd123 ; 
2121 => port number ; 
ftps => command is part of ftps client software ; 

How to add external JS scripts to VueJS Components

You can use the vue-head package to add scripts, and other tags to the head of your vue component.

Its as simple as:

var myComponent = Vue.extend({
  data: function () {
    return {
      ...
    }
  },
  head: {
    title: {
      inner: 'It will be a pleasure'
    },
    // Meta tags
    meta: [
      { name: 'application-name', content: 'Name of my application' },
      { name: 'description', content: 'A description of the page', id: 'desc' }, // id to replace intead of create element
      // ...
      // Twitter
      { name: 'twitter:title', content: 'Content Title' },
      // with shorthand
      { n: 'twitter:description', c: 'Content description less than 200 characters'},
      // ...
      // Google+ / Schema.org
      { itemprop: 'name', content: 'Content Title' },
      { itemprop: 'description', content: 'Content Title' },
      // ...
      // Facebook / Open Graph
      { property: 'fb:app_id', content: '123456789' },
      { property: 'og:title', content: 'Content Title' },
      // with shorthand
      { p: 'og:image', c: 'https://example.com/image.jpg' },
      // ...
    ],
    // link tags
    link: [
      { rel: 'canonical', href: 'http://example.com/#!/contact/', id: 'canonical' },
      { rel: 'author', href: 'author', undo: false }, // undo property - not to remove the element
      { rel: 'icon', href: require('./path/to/icon-16.png'), sizes: '16x16', type: 'image/png' }, 
      // with shorthand
      { r: 'icon', h: 'path/to/icon-32.png', sz: '32x32', t: 'image/png' },
      // ...
    ],
    script: [
      { type: 'text/javascript', src: 'cdn/to/script.js', async: true, body: true}, // Insert in body
      // with shorthand
      { t: 'application/ld+json', i: '{ "@context": "http://schema.org" }' },
      // ...
    ],
    style: [
      { type: 'text/css', inner: 'body { background-color: #000; color: #fff}', undo: false },
      // ...
    ]
  }
})

Check out this link for more examples.

How do I configure Maven for offline development?

A new plugin has appeared to fix shortcomings of mvn dependency:go-offline:

https://github.com/qaware/go-offline-maven-plugin

Add it in your pom, then run mvn -T1C de.qaware.maven:go-offline-maven-plugin:resolve-dependencies. Once you've setup all dynamic dependencies, maven won't try to download anything again (until you update versions).

Npm install cannot find module 'semver'

Just make sure semver is installed: npm install -g semver

Using PHP with Socket.io

UPDATE: Aug 2014 The current socket.io v1.0 site has a PHP example:- https://github.com/rase-/socket.io-php-emitter

What jar should I include to use javax.persistence package in a hibernate based application?

If you are using maven, adding below dependency should work

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

How to set selected item of Spinner by value, not by position?

There is actually a way to get this using an index search on the AdapterArray and all this can be done with reflection. I even went one step further as I had 10 Spinners and wanted to set them dynamically from my database and the database holds the value only not the text as the Spinner actually changes week to week so the value is my id number from the database.

 // Get the JSON object from db that was saved, 10 spinner values already selected by user
 JSONObject json = new JSONObject(string);
 JSONArray jsonArray = json.getJSONArray("answer");

 // get the current class that Spinner is called in 
 Class<? extends MyActivity> cls = this.getClass();

 // loop through all 10 spinners and set the values with reflection             
 for (int j=1; j< 11; j++) {
      JSONObject obj = jsonArray.getJSONObject(j-1);
      String movieid = obj.getString("id");

      // spinners variable names are s1,s2,s3...
      Field field = cls.getDeclaredField("s"+ j);

      // find the actual position of value in the list     
      int datapos = indexedExactSearch(Arrays.asList(Arrays.asList(this.data).toArray()), "value", movieid) ;
      // find the position in the array adapter
      int pos = this.adapter.getPosition(this.data[datapos]);

      // the position in the array adapter
      ((Spinner)field.get(this)).setSelection(pos);

}

Here is the indexed search you can use on almost any list as long as the fields are on top level of object.

    /**
 * Searches for exact match of the specified class field (key) value within the specified list.
 * This uses a sequential search through each object in the list until a match is found or end
 * of the list reached.  It may be necessary to convert a list of specific objects into generics,
 * ie: LinkedList&ltDevice&gt needs to be passed as a List&ltObject&gt or Object[&nbsp] by using 
 * Arrays.asList(device.toArray(&nbsp)).
 * 
 * @param list - list of objects to search through
 * @param key - the class field containing the value
 * @param value - the value to search for
 * @return index of the list object with an exact match (-1 if not found)
 */
public static <T> int indexedExactSearch(List<Object> list, String key, String value) {
    int low = 0;
    int high = list.size()-1;
    int index = low;
    String val = "";

    while (index <= high) {
        try {
            //Field[] c = list.get(index).getClass().getDeclaredFields();
            val = cast(list.get(index).getClass().getDeclaredField(key).get(list.get(index)) , "NONE");
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        if (val.equalsIgnoreCase(value))
            return index; // key found

        index = index + 1;
    }

    return -(low + 1);  // key not found return -1
}

Cast method which can be create for all primitives here is one for string and int.

        /**
 *  Base String cast, return the value or default
 * @param object - generic Object
 * @param defaultValue - default value to give if Object is null
 * @return - returns type String
 */
public static String cast(Object object, String defaultValue) {
    return (object!=null) ? object.toString() : defaultValue;
}


    /**
 *  Base integer cast, return the value or default
 * @param object - generic Object
 * @param defaultValue - default value to give if Object is null
 * @return - returns type integer
 */
public static int cast(Object object, int defaultValue) { 
    return castImpl(object, defaultValue).intValue();
}

    /**
 *  Base cast, return either the value or the default
 * @param object - generic Object
 * @param defaultValue - default value to give if Object is null
 * @return - returns type Object
 */
public static Object castImpl(Object object, Object defaultValue) {
    return object!=null ? object : defaultValue;
}

How to specify the default error page in web.xml?

You can also specify <error-page> for exceptions using <exception-type>, eg below:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

Or map a error code using <error-code>:

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>

.NET / C# - Convert char[] to string

One other way:

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = string.Join("", chars);
//we get "a string"
// or for fun:
string s = string.Join("_", chars);
//we get "a_ _s_t_r_i_n_g"

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

How to prevent IFRAME from redirecting top-level window

I use sandbox="..."

  • allow-forms allows form submission
  • allow-popups allows popups
  • allow-pointer-lock allows pointer lock
  • allow-same-origin allows the document to maintain its origin
  • allow-scripts allows JavaScript execution, and also allows features to trigger automatically
  • allow-top-navigation allows the document to break out of the frame by navigating the top-level window

Top navigation is what you want to prevent, so leave that out and it will not be allowed. Anything left out will be blocked

ex.

        <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="http://www.example.com"</iframe>

WP -- Get posts by category?

You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts

Note: The category_name parameter needs to be a string, in this case, the category name.

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

Retrieve column names from java.sql.ResultSet

You can get this info from the ResultSet metadata. See ResultSetMetaData

e.g.

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 String name = rsmd.getColumnName(1);

and you can get the column name from there. If you do

select x as y from table

then rsmd.getColumnLabel() will get you the retrieved label name too.

Select element by exact match of its content

Like T.J. Crowder stated above, the filter function does wonders. It wasn't working for me in my specific case. I needed to search multiple tables and their respective td tags inside a div (in this case a jQuery dialog).

$("#MyJqueryDialog table tr td").filter(function () {
    // The following implies that there is some text inside the td tag.
    if ($.trim($(this).text()) == "Hello World!") {
       // Perform specific task.
    }
});

I hope this is helpful to someone!

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

The source was not found, but some or all event logs could not be searched

For me this error was due to the command prompt, which was not running under administrator privileges. You need to right click on the command prompt and say "Run as administrator".

You need administrator role to install or uninstall a service.

git-diff to ignore ^M

I struggled with this problem for a long time. By far the easiest solution is to not worry about the ^M characters and just use a visual diff tool that can handle them.

Instead of typing:

git diff <commitHash> <filename>

try:

git difftool <commitHash> <filename>

what is the difference between ajax and jquery and which one is better?

It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.

It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.

Why does ASP.NET webforms need the Runat="Server" attribute?

I just came to this conclusion by trial-and-error: runat="server" is needed to access the elements at run-time on server side. Remove them, recompile and watch what happens.

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

Eclipse : Maven search dependencies doesn't work

For me for this issue worked to:

  • remove ~/.m2
  • enable "Full Index Enabled" in maven repository view on central repository
  • "Rebuild Index" on central maven repository

After eclipse restart everything worked well.

Installing a specific version of angular with angular cli

You can just have package.json with specific version and do npm install and it will install that version. Also you dont need to depend on angular-cli to develop your project.

Error: unable to verify the first certificate in nodejs

Another approach to solve this is to use the following module.

node_extra_ca_certs_mozilla_bundle

This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),

NODE_EXTRA_CA_CERTS

To generate the PEM file to use with the above environment variable. You can install the module using:

npm install --save node_extra_ca_certs_mozilla_bundle

and then launch your node script with an environment variable.

NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js

Other ways to use the generated PEM file are available at:

https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle

NOTE: I am the author of the above module.

IPython/Jupyter Problems saving notebook as PDF

If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.

Screenshot Convert ipynb to pdf

If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.

What are the default access modifiers in C#?

Simplest answer is the following.....

All members in C# always take the LEAST accessible modifier possible by default.

That is why all top level classes in an assembly are "internal" by default, which means they are public to the assembly they are in, but private or excluded from access to outside assemblies. The only other option for a top level class is public which is more accessible. For nested types its all private except for a few rare exceptions like members of enums and interfaces which can only be public. Some examples. In the case of top level classes and interfaces, the defaults are:

class Animal same as internal class Animal

interface Animal same as public interface Animal

In the case of nested classes and interfaces (inside types), the defaults are:

class Animal same as private class Animal

interface Animal same as private interface Animal

If you just assume the default is always the most private, then you do not need to use an accessors until you need to change the default. Easy.

Converting JSON data to Java object

HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}

No Exception while type casting with a null in java

You can cast null to any reference type without getting any exception.

The println method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null". Otherwise it will call the toString method of that object.

Adding more details: Internally print methods call String.valueOf(object) method on the input object. And in valueOf method, this check helps to avoid null pointer exception:

return (obj == null) ? "null" : obj.toString();

For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

Spring Boot application.properties value not populating

The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.

You need to do one of the following:

Better solution

@Component
public class MyBean {

    private final String prop;

    @Autowired
    public MyBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        System.out.println("================== " + prop + "================== ");
    }
}

Solution that will work but is less testable and slightly less readable

@Component
public class MyBean {

    @Value("${some.prop}")
    private String prop;

    public MyBean() {

    }

    @PostConstruct
    public void init() {
        System.out.println("================== " + prop + "================== ");
    }
}

Also note that is not Spring Boot specific but applies to any Spring application

jwt check if token expired

You should use jwt.verify it will check if the token is expired. jwt.decode should not be used if the source is not trusted as it doesn't check if the token is valid.

Why a function checking if a string is empty always returns true?

You can simply cast to bool, dont forget to handle zero.

function isEmpty(string $string): bool {
    if($string === '0') {
        return false;
    }
    return !(bool)$string;
}

var_dump(isEmpty('')); // bool(true)
var_dump(isEmpty('foo')); // bool(false)
var_dump(isEmpty('0')); // bool(false)

for each inside a for each - Java

for (Tweet : tweets){ ...

should really be

for(Tweet tweet: tweets){...

How can I get log4j to delete old rotating log files?

You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.

package com.example.package;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CustomLog4jAppender extends FileAppender {

    private static final int TOP_OF_TROUBLE = -1;
    private static final int TOP_OF_MINUTE = 0;
    private static final int TOP_OF_HOUR = 1;
    private static final int HALF_DAY = 2;
    private static final int TOP_OF_DAY = 3;
    private static final int TOP_OF_WEEK = 4;
    private static final int TOP_OF_MONTH = 5;

    private String datePattern = "'.'yyyy-MM-dd";
    private String compressBackups = "false";
    private String maxNumberOfDays = "7";
    private String scheduledFilename;
    private long nextCheck = System.currentTimeMillis() - 1;
    private Date now = new Date();
    private SimpleDateFormat sdf;
    private RollingCalendar rc = new RollingCalendar();

    private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

    public CustomLog4jAppender() {
    }

    public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
        super(layout, filename, true);
        this.datePattern = datePattern;
        activateOptions();
    }

    public void setDatePattern(String pattern) {
        datePattern = pattern;
    }

    public String getDatePattern() {
        return datePattern;
    }

    @Override
    public void activateOptions() {
        super.activateOptions();
        if (datePattern != null && fileName != null) {
            now.setTime(System.currentTimeMillis());
            sdf = new SimpleDateFormat(datePattern);
            int type = computeCheckPeriod();
            printPeriodicity(type);
            rc.setType(type);
            File file = new File(fileName);
            scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
        } else {
            LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
        }
    }

    private void printPeriodicity(int type) {
        String appender = "Log4J Appender: ";
        switch (type) {
            case TOP_OF_MINUTE:
                LogLog.debug(appender + name + " to be rolled every minute.");
                break;
            case TOP_OF_HOUR:
                LogLog.debug(appender + name + " to be rolled on top of every hour.");
                break;
            case HALF_DAY:
                LogLog.debug(appender + name + " to be rolled at midday and midnight.");
                break;
            case TOP_OF_DAY:
                LogLog.debug(appender + name + " to be rolled at midnight.");
                break;
            case TOP_OF_WEEK:
                LogLog.debug(appender + name + " to be rolled at start of week.");
                break;
            case TOP_OF_MONTH:
                LogLog.debug(appender + name + " to be rolled at start of every month.");
                break;
            default:
                LogLog.warn("Unknown periodicity for appender [" + name + "].");
        }
    }

    private int computeCheckPeriod() {
        RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
        Date epoch = new Date(0);
        if (datePattern != null) {
            for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
                simpleDateFormat.setTimeZone(gmtTimeZone);
                String r0 = simpleDateFormat.format(epoch);
                rollingCalendar.setType(i);
                Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
                String r1 = simpleDateFormat.format(next);
                if (!r0.equals(r1)) {
                    return i;
                }
            }
        }
        return TOP_OF_TROUBLE;
    }

    private void rollOver() throws IOException {
        if (datePattern == null) {
            errorHandler.error("Missing DatePattern option in rollOver().");
            return;
        }
        String datedFilename = fileName + sdf.format(now);
        if (scheduledFilename.equals(datedFilename)) {
            return;
        }
        this.closeFile();
        File target = new File(scheduledFilename);
        if (target.exists()) {
            Files.delete(target.toPath());
        }
        File file = new File(fileName);
        boolean result = file.renameTo(target);
        if (result) {
            LogLog.debug(fileName + " -> " + scheduledFilename);
        } else {
            LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
        }
        try {
            this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
        } catch (IOException e) {
            errorHandler.error("setFile(" + fileName + ", false) call failed.");
        }
        scheduledFilename = datedFilename;
    }

    @Override
    protected void subAppend(LoggingEvent event) {
        long n = System.currentTimeMillis();
        if (n >= nextCheck) {
            now.setTime(n);
            nextCheck = rc.getNextCheckMillis(now);
            try {
                cleanupAndRollOver();
            } catch (IOException ioe) {
                LogLog.error("cleanupAndRollover() failed.", ioe);
            }
        }
        super.subAppend(event);
    }

    public String getCompressBackups() {
        return compressBackups;
    }

    public void setCompressBackups(String compressBackups) {
        this.compressBackups = compressBackups;
    }

    public String getMaxNumberOfDays() {
        return maxNumberOfDays;
    }

    public void setMaxNumberOfDays(String maxNumberOfDays) {
        this.maxNumberOfDays = maxNumberOfDays;
    }

    protected void cleanupAndRollOver() throws IOException {
        File file = new File(fileName);
        Calendar cal = Calendar.getInstance();
        int maxDays = 7;
        try {
            maxDays = Integer.parseInt(getMaxNumberOfDays());
        } catch (Exception e) {
            // just leave it at 7.
        }
        cal.add(Calendar.DATE, -maxDays);
        Date cutoffDate = cal.getTime();
        if (file.getParentFile().exists()) {
            File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
            int nameLength = file.getName().length();
            for (File value : Optional.ofNullable(files).orElse(new File[0])) {
                String datePart;
                try {
                    datePart = value.getName().substring(nameLength);
                    Date date = sdf.parse(datePart);
                    if (date.before(cutoffDate)) {
                        Files.delete(value.toPath());
                    } else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
                        zipAndDelete(value);
                    }
                } catch (Exception pe) {
                    // This isn't a file we should touch (it isn't named correctly)
                }
            }
        }
        rollOver();
    }

    private void zipAndDelete(File file) throws IOException {
        if (!file.getName().endsWith(".zip")) {
            File zipFile = new File(file.getParent(), file.getName() + ".zip");
            try (FileInputStream fis = new FileInputStream(file);
                 FileOutputStream fos = new FileOutputStream(zipFile);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[4096];
                while (true) {
                    int bytesRead = fis.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    } else {
                        zos.write(buffer, 0, bytesRead);
                    }
                }
                zos.closeEntry();
            }
            Files.delete(file.toPath());
        }
    }

    class StartsWithFileFilter implements FileFilter {
        private String startsWith;
        private boolean inclDirs;

        StartsWithFileFilter(String startsWith, boolean includeDirectories) {
            super();
            this.startsWith = startsWith.toUpperCase();
            inclDirs = includeDirectories;
        }

        public boolean accept(File pathname) {
            if (!inclDirs && pathname.isDirectory()) {
                return false;
            } else {
                return pathname.getName().toUpperCase().startsWith(startsWith);
            }
        }
    }

    class RollingCalendar extends GregorianCalendar {
        private static final long serialVersionUID = -3560331770601814177L;

        int type = CustomLog4jAppender.TOP_OF_TROUBLE;

        RollingCalendar() {
            super();
        }

        RollingCalendar(TimeZone tz, Locale locale) {
            super(tz, locale);
        }

        void setType(int type) {
            this.type = type;
        }

        long getNextCheckMillis(Date now) {
            return getNextCheckDate(now).getTime();
        }

        Date getNextCheckDate(Date now) {
            this.setTime(now);

            switch (type) {
                case CustomLog4jAppender.TOP_OF_MINUTE:
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MINUTE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_HOUR:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.HOUR_OF_DAY, 1);
                    break;
                case CustomLog4jAppender.HALF_DAY:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    int hour = get(Calendar.HOUR_OF_DAY);
                    if (hour < 12) {
                        this.set(Calendar.HOUR_OF_DAY, 12);
                    } else {
                        this.set(Calendar.HOUR_OF_DAY, 0);
                        this.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    break;
                case CustomLog4jAppender.TOP_OF_DAY:
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.DATE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_WEEK:
                    this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.WEEK_OF_YEAR, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_MONTH:
                    this.set(Calendar.DATE, 1);
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MONTH, 1);
                    break;
                default:
                    throw new IllegalStateException("Unknown periodicity type.");
            }
            return getTime();
        }
    }    
}

And use this properties in your log4j config file:

log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true

Executing Batch File in C#

After some great help from steinar this is what worked for me:

public void ExecuteCommand(string command)
{
    int ExitCode;
    ProcessStartInfo ProcessInfo;
    Process process;

    ProcessInfo = new ProcessStartInfo(Application.StartupPath + "\\txtmanipulator\\txtmanipulator.bat", command);
    ProcessInfo.CreateNoWindow = true;
    ProcessInfo.UseShellExecute = false;
    ProcessInfo.WorkingDirectory = Application.StartupPath + "\\txtmanipulator";
    // *** Redirect the output ***
    ProcessInfo.RedirectStandardError = true;
    ProcessInfo.RedirectStandardOutput = true;

    process = Process.Start(ProcessInfo);
    process.WaitForExit();

    // *** Read the streams ***
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();

    ExitCode = process.ExitCode;

    MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
    MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
    MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
    process.Close();
}

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

In my case, I was getting the error with Mac OS X 10.9 Mavericks. I installed MySQL Community Server directly from the Oracle/MySQL Website from DMG.

All I needed to do was symlink the lib files to the /usr/local/lib directory.

mkdir -p /usr/local/lib   
ln -s /usr/local/mysql/lib/libmysql* /usr/local/lib

Bonus: If you're running Mac OS X as well, there is a great tool to finding files like the libmysqlclient.18.dylib file, http://apps.tempel.org/FindAnyFile. This is how I originally found the location of the dylib file.

Difference between BYTE and CHAR in column datatypes

I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.

Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).

Sublime Text 3 how to change the font size of the file sidebar?

You need to change it at "class": "sidebar_label" Example, in your .sublime-theme file:

// Sidebar entry
{
    "class": "sidebar_label",
    "color": [212, 212, 213],
    "shadow_offset": [0, 0],
    "font.size":13
}

Credit

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

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

Hibernate Union alternatives

Perhaps I had a more straight-forward problem to solve. My 'for instance' was in JPA with Hibernate as the JPA provider.

I split the three selects (two in a second case) into multiple select and combined the collections returned myself, effectively replacing a 'union all'.

Bootstrap modal appearing under background

Try this code to CSS.

.modal-open { overflow: hidden !important; }
.modal-open *{ position:unset; z-index: 0; }
.modal-open .modal-backdrop { position: fixed; z-index: 99998 !important; }
.modal-open .modal { position: fixed; z-index: 99999 !important; }

Ex:

_x000D_
_x000D_
    $(window).on('load', function() {_x000D_
      _x000D_
/* Latest compiled and minified JavaScript included as External Resource */_x000D_
$(document).ready(function() { $('.modal').modal("show"); });_x000D_
_x000D_
    });
_x000D_
/* Optional theme */_x000D_
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');_x000D_
_x000D_
body {_x000D_
    margin: 10px;_x000D_
    padding-top: 50px;_x000D_
}_x000D_
_x000D_
.my-module {_x000D_
    position: fixed;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    border: 1px solid red;_x000D_
}_x000D_
_x000D_
.modal-open { overflow: hidden !important; }_x000D_
.modal-open *{ position:unset; z-index: 0; }_x000D_
.modal-open .modal-backdrop { position: fixed; z-index: 99998 !important; }_x000D_
.modal-open .modal { position: fixed; z-index: 99999 !important; }
_x000D_
<html><head>_x000D_
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">_x000D_
  <title>Bootstrap 3 Template</title>_x000D_
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">_x000D_
  <meta name="robots" content="noindex, nofollow">_x000D_
  <meta name="googlebot" content="noindex, nofollow">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
_x000D_
_x000D_
  <script type="text/javascript" src="//code.jquery.com/jquery-compat-git.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">_x000D_
_x000D_
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">_x000D_
_x000D_
      <script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
      <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">_x000D_
_x000D_
_x000D_
</head>_x000D_
<body class="modal-open">_x000D_
    <div class="container">_x000D_
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus et augue sed lorem laoreet vehicula sit amet eget tortor. Donec in turpis gravida, commodo mauris ac, gravida neque. Proin eget tristique lorem. Integer tincidunt sem sit amet metus ultricies, vitae placerat dui gravida. Pellentesque viverra, nunc imperdiet egestas imperdiet, magna massa varius arcu, vitae iaculis tortor quam vitae arcu. Fusce posuere non lectus vel cursus. In rutrum sed dui non sollicitudin. Proin ante magna, imperdiet ac nisl ut, rhoncus pellentesque tortor.</p>_x000D_
_x000D_
    <p>Cras ac velit vitae elit tempus tempus. Nullam eu posuere leo. In posuere, tortor et cursus ultrices, lorem lacus efficitur dolor, a aliquet elit urna sed tortor. Donec dignissim ante ex, non congue ex efficitur sit amet. Suspendisse lacinia tristique odio, vel sagittis dui tempor tempus. Quisque gravida mauris metus, sed aliquam lacus sollicitudin sit amet. Pellentesque laoreet facilisis scelerisque. Nunc a pulvinar magna. Maecenas at mollis tortor.</p>_x000D_
_x000D_
    <p>Vivamus ultricies, odio sed ornare maximus, libero justo dignissim nulla, nec pharetra neque nulla vel leo. Donec imperdiet sem sem, eu interdum justo tincidunt finibus. Vestibulum lacinia diam gravida risus luctus, elementum blandit dui porttitor. Quisque varius lacus et tempor faucibus. Nam eros nunc, gravida eu tellus eget, placerat porta leo. Duis tempus ultricies felis sit amet cursus. Nunc egestas ex non lacus laoreet tincidunt. Sed malesuada placerat elementum. Mauris eu rutrum nulla. Nunc consequat lacus eget libero tincidunt, in semper eros accumsan. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse eu tincidunt quam, ut tincidunt eros. Donec luctus velit ac nulla lacinia malesuada.</p>_x000D_
_x000D_
    <p>Vestibulum id mi in urna lacinia mollis. Pellentesque sit amet mauris ullamcorper, suscipit dolor in, lacinia leo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse platea dictumst. Vivamus sollicitudin tempus massa sed molestie. Nullam quis neque vel nunc convallis porta a laoreet ex. Aliquam tempus hendrerit turpis eleifend convallis. Cras enim eros, fermentum sed velit eget, dignissim malesuada augue. Fusce ut fermentum nisl, vel imperdiet libero. Etiam luctus arcu volutpat turpis finibus pulvinar eget in augue. Integer sapien nisi, scelerisque ultrices quam sit amet, aliquam placerat neque. Morbi consequat porttitor lacus, quis pulvinar dolor aliquam ut. Ut et dolor id est iaculis lobortis nec aliquet nisl.</p>_x000D_
_x000D_
    <p>Nunc et tortor cursus, ullamcorper justo vitae, ullamcorper sapien. In fringilla urna quam, et finibus ipsum finibus eu. In fermentum turpis ut eros semper, non gravida purus ornare. Praesent vehicula lobortis lacinia. Vivamus nec elit libero. Suspendisse porta neque ut erat tempor rhoncus. Nunc quis massa in ante rhoncus bibendum. Nam maximus ex vitae orci luctus scelerisque. Sed id mauris iaculis, scelerisque mauris feugiat, vehicula ipsum. Duis semper erat ac nulla sodales gravida. Suspendisse nec sapien pharetra, scelerisque odio in, dignissim erat. Aenean feugiat sagittis eros, in mattis orci tristique lacinia. Phasellus posuere id neque sed mattis. Morbi accumsan faucibus ullamcorper.</p>    _x000D_
    _x000D_
    _x000D_
<div class="my-module">_x000D_
    This is a container for "my-module" with some fixed position. The module contains the modal code._x000D_
<div class="modal fade in" aria-hidden="false" style="display: block;">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body…</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div><!-- /.modal -->_x000D_
    _x000D_
</div>_x000D_
</div>_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

How can git be installed on CENTOS 5.5?

From source? From the repos? The easiest way is to use the repos: sudo yum install git should do it. It may first be necessary to set up an additional repo such as EPEL first if git is not provided by the main repos.

If you want to install from source, you can try these instructions. If you have yum-utils installed it's actually easier than that, too**:

sudo yum build-dep git
wget http://kernel.org/pub/software/scm/git/<latest-git-source>.tar.gz
tar -xvjf <latest-git>.tar.gz
cd <git>
make (possibly a ./configure before this)
sudo make install

**Substitute the portions enclosed in <> with the paths you need. Exact procedure may vary slightly as I have not compiled git from source, personally (there may be a configure script, for example). If you have no idea what I'm talking about, then you may want to just install from the repo as per my first suggestion.

What exceptions should be thrown for invalid or unexpected parameters in .NET?

There is a standard ArgumentException that you could use, or you could subclass and make your own. There are several specific ArgumentException classes:

http://msdn.microsoft.com/en-us/library/system.argumentexception(VS.71).aspx

Whichever one works best.

How to run cron job every 2 hours

0 */1 * * * “At minute 0 past every hour.”

0 */2 * * * “At minute 0 past every 2nd hour.”

This is the proper way to set cronjobs for every hr.

Proxy Basic Authentication in C#: HTTP 407 error

I had a similar problem due to a password protected proxy server and couldn't find much in the way of information out there - hopefully this helps someone. I wanted to pick up the credentials as used by the customer's browser. However, the CredentialCache.DefaultCredentials and DefaultNetworkCredentials aren't working when the proxy has it's own username and password even though I had entered these details to ensure thatInternet explorer and Edge had access.

The solution for me in the end was to use a nuget package called "CredentialManagement.Standard" and the below code:

using WebClient webClient = new WebClient();    
var request = WebRequest.Create("http://google.co.uk");
var proxy = request.Proxy.GetProxy(new Uri("http://google.co.uk"));

var cmgr = new CredentialManagement.Credential() { Target = proxy.Host };
if (cmgr.Load())
{
    var credentials = new NetworkCredential(cmgr.Username, cmgr.Password);
    webClient.Proxy.Credentials = credentials;
    webClient.Credentials = credentials;
}

This grabs credentials from 'Credentials Manager' - which can be found via Windows - click Start then search for 'Credentials Manager'. Credentials for the proxy that were manually entered when prompted by the browser will be in the Windows Credentials section.

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

How to ping ubuntu guest on VirtualBox

If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces still configured for eth0.

Diagnose:

ethtool -i eth0
Cannot get driver information: no such device

Find your interfaces:

ls /sys/class/net
eth1 eth2 lo

Fix it:

Edit /etc/networking/interfaces and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)

:%s/eth0/eth2/g

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

WPF loading spinner

You can do it without any additional controls and libraries, using only Image control and transform:

<Image
    Source="/images/spinner.png"
    Width="100"
    Height="100"
    RenderTransformOrigin="0.5, 0.5" Visibility="{Binding IsLoading, Converter={StaticResource BooleanToVisibilityConverter}}">
    <Image.RenderTransform>
        <RotateTransform x:Name="noFreeze" />
    </Image.RenderTransform>
    <Image.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation
                        Storyboard.TargetProperty="(Image.RenderTransform).(RotateTransform.Angle)"
                        To="360" Duration="0:0:1" RepeatBehavior="Forever" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Image.Triggers>
</Image>

Replace /images/spinner.png with your image. Change To="360" to To="-360" if you want to rotate it counterclockwise. Duration="0:0:1" equals to 1 second per rotation.

How to check if the string is empty?

The most elegant way would probably be to simply check if its true or falsy, e.g.:

if not my_string:

However, you may want to strip white space because:

 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.

Bootstrap : TypeError: $(...).modal is not a function

I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using

$('#button').on('click',function(){ $('#myModal').modal(); });

myModal is the id of Bootstrap modal and you have to give a click event to a button when you call click that button a pop up modal will be displayed.

What is the App_Data folder used for in Visual Studio?

The intended use for App_Data is to store database related file. Usually SQL Server Express .mdf files.

Text-decoration: none not working

a:link{
  text-decoration: none!important;
}

=> Working with me :) , good luck

Explaining the 'find -mtime' command

The POSIX specification for find says:

-mtimen The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.

Interestingly, the description of find does not further specify 'initialization time'. It is probably, though, the time when find is initialized (run).

In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:

+n More than n.
  n Exactly n.
-n Less than n.

At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):

1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00

so:

1409547224 - 1409457540 = 89684
89684 / 86400 = 1

Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).

The n value calculated for the 2014-08-30 log file therefore is exactly 1 (the calculation is done with integer arithmetic), and the +1 rejects it because it is strictly a > 1 comparison (and not >= 1).

Matplotlib: Specify format of floats for tick labels

If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:

from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places

From the documentation:

class matplotlib.ticker.StrMethodFormatter(fmt)

Use a new-style format string (as used by str.format()) to format the tick.

The field used for the value must be labeled x and the field used for the position must be labeled pos.

Windows command for file size only

Since you're using Windows XP, Windows PowerShell is an option.

(Get-Item filespec ).Length 

or as a function

function Get-FileLength { (Get-Item $args).Length }
Get-FileLength filespec

Android, How to limit width of TextView (and add three dots at the end of text)?

        <TextView
            android:id="@+id/product_description"
            android:layout_width="165dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:paddingLeft="12dp"
            android:paddingRight="12dp"
            android:text="Pack of 4 summer printed pajama"
            android:textColor="#d2131c"
            android:textSize="12sp"
            android:maxLines="2"
            android:ellipsize="end"/>

Getting the SQL from a Django QuerySet

Easy:

print my_queryset.query

For example:

from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

ImportError: No module named MySQLdb

yum install MySQL-python.x86_64

worked for me.

Difference between Static and final?

I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.

static is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static blocks but I would not worry about it for a start.

final has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.

Operation is not valid due to the current state of the object, when I select a dropdown list

From http://codecorner.galanter.net/2012/06/04/solution-for-operation-is-not-valid-due-to-the-current-state-of-the-object-error/

Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.

This can be done in your application Web.Config in the <appSettings> section (create the section directly under <configuration> if it doesn’t exist). Add 2 lines similar to the lines below to the section:

<add key="aspnet:MaxHttpCollectionKeys" value="2000" />
<add key="aspnet:MaxJsonDeserializerMembers" value="2000" />

The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

This is resolved. The problem was elsewhere. Another code in cron job was truncating XML to 0 length file. I have taken care of that.

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

My favorite slow sorting algorithm is the stooge sort:

void stooges(long *begin, long *end) {
   if( (end-begin) <= 1 ) return;
   if( begin[0] < end[-1] ) swap(begin, end-1);
   if( (end-begin) > 1 ) {
      int one_third = (end-begin)/3;
      stooges(begin, end-one_third);
      stooges(begin+one_third, end);
      stooges(begin, end-one_third);
   }
}

The worst case complexity is O(n^(log(3) / log(1.5))) = O(n^2.7095...).

Another slow sorting algorithm is actually named slowsort!

void slow(long *start, long *end) {
   if( (end-start) <= 1 ) return;
   long *middle = start + (end-start)/2;
   slow(start, middle);
   slow(middle, end);
   if( middle[-1] > end[-1] ) swap(middle-1, end-1);
   slow(start, end-1);
}

This one takes O(n ^ (log n)) in the best case... even slower than stoogesort.

Checking if a string can be converted to float in Python

TL;DR:

  • If your input is mostly strings that can be converted to floats, the try: except: method is the best native Python method.
  • If your input is mostly strings that cannot be converted to floats, regular expressions or the partition method will be better.
  • If you are 1) unsure of your input or need more speed and 2) don't mind and can install a third-party C-extension, fastnumbers works very well.

There is another method available via a third-party module called fastnumbers (disclosure, I am the author); it provides a function called isfloat. I have taken the unittest example outlined by Jacob Gabrielson in this answer, but added the fastnumbers.isfloat method. I should also note that Jacob's example did not do justice to the regex option because most of the time in that example was spent in global lookups because of the dot operator... I have modified that function to give a fairer comparison to try: except:.


def is_float_try(str):
    try:
        float(str)
        return True
    except ValueError:
        return False

import re
_float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$").match
def is_float_re(str):
    return True if _float_regexp(str) else False

def is_float_partition(element):
    partition=element.partition('.')
    if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):
        return True
    else:
        return False

from fastnumbers import isfloat


if __name__ == '__main__':
    import unittest
    import timeit

    class ConvertTests(unittest.TestCase):

        def test_re_perf(self):
            print
            print 're sad:', timeit.Timer('ttest.is_float_re("12.2x")', "import ttest").timeit()
            print 're happy:', timeit.Timer('ttest.is_float_re("12.2")', "import ttest").timeit()

        def test_try_perf(self):
            print
            print 'try sad:', timeit.Timer('ttest.is_float_try("12.2x")', "import ttest").timeit()
            print 'try happy:', timeit.Timer('ttest.is_float_try("12.2")', "import ttest").timeit()

        def test_fn_perf(self):
            print
            print 'fn sad:', timeit.Timer('ttest.isfloat("12.2x")', "import ttest").timeit()
            print 'fn happy:', timeit.Timer('ttest.isfloat("12.2")', "import ttest").timeit()


        def test_part_perf(self):
            print
            print 'part sad:', timeit.Timer('ttest.is_float_partition("12.2x")', "import ttest").timeit()
            print 'part happy:', timeit.Timer('ttest.is_float_partition("12.2")', "import ttest").timeit()

    unittest.main()

On my machine, the output is:

fn sad: 0.220988988876
fn happy: 0.212214946747
.
part sad: 1.2219619751
part happy: 0.754667043686
.
re sad: 1.50515985489
re happy: 1.01107215881
.
try sad: 2.40243887901
try happy: 0.425730228424
.
----------------------------------------------------------------------
Ran 4 tests in 7.761s

OK

As you can see, regex is actually not as bad as it originally seemed, and if you have a real need for speed, the fastnumbers method is quite good.

How to make a phone call programmatically?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
   final Button button = (Button) findViewById(R.id.btn_call);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String mobileNo = "123456789";
            String uri = "tel:" + mobileNo.trim();
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse(uri));
            startActivity(intent);
        }
    });*
 }

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Model::where('column_1','=','value_1')->where('column_2 ','=','value_2')->get();

OR

// If you are looking for equal value then no need to add =
Model::where('column_1','value_1')->where('column_2','value_2')->get();

OR

Model::where(['column_1' => 'value_1','column_2' => 'value_2'])->get();

Check string for palindrome

A concise version, that doesn't involve (inefficiently) initializing a bunch of objects:

boolean isPalindrome(String str) {    
    int n = str.length();
    for( int i = 0; i < n/2; i++ )
        if (str.charAt(i) != str.charAt(n-i-1)) return false;
    return true;    
}

How do I connect to a Websphere Datasource with a given JNDI name?

To get a connection from a data source, the following code should work:

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

Context ctx = new InitialContext();
DataSource dataSource = ctx.lookup("java:comp/env/jdbc/xxxx");
Connection conn = dataSource.getConnection();

// use the connection

conn.close();

While you can look up a data source as defined in the Websphere Data Sources config (i.e. through the websphere console) directly, the lookup from java:comp/env/jdbc/xxxx means that there needs to be an entry in web.xml:

<resource-ref>
    <res-ref-name>jdbc/xxxx</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

This means that data sources can be mapped on a per application bases and you don't need to change the name of the data source if you want to point your app to a different data source. This is useful when deploying the application to different servers (e.g. test, preprod, prod) which need to point to different databases.

How to extend an existing JavaScript array with another array, without creating a new array

You should use a loop-based technique. Other answers on this page that are based on using .apply can fail for large arrays.

A fairly terse loop-based implementation is:

Array.prototype.extend = function (other_array) {
    /* You should include a test to check whether other_array really is an array */
    other_array.forEach(function(v) {this.push(v)}, this);
}

You can then do the following:

var a = [1,2,3];
var b = [5,4,3];
a.extend(b);

DzinX's answer (using push.apply) and other .apply based methods fail when the array that we are appending is large (tests show that for me large is > 150,000 entries approx in Chrome, and > 500,000 entries in Firefox). You can see this error occurring in this jsperf.

An error occurs because the call stack size is exceeded when 'Function.prototype.apply' is called with a large array as the second argument. (MDN has a note on the dangers of exceeding call stack size using Function.prototype.apply - see the section titled "apply and built-in functions".)

For a speed comparison with other answers on this page, check out this jsperf (thanks to EaterOfCode). The loop-based implementation is similar in speed to using Array.push.apply, but tends to be a little slower than Array.slice.apply.

Interestingly, if the array you are appending is sparse, the forEach based method above can take advantage of the sparsity and outperform the .apply based methods; check out this jsperf if you want to test this for yourself.

By the way, do not be tempted (as I was!) to further shorten the forEach implementation to:

Array.prototype.extend = function (array) {
    array.forEach(this.push, this);
}

because this produces garbage results! Why? Because Array.prototype.forEach provides three arguments to the function it calls - these are: (element_value, element_index, source_array). All of these will be pushed onto your first array for every iteration of forEach if you use "forEach(this.push, this)"!

Add a CSS class to <%= f.submit %>

As Srdjan Pejic says, you can use

<%= f.submit 'name', :class => 'button' %>

or the new syntax which would be:

<%= f.submit 'name', class: 'button' %>

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

Set output of a command as a variable (with pipes)

You can set the output to a temporary file and the read the data from the file after that you can delete the temporary file.

echo %date%>temp.txt
set /p myVarDate= < temp.txt
echo Date is %myVarDate%
del temp.txt

In this variable myVarDate contains the output of command.

How can I get npm start at a different directory?

I came here from google so it might be relevant to others: for yarn you could use:

yarn --cwd /path/to/your/app run start 

How to convert an array of strings to an array of floats in numpy?

Another option might be numpy.asarray:

import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=np.float64, order='C')

For Python 2*:

print a, type(a), type(a[0])
print b, type(b), type(b[0])

resulting in:

['1.1', '2.2', '3.2'] <type 'list'> <type 'str'>
[1.1 2.2 3.2] <type 'numpy.ndarray'> <type 'numpy.float64'>

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

Changing tab bar item image and text color iOS

Swift 4.2 and Xcode 10

The solution that worked for me:

  1. Image setup - from the storyboard set Bar Item Image and Selected Image. To remove the tint overlay on the images go to Assets catalog, select the image and change its rendering mode like this:

image render mode

This will prevent the Tab bar component from setting its default image tint.

  1. Text - here I created a simple UITabBarController subclass and in its viewDidLoad method I customized the default and selected text color like this:

    class HomeTabBarController: UITabBarController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let appearance = UITabBarItem.appearance(whenContainedInInstancesOf: [HomeTabBarController.self])
            appearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: .black], for: .normal)
            appearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: .red], for: .selected)
        }
    }
    

Just set this class as your Tab bar controller custom class in identity inspector in IB.

Voila! That's it.

iOS 13 Update:

Add this to your setup for iOS 13:

if #available(iOS 13, *) {
    let appearance = UITabBarAppearance()
    appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: .red]
    tabBar.standardAppearance = appearance
}

How do I "select Android SDK" in Android Studio?

In my case there there is no selected java sdk version in project structure-

I had to select the -

1.Source Compatibility (1.7)

2.Target Compatibility (1.7)

as shown in image.

enter image description here

How to declare a vector of zeros in R

replicate is another option:

replicate(10, 0)
# [1] 0 0 0 0 0 0 0 0 0 0

replicate(5, 1)
# [1] 1 1 1 1 1

To create a matrix:

replicate( 5, numeric(3) )

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    0    0
#[2,]    0    0    0    0    0
#[3,]    0    0    0    0    0

CodeIgniter Active Record - Get number of returned rows

If you only need the number of rows in a query and don't need the actual row data, use count_all_results

echo $this->db
       ->where('active',1)
       ->count_all_results('table_name');

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

other useful threads

https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

How to allow only numeric (0-9) in HTML inputbox using jQuery?

It may be overkill for what you are looking for, yet I suggest a jQuery plugin called autoNumeric() - it is great!

You can limit to only numbers, decimal precision, max / min values and more.

http://www.decorplanit.com/plugin/

Having the output of a console application in Visual Studio instead of the console

You could create a wrapper application that you run instead of directly running your real app. The wrapper application can listen to stdout and redirect everything to Trace. Then change the run settings to launch your wrapper and pass in the path to the real app to run.

You could also have the wrapper auto-attach the debugger to the new process if a debugger is attached to the wrapper.

Is there a way to include commas in CSV columns without breaking the formatting?

You need to quote that values.
Here is a more detailed spec.

Foreach loop in C++ equivalent of C#

using C++ 14:

#include <string>
#include <vector>


std::vector<std::string> listbox;
...
std::vector<std::string> strarr {"ram","mohan","sita"};    
for (const auto &str : strarr)
{
    listbox.push_back(str);
}

Angular 2 'component' is not a known element

This question may seem old and odd, but when I was trying to load a module(lazy loading) and getting the same error, I realized I was missing an exports clause for the component that shipped as a part of a larger module.

This Angular.io Link explains why: Components/Services inside a module, remains private(or protected) by default. To make them public, you have to export them.

Expanding on @Robin Djikof's answer with @live-love code sample, this is what was technically missing in my case(Angular 8):

@NgModule({
  declarations: [
    SomeOtherComponent,
    ProductListComponent
  ],
  imports: [
    DependantModule
  ],
  exports: [ProductListComponent] 
  //<- This line makes ProductListComponent available outside the module, 
  //while keeping SomeOtherComponent private to the module
})
export class SomeLargeModule { }

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

Be careful, in some cases clicking on a Form Control or Active X Control will give two different results for the same macro - which should not be the case. I find Active X more reliable.

Unity Scripts edited in Visual studio don't provide autocomplete

  • Go to Options on the Tools menu and then select Documents in the Environment node. (If Documents does not appear in the list, select Show all settings in the Options dialog box.)
  • Put a tick on "Miscellaneous files in Solution Explorer" and Click OK. (This option displays the "Miscellaneous Files" node in Solution Explorer. Miscellaneous files are files that are not associated with a project or solution but can appear in Solution Explorer for your convenience if you tick this option.)
  • Locate your file in the Solution Explorer under "Miscellaneous Files". Then drag and drop your file to where it should belong and voila! This will copy the file to where you drop it. You may now safely delete the older file under Miscellaneous Files folder if you wish to do so

Credits: https://stackoverflow.com/a/47662523/10471480


In case Scripts folder is not visible:

  • Click on "Show all files" in Solution Explorer
  • Locate the Scripts folder.
  • Right Click on Scripts and select "Include in Project"

Bootstrap 3 Horizontal Divider (not in a dropdown)

Yes there is, you can simply put <hr> in your code where you want it, I already use it in one of my admin panel side bar.

document.getElementById replacement in angular4 / typescript?

You can tag your DOM element using #someTag, then get it with @ViewChild('someTag').

See complete example:

import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';

@Component({
    selector: 'app',
    template: `
        <div #myDiv>Some text</div>
    `,
})
export class AppComponent implements AfterViewInit {
    @ViewChild('myDiv') myDiv: ElementRef;

    ngAfterViewInit() {
        console.log(this.myDiv.nativeElement.innerHTML);
    }
}

console.log will print Some text.

Remove Array Value By index in jquery

Your example code is wrong and will throw a SyntaxError. You seem to have confused the syntax of creating an object Object with creating an Array.

The correct syntax would be: var arr = [ "abc", "def", "ghi" ];

To remove an item from the array, based on its value, use the splice method:

arr.splice(arr.indexOf("def"), 1);

To remove it by index, just refer directly to it:

arr.splice(1, 1);

Android TextView Text not getting wrapped

I'm an Android (and GUI) beginner, but have lots of experience with software. I've gone through a few of the tutorials, and this is my understanding:

layout_width and layout_height are attributes of the TextView. They are instructions for how the TextView should shape itself, they aren't referring to how to handle the content within the TextView.

If you use "fill_parent", you are saying that the TextView should shape itself relative to it's parent view, it should fill it.

If you use "wrap_content", you are saying that you should ignore the parent view, and let the contents of the TextView define it's shape.

I think this is the confusing point. "wrap_content" isn't telling the TextView how to manage it's contents (to wrap the lines), it's telling it that it should shape itself relative to it's contents. In this case, with no new line characters, it shapes itself so that all the text is on a single line (which unfortunately is overflowing the parent).

I think you want it to fill the parent horizontally, and to wrap it's contents vertically.

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something