Programs & Examples On #Activemerchant

Active Merchant is an extraction from the e-commerce system Shopify

Gulp command not found after install

I had this problem with getting "command not found" after install but I was installed into /usr/local as described in the solution above.

My problem seemed to be caused by me running the install with sudo. I did the following.

  1. Removing gulp again with sudo
  2. Changing the owner of /usr/local/lib/node_modules to my user
  3. Installing gulp again without sudo. "npm install gulp -g"

Linking to an external URL in Javadoc?

This creates a "See Also" heading containing the link, i.e.:

/**
 * @see <a href="http://google.com">http://google.com</a>
 */

will render as:

See Also:
           http://google.com

whereas this:

/**
 * See <a href="http://google.com">http://google.com</a>
 */

will create an in-line link:

See http://google.com

Disable browsers vertical and horizontal scrollbars

In case you also need support for Internet Explorer 6, just overflow the html

$("html").css("overflow", "hidden");

and

$("html").css("overflow", "auto");

How to find out what character key is pressed?

Try:

_x000D_
_x000D_
<table>_x000D_
<tr><td>Key:</td><td id="key"></td></tr>_x000D_
<tr><td>Key Code:</td><td id="keyCode"></td></tr>_x000D_
<tr><td>Event Code:</td><td id="eventCode"></td></tr>_x000D_
</table>_x000D_
<script type="text/javascript">_x000D_
window.addEventListener("keydown", function (e) {_x000D_
  //tested in IE/Chrome/Firefox_x000D_
  document.getElementById("key").innerHTML = e.key;_x000D_
  document.getElementById("keyCode").innerHTML = e.keyCode;_x000D_
  document.getElementById("eventCode").innerHTML = e.code;_x000D_
})_x000D_
</script>
_x000D_
_x000D_
_x000D_

*Note: this works in "Run code snippet"

This website does the same as my code above: Keycode.info

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Best way to combine two or more byte arrays in C#

Concat is the right answer, but for some reason a handrolled thing is getting the most votes. If you like that answer, perhaps you'd like this more general solution even more:

    IEnumerable<byte> Combine(params byte[][] arrays)
    {
        foreach (byte[] a in arrays)
            foreach (byte b in a)
                yield return b;
    }

which would let you do things like:

    byte[] c = Combine(new byte[] { 0, 1, 2 }, new byte[] { 3, 4, 5 }).ToArray();

Adding external library into Qt Creator project

If you want to deploy your application on machines of customers, rather than using your application only yourself, we find that the LIBS+= -Lxxx -lyyy method can lead to confusion if not problems.

We develop applications for Linux, Mac and Windows using Qt. We ship complete, stand-alone applications. So all non-system libraries should be included in the deployment package. We want our customers to be able to run the application from the same USB stick for all OSs. For reasons of platform compatibility the USB stick must then be formatted as FAT32, which does not support (Linux) symlinks.

We found the LIBS+= -Lxxx -lyyy idiom too much of a black box:

  1. We do not exactly know what the filepath is of the (static or dynamic) library that has been found by the linker. This is inconvenient. Our Mac linker regularly found libs different from the ones we thought that should be used. This happened several times with OpenSSL libraries where the Mac linker found and used its own - older, incompatible - OpenSSL version rather than our requested version.

  2. We cannot afford that the linker uses symlinks to libraries as this would break the deployment package.

  3. We want to see from the name of the library whether we link a static or a dynamic library.

So for our particular case we use only absolute filepaths and check whether they exist. We remove all symlinks.

First we find out what operating system we are using and put this in the CONFIG variable. And, for instance for Linux 64bit, then:

linux64 {
    LIBSSL= $$OPENSSLPATH/linux64/lib/libssl.a
    !exists($$LIBSSL): error ("Not existing $$LIBSSL")
    LIBS+= $$LIBSSL
    LIBCRYPTO= $$OPENSSLPATH/linux64/lib/libcrypto.a
    !exists($$LIBCRYPTO): error ("Not existing $$LIBCRYPTO")
    LIBS+= $$LIBCRYPTO
}

All the dependencies can be copied into deployment package as we know their filepaths.

Domain Account keeping locking out with correct password every few minutes

May be the virus by name CONFLICKER try d.exe tool from symantec on the machine hope your problem will be resolved. Check the security logs in domain controller and scan those machines because of this virus it creates bad passwords and lock the users.

What is the best method of handling currency/money?

I am using it on this way:

number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")

Of course that the currency symbol, precision, format and so on depends on each currency.

Regular expression to remove HTML tags from a string

A trivial approach would be to replace

<[^>]*>

with nothing. But depending on how ill-structured your input is that may well fail.

How do I finish the merge after resolving my merge conflicts?

After all files have been added, the next step is a "git commit".

"git status" will suggest what to do: files yet to add are listed at the bottom, and once they are all done, it will suggest a commit at the top, where it explains the merge status of the current branch.

Generating random, unique values C#

I'm calling NewNumber() regularly, but the problem is I often get repeated numbers.

Random.Next doesn't guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list of int and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:

public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode());
                                // Since similar code is done in default constructor internally
public List<int> randomList = new List<int>();
int MyNumber = 0;
private void NewNumber()
{
    MyNumber = a.Next(0, 10);
    if (!randomList.Contains(MyNumber))
        randomList.Add(MyNumber);
}

Replace None with NaN in pandas dataframe

The following line replaces None with NaN:

df['column'].replace('None', np.nan, inplace=True)

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

Node.js - EJS - including a partial

In oficial documentation https://github.com/mde/ejs#includes show that includes works like that:

<%- include('../partials/head') %>

Node.js on multi-core machines

It's possible to scale NodeJS out to multiple boxes using a pure TCP load balancer (HAProxy) in front of multiple boxes running one NodeJS process each.

If you then have some common knowledge to share between all instances you could use a central Redis store or similar which can then be accessed from all process instances (e.g. from all boxes)

Accessing Websites through a Different Port?

You can use ssh to forward ports onto somewhere else.

If you have two computers, one you browse from, and one which is free to access websites, and is not logged (ie. you own it and it's sitting at home), then you can set up a tunnel between them to forward http traffic over.

For example, I connect to my home computer from work using ssh, with port forwarding, like this:

ssh -L 22222:<target_website>:80 <home_computer>

Then I can point my browser to

http://localhost:22222/

And this request will be forwarded over ssh. Since the work computer is first contacting the home computer, and then contacting the target website, it will be hard to log.

However, this is all getting into 'how to bypass web proxies' and the like, and I suggest you create a new question asking what exactly you want to do.

Ie. "How do I bypass web proxies to avoid my traffic being logged?"

What's a simple way to get a text input popup dialog box on an iPhone

Try this Swift code in a UIViewController -

func doAlertControllerDemo() {

    var inputTextField: UITextField?;

    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);

    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)

        let entryStr : String = (inputTextField?.text)! ;

        print("BOOM! I received '\(entryStr)'");

        self.doAlertViewDemo(); //do again!
    }));


    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        print("done");
    }));


    passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.secureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });


    self.presentViewController(passwordPrompt, animated: true, completion: nil);


    return;
}

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

3D Plotting from X, Y, Z Data, Excel or other Tools

You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:

      13    21   29      37    45   
1000  75.2                              
1000       79.21                            
1000             80.02                      
5000             87.9                   
5000                    88.54               
5000                           88.56            
10000            90.11      
10000                   90.79   
10000                          90.87

Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.

The best 3D representation that Excel will give you of the above data is pretty confusing:

enter image description here

Representing this limited dataset as 2D data might be a better choice:

enter image description here

As a note for future reference, these types of questions usually do a little better on superuser.com.

Android fade in and fade out with ImageView

I used used fadeIn animation to replace new image for old one

ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();

How can I parse a YAML file in Python

The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml:

#!/usr/bin/env python

import yaml

with open("example.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

And that's it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.

Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Delete files older than 15 days using PowerShell

Esperento57's script doesn't work in older PowerShell versions. This example does:

Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt  (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue

CSS '>' selector; what is it?

As others have said, it's a direct child, but it's worth noting that this is different to just leaving a space... a space is for any descendant.

<div>
  <span>Some text</span>
</div>

div>span would match this, but it would not match this:

<div>
  <p><span>Some text</span></p>
</div>

To match that, you could do div>p>span or div span.

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Swift extract regex matches

If you want to extract substrings from a String, not just the position, (but the actual String including emojis). Then, the following maybe a simpler solution.

extension String {
  func regex (pattern: String) -> [String] {
    do {
      let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0))
      let nsstr = self as NSString
      let all = NSRange(location: 0, length: nsstr.length)
      var matches : [String] = [String]()
      regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {
        (result : NSTextCheckingResult?, _, _) in
        if let r = result {
          let result = nsstr.substringWithRange(r.range) as String
          matches.append(result)
        }
      }
      return matches
    } catch {
      return [String]()
    }
  }
} 

Example Usage:

"someText ?? pig".regex("??")

Will return the following:

["??"]

Note using "\w+" may produce an unexpected ""

"someText ?? pig".regex("\\w+")

Will return this String array

["someText", "?", "pig"]

How to execute an oracle stored procedure?

Execute is sql*plus syntax .. try wrapping your call in begin .. end like this:

begin 
    temp_proc;
end;

(Although Jeffrey says this doesn't work in APEX .. but you're trying to get this to run in SQLDeveloper .. try the 'Run' menu there.)

Cannot access wamp server on local network

I had the same issue, tried all nothing works, following works for me

Following is what i had

#onlineoffline tag - don't remove

Require local

Change to

Require all granted
Order Deny,Allow
Allow from all

Is there a way to 'uniq' by column?

awk -F"," '!_[$1]++' file
  • -F sets the field separator.
  • $1 is the first field.
  • _[val] looks up val in the hash _(a regular variable).
  • ++ increment, and return old value.
  • ! returns logical not.
  • there is an implicit print at the end.

Why can I ping a server but not connect via SSH?

On the server, try:

netstat -an 

and look to see if tcp port 22 is opened (use findstr in Windows or grep in Unix).

Open application after clicking on Notification

See below code. I am using that and it is opening my HomeActivity.

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    Intent notificationIntent = new Intent(context, HomeActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);

What does "O(1) access time" mean?

The easiest way to differentiate O(1) and O(n) is comparing array and list.

For array, if you have the right index value, you can access the data instantly. (If you don't know the index and have to loop through the array, then it won't be O(1) anymore)

For list, you always need to loop through it whether you know the index or not.

How can I debug git/git-shell related problems?

If its over SSH, you can use the following:

For a higher debug level for type -vv or -vvv for debug level 2 and 3 respectively:

# Debug level 1
GIT_SSH_COMMAND="ssh -v" git clone <repositoryurl>

# Debug level 2
GIT_SSH_COMMAND="ssh -vv" git clone <repositoryurl>

# Debug level 3
GIT_SSH_COMMAND="ssh -vvv" git clone <repositoryurl>

This is mainly useful to handle public and private key problems with the server. You can use this command for any git command, not only 'git clone'.

CodeIgniter 500 Internal Server Error

Try this to your .htaccess file:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >

Foreign Key naming scheme

I usually just leave my PK named id, and then concatenate my table name and key column name when naming FKs in other tables. I never bother with camel-casing, because some databases discard case-sensitivity and simply return all upper or lower case names anyway. In any case, here's what my version of your tables would look like:

task (id, userid, title);
note (id, taskid, userid, note);
user (id, name);

Note that I also name my tables in the singular, because a row represents one of the objects I'm persisting. Many of these conventions are personal preference. I'd suggest that it's more important to choose a convention and always use it, than it is to adopt someone else's convention.

PHP date() with timezone?

The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);

echo $dt->format('F j, Y @ G:i');

Is there a MySQL option/feature to track history of changes to records?

Here is how we solved it

a Users table looked like this

Users
-------------------------------------------------
id | name | address | phone | email | created_on | updated_on

And the business requirement changed and we were in a need to check all previous addresses and phone numbers a user ever had. new schema looks like this

Users (the data that won't change over time)
-------------
id | name

UserData (the data that can change over time and needs to be tracked)
-------------------------------------------------
id | id_user | revision | city | address | phone | email | created_on
 1 |   1     |    0     | NY   | lake st | 9809  | @long | 2015-10-24 10:24:20
 2 |   1     |    2     | Tokyo| lake st | 9809  | @long | 2015-10-24 10:24:20
 3 |   1     |    3     | Sdny | lake st | 9809  | @long | 2015-10-24 10:24:20
 4 |   2     |    0     | Ankr | lake st | 9809  | @long | 2015-10-24 10:24:20
 5 |   2     |    1     | Lond | lake st | 9809  | @long | 2015-10-24 10:24:20

To find the current address of any user, we search for UserData with revision DESC and LIMIT 1

To get the address of a user between a certain period of time we can use created_on bewteen (date1 , date 2)

Checking the form field values before submitting that page

You can simply make the start_date required using

<input type="submit" value="Submit" required />

You don't even need the checkform() then.

Thanks

Flutter - Layout a Grid

Use whichever suits your need.

  1. GridView.count(...)

    GridView.count(
      crossAxisCount: 2,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  2. GridView.builder(...)

    GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (_, index) => FlutterLogo(),
      itemCount: 4,
    )
    
  3. GridView(...)

    GridView(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  4. GridView.custom(...)

    GridView.custom(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      childrenDelegate: SliverChildListDelegate(
        [
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
        ],
      ),
    )
    
  5. GridView.extent(...)

    GridView.extent(
      maxCrossAxisExtent: 400,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    

Output (same for all):

enter image description here

How do I set a VB.Net ComboBox default value

Much simpler solution, Select the Combo-box, and in the option of Selected item, select the item index (0 for the first item) and set it to be the default value in the combo box.

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

Replacing .NET WebBrowser control with a better browser, like Chrome?

UPDATE 2020 JULY

Preview version of chromium based WebView 2 is released by the Microsoft. Now you can embed new Chromium Edge browser into a .NET application.

UPDATE 2018 MAY

If you're targeting application to run on Windows 10, then now you can embed Edge browser into your .NET application by using Windows Community Toolkit.

WPF Example:

  1. Install Windows Community Toolkit Nuget Package

    Install-Package Microsoft.Toolkit.Win32.UI.Controls
    
  2. XAML Code

    <Window
        x:Class="WebViewTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Win32.UI.Controls.WPF;assembly=Microsoft.Toolkit.Win32.UI.Controls"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WebViewTest"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="800"
        Height="450"
        mc:Ignorable="d">
        <Grid>
            <WPF:WebView x:Name="wvc" />
        </Grid>
    </Window>
    
  3. CS Code:

    public partial class MainWindow : Window
    {
      public MainWindow()
      {
        InitializeComponent();
    
        // You can also use the Source property here or in the WPF designer
        wvc.Navigate(new Uri("https://www.microsoft.com"));
      }
    }
    

WinForms Example:

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();

    // You can also use the Source property here or in the designer
    webView1.Navigate(new Uri("https://www.microsoft.com"));
  }
}

Please refer to this link for more information.

how to add script src inside a View when using Layout

You can add the script tags like how we use in the asp.net while doing client side validations like below.

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $(function () {
       //Your code
    });
</script>

How do I use StringUtils in Java?

StringUtils is an Apache Commons project. You need to download and add the library to your classpath.

To use:

import org.apache.commons.lang3.StringUtils;

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

how to use sqltransaction in c#

The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection 
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction. 
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred 
                // on the server that would cause the rollback to fail, such as 
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}

See SqlTransaction Class

$(this).val() not working to get text from span using jquery

Instead of .val() use .text(), like this:

$(".ui-datepicker-month").live("click", function () {
    var monthname =  $(this).text();
    alert(monthname);
});

Or in jQuery 1.7+ use on() as live is deprecated:

$(document).on('click', '.ui-datepicker-month', function () {
    var monthname =  $(this).text();
    alert(monthname);
});

.val() is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use .text() here.

is it possible to evenly distribute buttons across the width of an android linearlayout

In linearLayout Instead of giving weight to Button itself , set the weight to <Space> View this won't stretch the Button.

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.955">

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="@drawable/ic_baseline_arrow_back_24" />

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:id="@+id/captureButton"
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:background="@drawable/ic_round_camera_24" />

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:id="@+id/cameraChangerBtn"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="@drawable/ic_round_switch_camera_24" />

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>

as I am using 4 <Space> I set the android:weightSum="4" In linear layout also this is the result ::

layout preview

What is the difference between Sessions and Cookies in PHP?

Session

Session is used for maintaining a dialogue between server and user. It is more secure because it is stored on the server, we cannot easily access it. It embeds cookies on the user computer. It stores unlimited data.

Cookies

Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session. It stores limited amount of data, and is maintained for a limited time.

casting int to char using C++ style casting

You can implicitly convert between numerical types, even when that loses precision:

char c = i;

However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast for the conversion.

Of the other casts:

  • dynamic_cast only works for pointers or references to polymorphic class types;
  • const_cast can't change types, only const or volatile qualifiers;
  • reinterpret_cast is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.
  • C-style and function-style casts do whatever combination of static_cast, const_cast and reinterpret_cast is needed to get the job done.

How to randomize (shuffle) a JavaScript array?

Here is the EASIEST one,

function shuffle(array) {
  return array.sort(() => Math.random() - 0.5);
}

for further example, you can check it here

Change remote repository credentials (authentication) on Intellij IDEA 14

You can change your password from settings screen (Ctrl + Alt + S by default) as attached screenshot. After clearing, on the firts remote operation (like pull/push, etc.) it'll ask you your credentials)

IMPORTANT: Take a copy of the file before this operation.

Settings Screen

mysql is not recognised as an internal or external command,operable program or batch

In my case, I resolved it by adding this path C:\xampp\mysql\bin to system variables path and then restarted pash/cmd.

Note: Click me if you don't know how to set the path and system variables.

Remove Last Comma from a string

you can remove last comma:

var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);

General error: 1364 Field 'user_id' doesn't have a default value

So, after After reviewing the code again, I found the error. I am wondering how no one notice that! In the above code I wrote

Post::create(request([  // <= the error is Here!!!
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => auth()->id()
]));

actually, there is no need for the request function warping the body of the create function.

// this is right
Post::create([
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => auth()->id()
]);

Best way to convert strings to symbols in hash

In Ruby >= 2.5 (docs) you can use:

my_hash.transform_keys(&:to_sym)

Using older Ruby version? Here is a one-liner that will copy the hash into a new one with the keys symbolized:

my_hash = my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

With Rails you can use:

my_hash.symbolize_keys
my_hash.deep_symbolize_keys 

What is the proper use of an EventEmitter?

TL;DR:

No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.

Answer:

No, you should not subscribe manually to it.

EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald

[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.

This is stated really clear in EventEmitter's documentation.

Use by directives and components to emit custom Events.

What's wrong about using it?

Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit() method. We should never subscribe manually to an EventEmitter.

All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference

Do NOT count on EventEmitter continuing to be an Observable!

Do NOT count on those Observable operators being there in the future!

These will be deprecated soon and probably removed before release.

Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call eve.emit()

His comment is in line with Rob's comment long time ago.

So, how to use it properly?

Simply use it to emit events from your component. Take a look a the following example.

@Component({
    selector : 'child',
    template : `
        <button (click)="sendNotification()">Notify my parent!</button>
    `
})
class Child {
    @Output() notifyParent: EventEmitter<any> = new EventEmitter();
    sendNotification() {
        this.notifyParent.emit('Some value to send to the parent');
    }
}

@Component({
    selector : 'parent',
    template : `
        <child (notifyParent)="getNotification($event)"></child>
    `
})
class Parent {
    getNotification(evt) {
        // Do something with the notification (evt) sent by the child!
    }
}

How not to use it?

class MyService {
    @Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}

Stop right there... you're already wrong...

Hopefully these two simple examples will clarify EventEmitter's proper usage.

Get the latest date from grouped MySQL data

This should work:

SELECT model, date FROM doc GROUP BY model ORDER BY date DESC

It just sort the dates from last to first and by grouping it only grabs the first one.

Storing a Key Value Array into a compact JSON string

So why don't you simply use a key-value literal?

var params = {
    'slide0001.html': 'Looking Ahead',
    'slide0002.html': 'Forecase',
    ...
};

return params['slide0001.html']; // returns: Looking Ahead

Show Youtube video source into HTML5 video tag?

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

What is a good practice to check if an environmental variable exists or not?

My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R

'USERNAME' %in% names(Sys.getenv())

How to find text in a column and saving the row number where it is first found - Excel VBA

Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....

and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...

Read url to string in few lines of java code

If your url is of type java.net.URL, then you can just convert it to uri and then to string

url.toURI().toString()

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

Jonty, I'm struggling with this too.

I think there's a clue in here:

otool -L /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

/Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle:
    /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/libruby.1.dylib (compatibility version 1.8.0, current version 1.8.7)
    libmysqlclient.16.dylib (compatibility version 16.0.0, current version 16.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)

Notice the path to the dylib is, uh, rather short?

I'm trying to figure out where the gem install instructions are leaving off the dylib path, but it's slow going as I have never built a gem myself.

I'll post more if I find more!

Convert JSON String To C# Object

Copy your Json and paste at textbox on json2csharp and click on Generate button.

A cs class will be generated use that cs file as below

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

Where RootObject is the name of the generated cs file;

Why catch and rethrow an exception in C#?

C# (before C# 6) doesn't support CIL "filtered exceptions", which VB does, so in C# 1-5 one reason for re-throwing an exception is that you don't have enough information at the time of catch() to determine whether you wanted to actually catch the exception.

For example, in VB you can do

Try
 ..
Catch Ex As MyException When Ex.ErrorCode = 123
 .. 
End Try

...which would not handle MyExceptions with different ErrorCode values. In C# prior to v6, you would have to catch and re-throw the MyException if the ErrorCode was not 123:

try 
{
   ...
}
catch(MyException ex)
{
    if (ex.ErrorCode != 123) throw;
    ...
}

Since C# 6.0 you can filter just like with VB:

try 
{
  // Do stuff
} 
catch (Exception e) when (e.ErrorCode == 123456) // filter
{
  // Handle, other exceptions will be left alone and bubble up
}

Only allow specific characters in textbox

You can probably use the KeyDown event, KeyPress event or KeyUp event. I would first try the KeyDown event I think.

You can set the Handled property of the event args to stop handling the event.

numpy get index where value is true

You can use nonzero function. it returns the nonzero indices of the given input.

Easy Way

>>> (e > 15).nonzero()

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

to see the indices more cleaner, use transpose method:

>>> numpy.transpose((e>15).nonzero())

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

Not Bad Way

>>> numpy.nonzero(e > 15)

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

or the clean way:

>>> numpy.transpose(numpy.nonzero(e > 15))

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

Wampserver icon not going green fully, mysql services not starting up?

This happened to me today. Since I had not changed my system setting since yesterday, I assumed it's predominantly a mysql issue on the system. I managed to fix it in the following way.

  1. Open wampserver's mysql log file. This will contain information on why the service threw and error and exited prematurely.

  2. In my case, the mysql service failed to start because it could not read a certain tablespace. The specific tablespace was indicated in the log.

  3. Failure to read such a file could be because of file permissions or the file being broken. In such a case, mysql stops executing in order to avoid damaging a tablespace file that may be linked to a database you need. Usually, if you have a backup of the database, then it is safe to simply delete this problematic file and restore the database once your mysql service is started again.

  4. If you do not have a database backup then you could force the mysql instance to run a recovery by enabling the option in your my.cnf / my.ini file.

innodb_force_recovery = 1

This forces the instance to run the crash recovery.

NOTE: installing a new instance of mysql does not necessarily mean that your databases shall be retained. I suggest you run a nightly backup of your databases if you are working on huge projects.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

How to generate a random String in Java

Many possibilities...

You know how to generate randomly an integer right? You can thus generate a char from it... (ex 65 -> A)

It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)

HTML 5 Geo Location Prompt in Chrome

if you're hosting behind a server, and still facing issues: try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/

The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).

For my sanity check I was using Remy Sharp's demo: https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html

and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):

"User denied Geolocation"

I made the following change to get more detailed error message:

function error(msg) {
  var s = document.querySelector('#status');
  msg = msg.message ? msg.message : msg; //add this line
  s.innerHTML = typeof msg == 'string' ? msg : "failed";
  s.className = 'fail';

  // console.log(arguments);
}

failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :

"The current location cannot be determined"

Convert Mongoose docs to json

You may also try mongoosejs's lean() :

UserModel.find().lean().exec(function (err, users) {
    return res.end(JSON.stringify(users));
}

onchange file input change img src and change image color

in your HTML : <input type="file" id="yourFile"> don't forget to reference your js file or put the following script between <script></script> in your script :

var fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener("change", function(event) {
    var files = fileToRead.files;
    if (files.length) {
        console.log("Filename: " + files[0].name);
        console.log("Type: " + files[0].type);
        console.log("Size: " + files[0].size + " bytes");
    }

}, false);

How do I trim a file extension from a String in Java?

String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

This command did the trick from @Aniket Sinha's answer above:

pip install mysqlclient

pip install failing with: OSError: [Errno 13] Permission denied on directory

Just clarifying what worked for me after much pain in linux (ubuntu based) on permission denied errors, and leveraging from Bert's answer above, I now use ...

$ pip install --user <package-name>

or if running pip on a requirements file ...

$ pip install --user -r requirements.txt

and these work reliably for every pip install including creating virtual environments.

However, the cleanest solution in my further experience has been to install python-virtualenv and virtualenvwrapper with sudo apt-get install at the system level.

Then, inside virtual environments, use pip install without the --user flag AND without sudo. Much cleaner, safer, and easier overall.

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

How to keep the local file or the remote file during merge using Git and the command line?

For the line-end thingie, refer to man git-merge:

--ignore-space-change 
--ignore-all-space 
--ignore-space-at-eol

Be sure to add autocrlf = false and/or safecrlf = false to the windows clone (.git/config)

Using git mergetool

If you configure a mergetool like this:

git config mergetool.cp.cmd '/bin/cp -v "$REMOTE" "$MERGED"'
git config mergetool.cp.trustExitCode true

Then a simple

git mergetool --tool=cp
git mergetool --tool=cp -- paths/to/files.txt
git mergetool --tool=cp -y -- paths/to/files.txt # without prompting

Will do the job

Using simple git commands

In other cases, I assume

git checkout HEAD -- path/to/myfile.txt

should do the trick

Edit to do the reverse (because you screwed up):

git checkout remote/branch_to_merge -- path/to/myfile.txt

How to change the default message of the required field in the popover of form-control in bootstrap?

$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");

this work if you move to previous or next field by mouse, but by enter key, this is not work !!!

Remove numbers from string sql server

Quoting part of @Jatin answer with some modifications,

use this in your where statement:

    SELECT * FROM .... etc.
        Where 
         REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE (Name, '0', ''),
        '1', ''),
        '2', ''),
        '3', ''),
        '4', ''),
        '5', ''),
        '6', ''),
        '7', ''),
        '8', ''),
        '9', '') = P_SEARCH_KEY

Git: How to check if a local repo is up to date?

If you use

git fetch --dry-run -v <link/to/remote/git/repo>

you'll get feedback about whether it is up-to-date. So basically, you just need to add the "verbose" option to the answer given before.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

Much better to use following:

For is not null:

where('archived IS NOT NULL', null);

For is null:

where('archived', null);

How to have a default option in Angular.js select box

If you are using ng-options to render you drop down than option having same value as of ng-modal is default selected. Consider the example:

<select ng-options="list.key as list.name for list in lists track by list.id" ng-model="selectedItem">

So option having same value of list.key and selectedItem, is default selected.

No resource identifier found for attribute '...' in package 'com.app....'

I just changed:

xmlns:app="http://schemas.android.com/apk/res-auto" 

to:

xmlns:app="http://schemas.android.com/apk/lib/com.app.chasebank"

and it stopped generating the errors, com.app.chasebank is the name of the package. It should work according to this Stack Overflow : No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

How to programmatically tell if a Bluetooth device is connected?

I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:

BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothGatt.GATT);
int status = -1;

for (BluetoothDevice device : devices) {
  status = bm.getConnectionState(device, BLuetoothGatt.GATT);
  // compare status to:
  //   BluetoothProfile.STATE_CONNECTED
  //   BluetoothProfile.STATE_CONNECTING
  //   BluetoothProfile.STATE_DISCONNECTED
  //   BluetoothProfile.STATE_DISCONNECTING
}

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

You may need to add a JDK (Java Development Kit) to the installed JRE's within Eclipse

Go to Window->Preferences->Java->Installed JRE's

In the Name column if you do not have a JDK as your default, then you will need to add it.

Click the "Add" Button and locate the JDK on your machine. You may find it in this location: C:\Program Files\Java\jdk1.x.y
Where x and y are numbers.

If there are no JDK's installed on your machine then download and install the Java SE (Standard Edition) from the Oracle website.

Then do the steps above again. Be sure that it is set as the default JRE to use.

Then go back to the Projects->Generate Javadoc... dialog

Now it should work.

Good Luck.

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

Select all 'tr' except the first one

sounds like the 'first line' you're talking of is your table-header - so you realy should think of using thead and tbody in your markup (click here) which would result in 'better' markup (semantically correct, useful for things like screenreaders) and easier, cross-browser-friendly possibilitys for css-selection (table thead ... { ... })

Use of "global" keyword in Python

This is the difference between accessing the name and binding it within a scope.

If you're just looking up a variable to read its value, you've got access to global as well as local scope.

However if you assign to a variable who's name isn't in local scope, you are binding that name into this scope (and if that name also exists as a global, you'll hide that).

If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.

Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).

>>> a = 1
>>> def p():
    print(a) # accessing global scope, no binding going on
>>> def q():
    a = 3 # binding a name in local scope - hiding global
    print(a)
>>> def r():
    print(a) # fail - a is bound to local scope, but not assigned yet
    a = 4
>>> p()
1
>>> q()
3
>>> r()
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    r()
  File "<pyshell#32>", line 2, in r
    print(a) # fail - a is bound to local scope, but not assigned yet
UnboundLocalError: local variable 'a' referenced before assignment
>>> 

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

What is Express.js?

Express is a module framework for Node that you can use for applications that are based on server/s that will "listen" for any input/connection requests from clients. When you use it in Node, it is just saying that you are requesting the use of the built-in Express file from your Node modules.

Express is the "backbone" of a lot of Web Apps that have their back end in NodeJS. From what I know, its primary asset being the providence of a routing system that handles the services of "interaction" between 2 hosts. There are plenty of alternatives for it, such as Sails.

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

How do I write stderr to a file while using "tee" with a pipe?

I'm assuming you want to still see STDERR and STDOUT on the terminal. You could go for Josh Kelley's answer, but I find keeping a tail around in the background which outputs your log file very hackish and cludgy. Notice how you need to keep an exra FD and do cleanup afterward by killing it and technically should be doing that in a trap '...' EXIT.

There is a better way to do this, and you've already discovered it: tee.

Only, instead of just using it for your stdout, have a tee for stdout and one for stderr. How will you accomplish this? Process substitution and file redirection:

command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)

Let's split it up and explain:

> >(..)

>(...) (process substitution) creates a FIFO and lets tee listen on it. Then, it uses > (file redirection) to redirect the STDOUT of command to the FIFO that your first tee is listening on.

Same thing for the second:

2> >(tee -a stderr.log >&2)

We use process substitution again to make a tee process that reads from STDIN and dumps it into stderr.log. tee outputs its input back on STDOUT, but since its input is our STDERR, we want to redirect tee's STDOUT to our STDERR again. Then we use file redirection to redirect command's STDERR to the FIFO's input (tee's STDIN).

See http://mywiki.wooledge.org/BashGuide/InputAndOutput

Process substitution is one of those really lovely things you get as a bonus of choosing bash as your shell as opposed to sh (POSIX or Bourne).


In sh, you'd have to do things manually:

out="${TMPDIR:-/tmp}/out.$$" err="${TMPDIR:-/tmp}/err.$$"
mkfifo "$out" "$err"
trap 'rm "$out" "$err"' EXIT
tee -a stdout.log < "$out" &
tee -a stderr.log < "$err" >&2 &
command >"$out" 2>"$err"

How to get a MemoryStream from a Stream in .NET?

public static void Do(Stream in)
{
    _ms = new MemoryStream();
    byte[] buffer = new byte[65536];
    while ((int read = input.Read(buffer, 0, buffer.Length))>=0)
        _ms.Write (buffer, 0, read);
}

Send values from one form to another form

Form1 Code :

private void button1_Click(object sender, EventArgs e)
{
            Form2 f2 = new Form2();
            f2.ShowDialog();
            MessageBox.Show("Form1 Message :"+Form2.t.Text); //can put label also in form 1 to show the value got from form2
}

Form2 Code :

        public Form2()
        {
            InitializeComponent();
            t = textBox1;                        //Initialize with static textbox
        }
        public static TextBox t=new TextBox();   //make static to get the same value as inserted
        private void button1_Click(object sender, EventArgs e)
        {

            this.Close();

        }

It Works!

How do I abort the execution of a Python script?

If the entire program should stop use sys.exit() otherwise just use an empty return.

C#: How do you edit items and subitems in a listview?

If you're looking for "in-place" editing of a ListView's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.

By default, the best you can achieve with a "standard" ListView is to set it's LabelEdit property to true to allow the user to edit the text of the first column of the ListView (assuming you want to allow a free-format text edit).

Some examples (including full source-code) of customized ListView's that allow "in-place" editing of sub-items are:

C# Editable ListView
In-place editing of ListView subitems

Given URL is not allowed by the Application configuration Facebook application error

I chased my tail on this issue for hours. My coder and I could login with FB without a problem but my wife couldn't. She would get this topic's subject message. I tried every setting and URL that I could think of for my Lavarel app.

My issue was that my wife was signing in from:

http://www and we were using http://  

A short trip to CPanel and a redirect fixed that. Hope this helps someone!

For Lavarel these FB app settings worked for me:

Settings/Basic - App Domain: mydomain.com ,  Site URL: http://mydomain.com/login.

Settings/Advanced - Client OAuth Login: Yes. 

Settings/Advanced - OAuth redirect URIs: http://mydomain.com , http://mydomain.com/login.

App Details/App Center listed platforms = No.  I'm only using the login for now.

$(document).click() not working correctly on iPhone. jquery

Change this:

$(document).click( function () {

To this

$(document).on('click touchstart', function () {

Maybe this solution don't fit on your work and like described on the replies this is not the best solution to apply. Please, check another fixes from another users.

Generate an integer that is not among four billion given ones

Strip the white space and non numeric characters from the file and append 1. Your file now contains a single number not listed in the original file.

From Reddit by Carbonetc.

How to refer to Excel objects in Access VBA?

I dissent from both the answers. Don't create a reference at all, but use late binding:

  Dim objExcelApp As Object
  Dim wb As Object

  Sub Initialize()
    Set objExcelApp = CreateObject("Excel.Application")
  End Sub

  Sub ProcessDataWorkbook()
     Set wb = objExcelApp.Workbooks.Open("path to my workbook")
     Dim ws As Object
     Set ws = wb.Sheets(1)

     ws.Cells(1, 1).Value = "Hello"
     ws.Cells(1, 2).Value = "World"

     'Close the workbook
     wb.Close
     Set wb = Nothing
  End Sub

You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().

This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.

Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.

Send Message in C#

Building on Mark Byers's answer.

The 3rd project could be a WCF project, hosted as a Windows Service. If all programs listened to that service, one application could call the service. The service passes the message on to all listening clients and they can perform an action if suitable.

Good WCF videos here - http://msdn.microsoft.com/en-us/netframework/dd728059

How do I enumerate the properties of a JavaScript object?

I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..

Increase heap size in Java

You can increase the Heap Size by passing JVM parameters -Xms and -Xmx like below:

For Jar Files:

java -jar -Xms4096M -Xmx6144M jarFilePath.jar

For Java Files:

 java -Xms4096M -Xmx6144M ClassName

The above parameters increase the InitialHeapSize (-Xms) to 4GB (4096 MB) and MaxHeapSize(-Xmx) to 6GB (6144 MB).

But, the Young Generation Heap Size will remain same and the additional HeapSize will be added to the Old Generation Heap Size. To equalize the size of Young Gen Heap and Old Gen Heap, use -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy params.

java -jar -Xms4096M -Xmx6144M -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy pathToJarFile.jar

-XX:NewRatio = Old Gen Heap Size : Young Gen HeapSize (You can play with this ratio to get your desired ratio).

C++ terminate called without an active exception

As long as your program die, then without detach or join of the thread, this error will occur. Without detaching and joining the thread, you should give endless loop after creating thread.

int main(){

std::thread t(thread,1);

while(1){}

//t.detach();
return 0;}

It is also interesting that, after sleeping or looping, thread can be detach or join. Also with this way you do not get this error.

Below example also shows that, third thread can not done his job before main die. But this error can not happen also, as long as you detach somewhere in the code. Third thread sleep for 8 seconds but main will die in 5 seconds.

void thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));}

int main() {
std::cout << "Start main\n";
std::thread t(thread,1);
std::thread t2(thread,3);
std::thread t3(thread,8);
sleep(5);

t.detach();
t2.detach();
t3.detach();
return 0;}

Spark Kill Running Application

  • copy past the application Id from the spark scheduler, for instance application_1428487296152_25597
  • connect to the server that have launch the job
  • yarn application -kill application_1428487296152_25597

How to Consume WCF Service with Android

If I were doing this I would probably use WCF REST on the server and a REST library on the Java/Android client.

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

Unit testing with Spring Security

Personally I would just use Powermock along with Mockito or Easymock to mock the static SecurityContextHolder.getSecurityContext() in your unit/integration test e.g.

@RunWith(PowerMockRunner.class)
@PrepareForTest(SecurityContextHolder.class)
public class YourTestCase {

    @Mock SecurityContext mockSecurityContext;

    @Test
    public void testMethodThatCallsStaticMethod() {
        // Set mock behaviour/expectations on the mockSecurityContext
        when(mockSecurityContext.getAuthentication()).thenReturn(...)
        ...
        // Tell mockito to use Powermock to mock the SecurityContextHolder
        PowerMockito.mockStatic(SecurityContextHolder.class);

        // use Mockito to set up your expectation on SecurityContextHolder.getSecurityContext()
        Mockito.when(SecurityContextHolder.getSecurityContext()).thenReturn(mockSecurityContext);
        ...
    }
}

Admittedly there is quite a bit of boiler plate code here i.e. mock an Authentication object, mock a SecurityContext to return the Authentication and finally mock the SecurityContextHolder to get the SecurityContext, however its very flexible and allows you to unit test for scenarios like null Authentication objects etc. without having to change your (non test) code

Convert a PHP script into a stand-alone windows executable

I had problems with most of the tools in other answers as they are all very outdated.

If you need a solution that will "just work", pack a bare-bones version of php with your project in a WinRar SFX archive, set it to extract everything to a temporary directory and execute php your_script.php.

To run a basic script, the only files required are php.exe and php5.dll (or php5ts.dll depending on version).

To add extensions, pack them along with a php.ini file:

[PHP]
extension_dir = "."
extension=php_curl.dll
extension=php_xxxx.dll
...

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

error: (-215) !empty() in function detectMultiScale

no need to change the code

download that .xml file , then put the path of that file

it will solve the error (100%)

Iterate keys in a C++ map

If you need an iterator that just returns the keys you need to wrap map's iterator in your own class that provides the desired interface. You can declare a new iterator class from scratch like here, of use existing helper constructs. This answer shows how to use Boost's transform_iterator to wrap the iterator in one that only returns the values/keys.

Select from one table where not in another

To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.

To correct this, add a null check...

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN 
      (SELECT pd.part_num FROM wpsapi4.product_details pd 
                  where pd.part_num is not null)
  • Sorry but I couldn't add a comment as I don't have the rep!

How to try convert a string to a Guid

This will get you pretty close, and I use it in production and have never had a collision. However, if you look at the constructor for a guid in reflector, you will see all of the checks it makes.

 public static bool GuidTryParse(string s, out Guid result)
    {
        if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
        {
            result = new Guid(s);
            return true;
        }

        result = default(Guid);
        return false;
    }

    static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
                          "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
                          "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Compiled);

How to make a new List in Java

In Java 8

To create a non-empty list of fixed size (operations like add, remove, etc., are not supported):

List<Integer> list = Arrays.asList(1, 2); // but, list.set(...) is supported

To create a non-empty mutable list:

List<Integer> list = new ArrayList<>(Arrays.asList(3, 4));

In Java 9

Using a new List.of(...) static factory methods:

List<Integer> immutableList = List.of(1, 2);

List<Integer> mutableList = new ArrayList<>(List.of(3, 4));

In Java 10

Using the Local Variable Type Inference:

var list1 = List.of(1, 2);

var list2 = new ArrayList<>(List.of(3, 4));

var list3 = new ArrayList<String>();

And follow best practices...

Don't use raw types

Since Java 5, generics have been a part of the language - you should use them:

List<String> list = new ArrayList<>(); // Good, List of String

List list = new ArrayList(); // Bad, don't do that!

Program to interfaces

For example, program to the List interface:

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

Instead of:

ArrayList<Double> list = new ArrayList<>(); // This is a bad idea!

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The only good use case for recursion mutex is when an object contains multiple methods. When any of the methods modify the content of the object, and therefore must lock the object before the state is consistent again.

If the methods use other methods (ie: addNewArray() calls addNewPoint(), and finalizes with recheckBounds()), but any of those functions by themselves need to lock the mutex, then recursive mutex is a win-win.

For any other case (solving just bad coding, using it even in different objects) is clearly wrong!

Python Image Library fails with message "decoder JPEG not available" - PIL

On Mac OS X Mavericks (10.9.3), I solved this by doing the follows:

Install libjpeg by brew (package management system)

brew install libjpeg

reinstall pillow (I use pillow instead of PIL)

pip install -I pillow

How do I add an active class to a Link from React Router?

With [email protected] (though any 4.x.x should do I guess), we can use the withRouter HOC to accomplish this. For example, I want to implement the Bootstrap navbar and since it requires a class of active on <li class="nav-item"> and not on the anchor tag, I made a new component called NavItem to encapsulate a single li.nav-item. The implementation is as follows:

import React from "react";
import { Link, withRouter } from "react-router-dom";

const NavItem = ({ isActive, to, label }) => {
  let classes = ["nav-item"];
  if (isActive) classes.push("active");

  return (
    <li className={classes.join(" ")}>
      <Link className="nav-link" to={to}>
        {label}
      </Link>
    </li>
  );
};

export default withRouter(({ location, ...props }) => {
  const isActive = location.pathname === props.to;

  console.log(location.pathname, props.to);

  return <NavItem {...props} isActive={isActive} />;
});

As you can see, NavItem is just a stateless functional component which expects an isActive prop to determine whether active class should be added. Now, to update this prop as the location changes, we can make use of the withRouter HOC. You can pass any component to this function and it'll give it { match, location, history } objects in its props along with the ones you pass down. Here, I am creating a functional component inline which receives these objects and determines whether the current link is the active one using the location.pathname property. This'll give us a Boolean and we can return the NavItem along with isActive set to the value we computed using location.pathname.

A working example of this can be found here. Please let me know if there's an easier way to do this.

How to convert a GUID to a string in C#?

According to MSDN the method Guid.ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier.

Examples:

  • guidVal.ToString() or guidVal.ToString("D") returns 32 hex digits separated by hyphens: 00000000-0000-0000-0000-000000000000
  • guidVal.ToString("N") returns 32 hex digits:00000000000000000000000000000000
  • guidVal.ToString("B") returns 32 hex digits separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
  • guidVal.ToString("P") returns 32 hex digits separated by hyphens, enclosed in parentheses: (00000000-0000-0000-0000-000000000000)

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

Get ID of element that called a function

i also want this to happen , so just pass the id of the element in the called function and used in my js file :

function copy(i,n)
{
 var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range); 
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById(n).value = "Copied";
}

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

Conditional logic in AngularJS template

Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.

If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:


Original answer:

Here is a not-so-great "ng-if" directive:

myApp.directive('ngIf', function() {
    return {
        link: function(scope, element, attrs) {
            if(scope.$eval(attrs.ngIf)) {
                // remove '<div ng-if...></div>'
                element.replaceWith(element.children())
            } else {
                element.replaceWith(' ')
            }
        }
    }
});

that allows for this HTML syntax:

<div ng-repeat="message in data.messages" ng-class="message.type">
   <hr>
   <div ng-if="showFrom(message)">
       <div>From: {{message.from.name}}</div>
   </div>    
   <div ng-if="showCreatedBy(message)">
      <div>Created by: {{message.createdBy.name}}</div>
   </div>    
   <div ng-if="showTo(message)">
      <div>To: {{message.to.name}}</div>
   </div>    
</div>

Fiddle.

replaceWith() is used to remove unneeded content from the DOM.

Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?

The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.

E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

Java 8 Lambda Stream forEach with multiple statements

In the first case alternatively to multiline forEach you can use the peek stream operation:

entryList.stream()
         .peek(entry -> entry.setTempId(tempId))
         .forEach(updatedEntries.add(entityManager.update(entry, entry.getId())));

In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.

Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.

Simpler way to check if variable is not equal to multiple string values?

You may find it more readable to reverse your logic and use an else statement with an empty if.

if($some_variable === 'uk' || $another_variable === 'in'){}

else {
    // This occurs when neither of the above are true
}

How do I create a MongoDB dump of my database?

cmd -->

C:\Program Files\MongoDB\Server\3.2\bin>mongodump.exe --db Dintest

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon destroys the session as stated above so you should use this when logging someone out. I think a good use of Session.Clear would be for a shopping basket on an ecommerce website. That way the basket gets cleared without logging out the user.

Declaring an HTMLElement Typescript

Okay: weird syntax!

var el: HTMLElement = document.getElementById('content');

fixes the problem. I wonder why the example didn't do this in the first place?

complete code:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    var el: HTMLElement = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

Why does multiplication repeats the number several times?

You cannot multiply an integer by a string. To be sure, you could try using the int (short for integer which means whole number) command, like this for example -

firstNumber = int(9)
secondNumber = int(1)
answer = (firstNumber*secondNumber)

Hope that helped :)

Smooth scrolling when clicking an anchor link

Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;

    $('.a-parent-div').find('a').click(function(event){
        event.preventDefault();
        $('.scroll-div').animate({
     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       
  });

The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.

open link in iframe

Assuming the iFrame has a name attribute of "myIframe":

<a href="http://www.google.com" target="myIframe">Link Text</a> 

You can also accomplish this with the use of Javascript. The iFrame has a src attribute which specifies the location it shows. As such, it's a simple matter of binding the click of a link to changing that src attribute.

Rotating a two-dimensional array in Python

Just an observation. The input is a list of lists, but the output from the very nice solution: rotated = zip(*original[::-1]) returns a list of tuples.

This may or may not be an issue.

It is, however, easily corrected:

original = [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]
            ]


def rotated(array_2d):
    list_of_tuples = zip(*array_2d[::-1])
    return [list(elem) for elem in list_of_tuples]
    # return map(list, list_of_tuples)

print(list(rotated(original)))

# [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

The list comp or the map will both convert the interior tuples back to lists.

How to return a struct from a function in C++?

studentType newStudent() // studentType doesn't exist here
{   
    struct studentType // it only exists within the function
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;
...

Move it outside the function:

struct studentType
{
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;

    int arrayMarks[4];

    double avgMarks;

};

studentType newStudent()
{
    studentType newStudent
    ...
    return newStudent;
}

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

Bootstrap 3 only for mobile

If you're looking to make the elements be 33.3% only on small devices and lower:

This is backwards from what Bootstrap is designed for, but you can do this:

<div class="row">
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>

This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.

JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/

If you're only looking to hide elements for smaller devices:

I think you're looking for the visible-xs and/or visible-sm classes. These will let you make certain elements only visible to small screen devices.

For example, if you want a element to only be visible to small and extra-small devices, do this:

<div class="visible-xs visible-sm">You're using a fairly small device.</div>

To show it only for larger screens, use this:

<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>

See http://getbootstrap.com/css/#responsive-utilities-classes for more information.

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

How can I read input from the console using the Scanner class in Java?

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] arguments){
        Scanner input = new Scanner(System.in);

        String username;
        double age;
        String gender;
        String marital_status;
        int telephone_number;

        // Allows a person to enter his/her name   
        Scanner one = new Scanner(System.in);
        System.out.println("Enter Name:" );  
        username = one.next();
        System.out.println("Name accepted " + username);

        // Allows a person to enter his/her age   
        Scanner two = new Scanner(System.in);
        System.out.println("Enter Age:" );  
        age = two.nextDouble();
        System.out.println("Age accepted " + age);

        // Allows a person to enter his/her gender  
        Scanner three = new Scanner(System.in);
        System.out.println("Enter Gender:" );  
        gender = three.next();
        System.out.println("Gender accepted " + gender);

        // Allows a person to enter his/her marital status
        Scanner four = new Scanner(System.in);
        System.out.println("Enter Marital status:" );  
        marital_status = four.next();
        System.out.println("Marital status accepted " + marital_status);

        // Allows a person to enter his/her telephone number
        Scanner five = new Scanner(System.in);
        System.out.println("Enter Telephone number:" );  
        telephone_number = five.nextInt();
        System.out.println("Telephone number accepted " + telephone_number);
    }
}

SSL Error: CERT_UNTRUSTED while using npm command

npm ERR! node -v v0.8.0
npm ERR! npm -v 1.1.32

Update your node.js installation.The following commands should do it (from here):

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Edit: okay, if you really have a good reason to run an ancient version of the software, npm set ca null will fix the issue. It happened, because built-in npm certificate has expired over the years.

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

I know this has already been answered, but I stumbled across this question and went down the path of using format, which works, but it returns them as strings when I wanted integers.

I just realized that moment comes with date, month and year methods that return the actual integers for each method.

moment().date()
moment().month()  // jan=0, dec=11
moment().year()

Order by in Inner Join

I found this to be an issue when joining but you might find this blog useful in understanding how Joins work in the back. How Joins Work..

[Edited] @Shree Thank you for pointing that out. On the paragraph of Merge Join. It mentions on how joins work...

Like hash join, merge join consists of two steps. First, both tables of the join are sorted on the join attribute. This can be done with just two passes through each table via an external merge sort. Finally, the result tuples are generated as the next ordered element is pulled from each table and the join attributes are compared

.

Formatting a number with exactly two decimals in JavaScript

Here's a simple one

function roundFloat(num,dec){
    var d = 1;
    for (var i=0; i<dec; i++){
        d += "0";
    }
    return Math.round(num * d) / d;
}

Use like alert(roundFloat(1.79209243929,4));

Jsfiddle

Creating a batch file, for simple javac and java command execution

The only other thing I would add is to make it a tad more flexible. Most times I'll have a trivial java file I want to run like - Main.java, Simple.java, Example.java, or Playground.java (you get the idea).

I use the following to strike off a javac and corresponding java.

@echo off
javac %~n1.java
java %~n1

The %~n1 gets the filename (sans extension) of the first argument passed to the batch file. So this way I can run it using tab completion and not have to worry about it working with either the .class or .java extension.

So both of the following will have the same result:

run.bat Main.class
and
run.bat Main.java

Doesn't 100% answer the original posters question, but I think it is a good next step/evolution for simple javac/java programs.

How to change file encoding in NetBeans?

Go to etc folder in Netbeans home --> open netbeans.conf file and add on netbeans_default_options following line:

-J-Dfile.encoding=UTF-8

Restart Netbeans and it should be in UTF-8

To check go to help --> about and check System: Windows Vista version 6.0 running on x86; UTF-8; nl_NL (nb)

How to redirect to another page using AngularJS?

You can use Angular $window:

$window.location.href = '/index.html';

Example usage in a contoller:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];

    function LoginCtrl($window, loginSrv, notify) {
        /* jshint validthis:true */
        var vm = this;
        vm.validateUser = function () {
             loginSrv.validateLogin(vm.username, vm.password).then(function (data) {          
                if (data.isValidUser) {    
                    $window.location.href = '/index.html';
                }
                else
                    alert('Login incorrect');
            });
        }
    }
})();

How to convert string representation of list to a list?

Assuming that all your inputs are lists and that the double quotes in the input actually don't matter, this can be done with a simple regexp replace. It is a bit perl-y but works like a charm. Note also that the output is now a list of unicode strings, you didn't specify that you needed that, but it seems to make sense given unicode input.

import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" \]]')
result = junkers.sub('', x).split(',')
print result
--->  [u'A', u'B', u'C', u'D']

The junkers variable contains a compiled regexp (for speed) of all characters we don't want, using ] as a character required some backslash trickery. The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.

Note that this also removes spaces from inside entries u'["oh no"]' ---> [u'ohno']. If this is not what you wanted, the regexp needs to be souped up a bit.

How to obtain the query string from the current URL with JavaScript?

This will add a global function to access to the queryString variables as a map.

// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
    window.location.query = function (source) {
        var map = {};
        source = source || this.search;

        if ("" != source) {
            var groups = source, i;

            if (groups.indexOf("?") == 0) {
                groups = groups.substr(1);
            }

            groups = groups.split("&");

            for (i in groups) {
                source = groups[i].split("=",
                    // For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
                    (groups[i].slice(-1) !== "=") + 1
                );

                // Key
                i = decodeURIComponent(source[0]);

                // Value
                source = source[1];
                source = typeof source === "undefined"
                    ? source
                    : decodeURIComponent(source);

                // Save Duplicate Key
                if (i in map) {
                    if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
                        map[i] = [map[i]];
                    }

                    map[i].push(source);
                }

                // Save New Key
                else {
                    map[i] = source;
                }
            }
        }

        return map;
    }

    window.location.query.makeString = function (source, addQuestionMark) {
        var str = "", i, ii, key;

        if (typeof source == "boolean") {
            addQuestionMark = source;
            source = undefined;
        }

        if (source == undefined) {
            str = window.location.search;
        }
        else {
            for (i in source) {
                key = "&" + encodeURIComponent(i);

                if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
                    str += key + addUndefindedValue(source[i]);
                }
                else {
                    for (ii = 0; ii < source[i].length; ii++) {
                        str += key + addUndefindedValue(source[i][ii]);
                    }
                }
            }
        }

        return (addQuestionMark === false ? "" : "?") + str.substr(1);
    }

    function addUndefindedValue(source) {
        return typeof source === "undefined"
            ? ""
            : "=" + encodeURIComponent(source);
    }
}

Enjoy.

CodeIgniter : Unable to load the requested file:

I error occor. When you are trying to access a file which is not in the director. Carefully check path in the view

 $this->load->view('path');

default root path of view function is application/view .

I had the same error. I was trying to access files like this

 $this->load->view('pages/view/file.php');

Actually I have the class Pages and function. I built the function with one argument to call the any files from the director application/view/pages . I was put the wrong path. The above path pages/view/files can be used when you are trying to access the controller. Not for the view. MVC gave a lot confusion. I had this problem. I just solve it. Thanks.

Finding the number of non-blank columns in an Excel sheet using VBA

Jean-François Corbett's answer is perfect. To be exhaustive I would just like to add that with some restrictons you could also use UsedRange.Columns.Count or UsedRange.Rows.Count.
The problem is that UsedRange is not always updated when deleting rows/columns (at least until you reopen the workbook).

Send File Attachment from Form Using phpMailer and PHP

Hey guys the code below worked perfectly fine for me. Just replace the setFrom and addAddress with your preference and that's it.

<?php
/**
 * PHPMailer simple file upload and send example.
 */
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
    // First handle the upload
    // Don't trust provided filename - same goes for MIME types
    // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
    $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) 
    {
        // Upload handled successfully
        // Now create a message

        require 'vendor/autoload.php';
        $mail = new PHPMailer;
        $mail->setFrom('[email protected]', 'CV from Web site');
        $mail->addAddress('[email protected]', 'CV');
        $mail->Subject = 'PHPMailer file sender';
        $mail->Body = 'My message body';

        $filename = $_FILES["userfile"]["name"]; // add this line of code to auto pick the file name
        //$mail->addAttachment($uploadfile, 'My uploaded file'); use the one below instead

        $mail->addAttachment($uploadfile, $filename);
        if (!$mail->send()) 
        {
            $msg .= "Mailer Error: " . $mail->ErrorInfo;
        } 
        else 
        {
            $msg .= "Message sent!";
        }
    } 
        else 
        {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="4194304" />
        <input name="userfile" type="file">
        <input type="submit" value="Send File">
    </form>

<?php } else {
    echo $msg;
} ?>
</body>
</html>

Add MIME mapping in web.config for IIS Express

I know this is an old question, but...

I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:

http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/

I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:

  • Open a console application with administrator privilages.
  • Navigation to the IIS Express directory. This lives under Program Files or Program Files (x86)
  • Run the command:

    appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']

Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT and DELETE verbs). Yay!

How to force Eclipse to ask for default workspace?

I had the same problem on my eclipse, and calling eclipse -clean did not solve the problem.

In the end I figured out that within the installation folder of eclipse there is a script called eclipse. This script does some setting of environment variables and then calls eclipse.bin. The call for eclipse.bin contained the command line switch

-data ~/.eclipse

When I removed that switch from start-up script, I got the workspace selection as expected. Maybe that helps others to solve their problems.

Printing one character at a time from a string, using the while loop

   # make a list out of text - ['h','e','l','l','o']
   text = list('hello') 

   while text:
       print text.pop()

:)

In python empty object are evaluated as false. The .pop() removes and returns the last item on a list. And that's why it prints on reverse !

But can be fixed by using:

text.pop( 0 )

pythonw.exe or python.exe?

In my experience the pythonw.exe is faster at least with using pygame.

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Process Bar:

Dependency:

     implementation 'com.github.castorflex.smoothprogressbar:library:1.0.0'

XML:

     <fr.castorflex.android.smoothprogressbar.SmoothProgressBar
        xmlns:android="http://schemas.android.com/apk/res/android"                
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/myProcessbar"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:indeterminate="true" />

In Res->color

      <color name="pocket_color_1">#ff1635</color>
      <integer-array name="pocket_background_colors">
          <item>@color/pocket_color_1</item>
      </integer-array>

      <color name="pocket_color_stop">#00ff00</color>
      <integer-array name="pocket_background_stop">
          <item>@color/pocket_color_stop</item>
      </integer-array>

In Main:

      public class MainActivity extends AppCompatActivity{
        SmoothProgressBar smoothProgressBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          smoothProgressBar=findViewById(R.id.myProcessbar);
          showProcessBar();
          stopAnimation();    // call when required to stop process
        }

        public void showProcessBar(){
          smoothProgressBar.setVisibility(View.VISIBLE);
          smoothProgressBar.setIndeterminateDrawable(new SmoothProgressDrawable.Builder(getApplicationContext())
            .interpolator(new AccelerateInterpolator())
            .progressiveStart(true)
            .progressiveStopSpeed(1000)
            .build());
          smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
          SmoothProgressBarUtils.generateDrawableWithColors(
                    getResources().getIntArray(R.array.pocket_background_colors),
                    ((SmoothProgressDrawable)  smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
        }

        public void stopAnimation(){
          smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
          SmoothProgressBarUtils.generateDrawableWithColors(
                    getResources().getIntArray(R.array.pocket_background_stop),
                    ((SmoothProgressDrawable)  smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
          smoothProgressBar.progressiveStop();
          Handler handler=new Handler();
          handler.postDelayed(new Runnable() {
            @Override
            public void run() {
               smoothProgressBar.animate().alpha(0.0f).setDuration(6000).translationY(1000);
               smoothProgressBar.setVisibility(View.GONE);
            }
          },1000);
}

      }

SQL Server® 2016, 2017 and 2019 Express full download

Once you start the web installer there's an option to download media, that being the full installation package. There's even download options for what kind of package to download.

Unable to allocate array with shape and data type

change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:

data['label'] = data['label'].astype(np.uint8)

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

Find the directory part (minus the filename) of a full path in access 97

left(currentdb.Name,instr(1,currentdb.Name,dir(currentdb.Name))-1)

The Dir function will return only the file portion of the full path. Currentdb.Name is used here, but it could be any full path string.

"Could not find a version that satisfies the requirement opencv-python"

It happened with me on Windows, pip was not able to install opencv-python==3.4.0.12.

Later found out that it was due to the Python version, Python 3.7 has some issue with not getting linked to https://github.com/skvark/opencv-python.

Downgraded to Python 3.6 and it worked with:

pip3 install opencv-python

Best practices to test protected methods with PHPUnit

I'd like to propose a slight variation to getMethod() defined in uckelman's answer.

This version changes getMethod() by removing hard-coded values and simplifying usage a little. I recommend adding it to your PHPUnitUtil class as in the example below or to your PHPUnit_Framework_TestCase-extending class (or, I suppose, globally to your PHPUnitUtil file).

Since MyClass is being instantiated anyways and ReflectionClass can take a string or an object...

class PHPUnitUtil {
    /**
     * Get a private or protected method for testing/documentation purposes.
     * How to use for MyClass->foo():
     *      $cls = new MyClass();
     *      $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');
     *      $foo->invoke($cls, $...);
     * @param object $obj The instantiated instance of your class
     * @param string $name The name of your private/protected method
     * @return ReflectionMethod The method you asked for
     */
    public static function getPrivateMethod($obj, $name) {
      $class = new ReflectionClass($obj);
      $method = $class->getMethod($name);
      $method->setAccessible(true);
      return $method;
    }
    // ... some other functions
}

I also created an alias function getProtectedMethod() to be explicit what is expected, but that one's up to you.

Assignment makes pointer from integer without cast

As others already noted, in one case you are attempting to return cString (which is a char * value in this context - a pointer) from a function that is declared to return a char (which is an integer). In another case you do the reverse: you are assigning a char return value to a char * pointer. This is what triggers the warnings. You certainly need to declare your return values as char *, not as char.

Note BTW that these assignments are in fact constraint violations from the language point of view (i.e. they are "errors"), since it is illegal to mix pointers and integers in C like that (aside from integral constant zero). Your compiler is simply too forgiving in this regard and reports these violations as mere "warnings".

What I also wanted to note is that in several answers you might notice the relatively strange suggestion to return void from your functions, since you are modifying the string in-place. While it will certainly work (since you indeed are modifying the string in-place), there's nothing really wrong with returning the same value from the function. In fact, it is a rather standard practice in C language where applicable (take a look at the standard functions like strcpy and others), since it enables "chaining" of function calls if you choose to use it, and costs virtually nothing if you don't use "chaining".

That said, the assignments in your implementation of compareString look complete superfluous to me (even though they won't break anything). I'd either get rid of them

int compareString(char cString1[], char cString2[]) { 
    // To lowercase 
    strToLower(cString1); 
    strToLower(cString2); 

    // Do regular strcmp 
    return strcmp(cString1, cString2); 
} 

or use "chaining" and do

int compareString(char cString1[], char cString2[]) { 
    return strcmp(strToLower(cString1), strToLower(cString2)); 
} 

(this is when your char * return would come handy). Just keep in mind that such "chained" function calls are sometimes difficult to debug with a step-by-step debugger.

As an additional, unrealted note, I'd say that implementing a string comparison function in such a destructive fashion (it modifies the input strings) might not be the best idea. A non-destructive function would be of a much greater value in my opinion. Instead of performing as explicit conversion of the input strings to a lower case, it is usually a better idea to implement a custom char-by-char case-insensitive string comparison function and use it instead of calling the standard strcmp.

PHP 7: Missing VCRUNTIME140.dll

I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ filesFrom There yoy can modify MVC

How to stop mysqld

For MAMP

  1. Stop servers (but you may notice MySQL stays on)
  2. Remove or rename /Applications/MAMP/tmp/mysql/ which holds the mysql.pid and mysql.sock.lock files
  3. When you go back to Mamp, you'll see MySQL is now off. You can "Start Servers" again.

How to find which git branch I am on when my disk is mounted on other server

Our git repo disk is mounted on AIX box to do BUILD.

It sounds like you mounted the drive on which the git repository is stored on another server, and you are asking how to modify that. If that is the case, this is a bad idea.

The build server should have its own copy of the git repository, and it will be locally managed by git on the build server. The build server's repository will be connected to the "main" git repository with a "remote", and you can issue the command git pull to update the local repository on the build server.

If you don't want to go to the trouble of setting up SSH or a gitolite server or something similar, you can use a file path as the "remote" location. So you could continue to mount the Linux server's file system on the build server, but instead of running the build out of that mounted path, clone the repository into another folder and run it from there.

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

Database, Table and Column Naming Conventions?

Table names should always be singular, because they represent a set of objects. As you say herd to designate a group of sheep, or flock do designate a group of birds. No need for plural. When a table name is composition of two names and naming convention is in plural it becomes hard to know if the plural name should be the first word or second word or both. It’s the logic – Object.instance, not objects.instance. Or TableName.column, not TableNames.column(s). Microsoft SQL is not case sensitive, it’s easier to read table names, if upper case letters are used, to separate table or column names when they are composed of two or more names.

React: Expected an assignment or function call and instead saw an expression

You are not returning anything, at least from your snippet and comment.

const def = (props) => { <div></div> };

This is not returning anything, you are wrapping the body of the arrow function with curly braces but there is no return value.

const def = (props) => { return (<div></div>); }; OR const def = (props) => <div></div>;

These two solutions on the other hand are returning a valid React component. Keep also in mind that inside your jsx (as mentioned by @Adam) you can't have if ... else ... but only ternary operators.

Platform.runLater and Task in JavaFX

  • Platform.runLater: If you need to update a GUI component from a non-GUI thread, you can use that to put your update in a queue and it will be handled by the GUI thread as soon as possible.
  • Task implements the Worker interface which is used when you need to run a long task outside the GUI thread (to avoid freezing your application) but still need to interact with the GUI at some stage.

If you are familiar with Swing, the former is equivalent to SwingUtilities.invokeLater and the latter to the concept of SwingWorker.

The javadoc of Task gives many examples which should clarify how they can be used. You can also refer to the tutorial on concurrency.

How to change Status Bar text color in iOS

If you want to set it to any color, use below code.

id statusBarWindow = [[UIApplication sharedApplication] valueForKey:@"statusBarWindow"];
id statusBar = [statusBarWindow valueForKey:@"statusBar"];

SEL setForegroundColor_sel = NSSelectorFromString(@"setForegroundColor:");
if([statusBar respondsToSelector:setForegroundColor_sel]) {
    // iOS 7+
    [statusBar performSelector:setForegroundColor_sel withObject:YourColorHere];
                                                                 ^^^^^^^^^^^^^
}

I know I am accessing private API, but I have used this in many projects and Apple have approved it.

Just while submitting the app, send this code to Apple in Comments section and inform that you are using this code to change the status bar color.

And yes, don't forget below too.

Calculating Distance between two Latitude and Longitude GeoCoordinates

When CPU/math computing power is limited:

There are times (such as in my work) when computing power is scarce (e.g. no floating point processor, working with small microcontrollers) where some trig functions can take an exorbitant amount of CPU time (e.g. 3000+ clock cycles), so when I only need an approximation, especially if if the CPU must not be tied up for a long time, I use this to minimize CPU overhead:

/**------------------------------------------------------------------------
 * \brief  Great Circle distance approximation in km over short distances.
 *
 * Can be off by as much as 10%.
 *
 * approx_distance_in_mi = sqrt(x * x + y * y)
 *
 * where x = 69.1 * (lat2 - lat1)
 * and y = 69.1 * (lon2 - lon1) * cos(lat1/57.3)
 *//*----------------------------------------------------------------------*/
double    ApproximateDisatanceBetweenTwoLatLonsInKm(
                  double lat1, double lon1,
                  double lat2, double lon2
                  ) {
    double  ldRadians, ldCosR, x, y;

    ldRadians = (lat1 / 57.3) * 0.017453292519943295769236907684886;
    ldCosR = cos(ldRadians);
    x = 69.1 * (lat2 - lat1);
    y = 69.1 * (lon2 - lon1) * ldCosR;

    return sqrt(x * x + y * y) * 1.609344;  /* Converts mi to km. */
}

Credit goes to https://github.com/kristianmandrup/geo_vectors/blob/master/Distance%20calc%20notes.txt.

C#: How to add subitems in ListView

add:

.SubItems.Add("asdasdasd");

to the last line of your code so it will look like this in the end.

listView1.Items.Add("sdasdasdasd").SubItems.Add("asdasdasd");

How to disable scrolling in UITableView table when the content fits on the screen

So there's are multiple answers and requires a all content at once place so I'm adding this answer:

If you're using AutoLayout, by setting this only should work for you:

  • In code:

tableView.alwaysBounceVertical = false

  • or In Interface Builder:

Just find this option and untick "Bounce Vertically" option.

Here's the reference:

enter image description here

If you're not using AutoLayout:

 override func viewDidLayoutSubviews() {
    // Enable scrolling based on content height
    tableView.isScrollEnabled = tableView.contentSize.height > tableView.frame.size.height
 }

Any reason to prefer getClass() over instanceof when generating .equals()?

Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:

class A { }

class B extends A { }

Object oA = new A();
Object oB = new B();

oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true

oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true

Git add and commit in one command

To keep it in one line use:

git add . && git commit -am "comment"

This line will add and commit all changed and added files to repository.

How to remove trailing whitespace in code, using another script?

If you're looking to tidy up for PEP8, this will trim trailing whitespace for your whole project:

import os

PATH = '/path/to/your/project'

for path, dirs, files in os.walk(PATH):
    for f in files:
        file_name, file_extension = os.path.splitext(f)
        if file_extension == '.py':
            path_name = os.path.join(path, f)
            with open(path_name, 'r') as fh:
                new = [line.rstrip() for line in fh]
            with open(path_name, 'w') as fh:
                [fh.write('%s\n' % line) for line in new]

ClassCastException, casting Integer to Double

This means that your ArrayList has integers in some elements. The casting should work unless there's an integer in one of your elements.

One way to make sure that your arraylist has no integers is by declaring it as a Doubles array.

    ArrayList<Double> marks = new ArrayList<Double>();

Filtering a list based on a list of booleans

With numpy:

In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]

Out[130]: array([1, 4])

or see Alex Szatmary's answer if list_a can be a numpy array but not filter

Numpy usually gives you a big speed boost as well

In [133]: list_a = [1, 2, 4, 6]*10000
In [134]: fil = [True, False, True, False]*10000
In [135]: list_a_np = np.array(list_a)
In [136]: fil_np = np.array(fil)

In [139]: %timeit list(itertools.compress(list_a, fil))
1000 loops, best of 3: 625 us per loop

In [140]: %timeit list_a_np[fil_np]
10000 loops, best of 3: 173 us per loop

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

What is the difference between mocking and spying when using Mockito?

Spy can be useful when you want to create unit tests for legacy code.

I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.

If you have something like this code:

public void transfer(  DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService, 
             double amount, String fromAccount, String toAccount){
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some, legacy code, dependency is in the code like this:

    public void transfer(String fromAccount, String toAccount, double amount){

        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }

Then you can use the spy the inject the dependency like this:

DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target).proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target).proxyWithdrawMoneyServiceCreator();

More detail in the link above.

Object Dump JavaScript

Using console.log(object) will throw your object to the Javascript console, but that's not always what you want. Using JSON.stringify(object) will return most stuff to be stored in a variable, for example to send it to a textarea input and submit the content back to the server.

Text editor to open big (giant, huge, large) text files

Tips and tricks

less

Why are you using editors to just look at a (large) file?

Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.

There is a Win32 port of GNU less. See the "less" section of the answer above.

Perl

Perl is good for quick scripts, and its .. (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.

For example:

$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less

This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.

Another example:

$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less

This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...

logparser

This is another useful tool you can use. To quote the Wikipedia article:

logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.

Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.

Example usage:

C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"

The relativity of sizes

100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.

And more...

Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...

Example of waitpid() in use?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(2);
        exit(EXIT_SUCCESS);
    }

//Comment from here to...
    //Parent waits process pid (child)
    waitpid(pid, &status, 0);
    //Option is 0 since I check it later

    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
//To Here and see the difference
    printf("Parent: %d\n", getpid());

    return 0;
}

How can I show current location on a Google Map on Android Marshmallow?

Sorry but that's just much too much overhead (above), short and quick, if you have the MapFragment, you also have to map, just do the following:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            googleMap.setMyLocationEnabled(true)
} else {
    // Show rationale and request permission.
}

Code is in Kotlin, hope you don't mind.

have fun

Btw I think this one is a duplicate of: Show Current Location inside Google Map Fragment

How to convert TimeStamp to Date in Java?

You can use this method to get Date from Timestamp and Time-zone of particular area.

public String getDayOfTimestamp(long yourLinuxTimestamp, String timeZone) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(yourLinuxTimestamp * 1000);
    cal.setTimeZone(TimeZone.getTimeZone(timeZone));
    Date date = cal.getTime();
}

Simple insecure two-way data "obfuscation"?

The namespace System.Security.Cryptography contains the TripleDESCryptoServiceProvider and RijndaelManaged classes

Don't forget to add a reference to the System.Security assembly.

Changing the cursor in WPF sometimes works, sometimes doesn't

One way we do this in our application is using IDisposable and then with using(){} blocks to ensure the cursor is reset when done.

public class OverrideCursor : IDisposable
{

  public OverrideCursor(Cursor changeToCursor)
  {
    Mouse.OverrideCursor = changeToCursor;
  }

  #region IDisposable Members

  public void Dispose()
  {
    Mouse.OverrideCursor = null;
  }

  #endregion
}

and then in your code:

using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait))
{
  // Do work...
}

The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement.

Update

To prevent the cursor flickering you can do:

public class OverrideCursor : IDisposable
{
  static Stack<Cursor> s_Stack = new Stack<Cursor>();

  public OverrideCursor(Cursor changeToCursor)
  {
    s_Stack.Push(changeToCursor);

    if (Mouse.OverrideCursor != changeToCursor)
      Mouse.OverrideCursor = changeToCursor;
  }

  public void Dispose()
  {
    s_Stack.Pop();

    Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null;

    if (cursor != Mouse.OverrideCursor)
      Mouse.OverrideCursor = cursor;
  }

}

"Too many characters in character literal error"

I believe you can do this using a Unicode encoding, but I doubt this is what you really want.

The == is the unicode value 2A76 so I belive you can do this:

char c = '\u2A76';

I can't test this at the moment but I'd be interested to know if that works for you.

You will need to dig around for the others. Here is a unicode table if you want to look:

http://www.tamasoft.co.jp/en/general-info/unicode.html

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

There are some dedicated classes for this:

import java.text.*;

final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
   // process c
   ...
}