Programs & Examples On #Braintree

Braintree provides an API for accepting payments online and through mobile apps with a single integration.

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

It is due permission problem,

sudo chown -R $USER /path to your python installed directory

default it would be /usr/local/lib/python2.7/

or try,

pip install --user -r package_name

and then say, pip install -r requirements.txt this will install inside your env

dont say, sudo pip install -r requirements.txt this is will install into arbitrary python path.

How to input a path with a white space?

You can escape the "space" char by putting a \ right before it.

How to use Git Revert

git revert makes a new commit

git revert simply creates a new commit that is the opposite of an existing commit.

It leaves the files in the same state as if the commit that has been reverted never existed. For example, consider the following simple example:

$ cd /tmp/example
$ git init
Initialized empty Git repository in /tmp/example/.git/
$ echo "Initial text" > README.md
$ git add README.md
$ git commit -m "initial commit"
[master (root-commit) 3f7522e] initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 README.md
$ echo "bad update" > README.md 
$ git commit -am "bad update"
[master a1b9870] bad update
 1 file changed, 1 insertion(+), 1 deletion(-)

In this example the commit history has two commits and the last one is a mistake. Using git revert:

$ git revert HEAD
[master 1db4eeb] Revert "bad update"
 1 file changed, 1 insertion(+), 1 deletion(-)

There will be 3 commits in the log:

$ git log --oneline
1db4eeb Revert "bad update"
a1b9870 bad update
3f7522e initial commit

So there is a consistent history of what has happened, yet the files are as if the bad update never occured:

cat README.md 
Initial text

It doesn't matter where in the history the commit to be reverted is (in the above example, the last commit is reverted - any commit can be reverted).

Closing questions

do you have to do something else after?

A git revert is just another commit, so e.g. push to the remote so that other users can pull/fetch/merge the changes and you're done.

Do you have to commit the changes revert made or does revert directly commit to the repo?

git revert is a commit - there are no extra steps assuming reverting a single commit is what you wanted to do.

Obviously you'll need to push again and probably announce to the team.

Indeed - if the remote is in an unstable state - communicating to the rest of the team that they need to pull to get the fix (the reverting commit) would be the right thing to do :).

How do I detect if a user is already logged in Firebase?

use Firebase.getAuth(). It returns the current state of the Firebase client. Otherwise the return value is nullHere are the docs: https://www.firebase.com/docs/web/api/firebase/getauth.html

How do I encrypt and decrypt a string in python?

Although its very old, but I thought of sharing another idea to do this:

from Crypto.Cipher import AES    
from Crypto.Hash import SHA256

password = ("anything")    
hash_obj = SHA256.new(password.encode('utf-8'))    
hkey = hash_obj.digest()

def encrypt(info):
    msg = info
    BLOCK_SIZE = 16
    PAD = "{"
    padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD
    cipher = AES.new(hkey, AES.MODE_ECB)
    result = cipher.encrypt(padding(msg).encode('utf-8'))
    return result  

msg = "Hello stackoverflow!"
cipher_text = encrypt(msg)
print(cipher_text)

def decrypt(info):
    msg = info
    PAD = "{"
    decipher = AES.new(hkey, AES.MODE_ECB)
    pt = decipher.decrypt(msg).decode('utf-8')
    pad_index = pt.find(PAD)
    result = pt[: pad_index]
    return result

plaintext = decrypt(cipher_text)
print(plaintext)

Outputs:

> b'\xcb\x0b\x8c\xdc#\n\xdd\x80\xa6|\xacu\x1dEg;\x8e\xa2\xaf\x80\xea\x95\x80\x02\x13\x1aem\xcb\xf40\xdb'

> Hello stackoverflow!

What's the best three-way merge tool?

Beyond Compare 3 Pro supports three-way merging, and it is a pretty impressive merge tool. It's commercial (but worth it, IMHO) and is available on Windows, Linux, and Mac OS X.

As pointed out in a comment, it's also inexpensive.

Enter image description here

Note: If one does not have a merge set, that is, merge markers resident in the destination file, Beyond Compare does not offer three-way file compare/editing. Beyond Compare says that feature is on their list.

Note: 3-way merge is a feature in the Pro edition of Beyond Compare 3 only

iOS - Dismiss keyboard when touching outside of UITextField

How about this: I know this is an old post. It might help someone :)

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {  
    NSArray *subviews = [self.view subviews];
    for (id objects in subviews) {
        if ([objects isKindOfClass:[UITextField class]]) {
            UITextField *theTextField = objects;
            if ([objects isFirstResponder]) {
                [theTextField resignFirstResponder];
            }
        } 
    }
}

Generate random numbers using C++11 random library

You've got two common situations. The first is that you want random numbers and aren't too fussed about the quality or execution speed. In that case, use the following macro

#define uniform() (rand()/(RAND_MAX + 1.0))

that gives you p in the range 0 to 1 - epsilon (unless RAND_MAX is bigger than the precision of a double, but worry about that when you come to it).

int x = (int) (uniform() * N);

Now gives a random integer on 0 to N -1.

If you need other distributions, you have to transform p. Or sometimes it's easier to call uniform() several times.

If you want repeatable behaviour, seed with a constant, otherwise seed with a call to time().

Now if you are bothered about quality or run time performance, rewrite uniform(). But otherwise don't touch the code. Always keep uniform() on 0 to 1 minus epsilon. Now you can wrap the C++ random number library to create a better uniform(), but that's a sort of medium-level option. If you are bothered about the characteristics of the RNG, then it's also worth investing a bit of time to understand how the underlying methods work, then provide one. So you've got complete control of the code, and you can guarantee that with the same seed, the sequence will always be exactly the same, regardless of platform or which version of C++ you are linking to.

Can't compile C program on a Mac after upgrade to Mojave

apue.h dependency was still missing in my /usr/local/include after I managed to fix this problem on Mac OS Catalina following the instructions of this answer

I downloaded the dependency manually from git and placed it in /usr/local/include

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

On Windows 10 - This happened for me after the latest update in 2020.

What solved this issue for me was running the following in PowerShell

C:\>Install-Module -Name MicrosoftPowerBIMgmt

Validating file types by regular expression

Your regexp seems to validate both the file name and the extension. Is that what you need? I'll assume it's just the extension and would use a regexp like this:

\.(jpg|gif|doc|pdf)$

And set the matching to be case insensitive.

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

It's worth noting some other things:

  1. As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.

    In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.

  2. AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.

    Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.

  3. I don't know the impact upon an installer of using something other than numeric file version numbers, though.

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

jQuery to retrieve and set selected option value of html select element

When setting with JQM, don't forget to update the UI:

$('#selectId').val('newValue').selectmenu('refresh', true);

Do I need to compile the header files in a C program?

In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.

Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.

Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.

Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.

Converting List<Integer> to List<String>

This is such a basic thing to do I wouldn't use an external library (it will cause a dependency in your project that you probably don't need).

We have a class of static methods specifically crafted to do these sort of jobs. Because the code for this is so simple we let Hotspot do the optimization for us. This seems to be a theme in my code recently: write very simple (straightforward) code and let Hotspot do its magic. We rarely have performance issues around code like this - when a new VM version comes along you get all the extra speed benefits etc.

As much as I love Jakarta collections, they don't support Generics and use 1.4 as the LCD. I am wary of Google Collections because they are listed as Alpha support level!

If my interface must return Task what is the best way to have a no-operation implementation?

Task.Delay(0) as in the accepted answer was a good approach, as it is a cached copy of a completed Task.

As of 4.6 there's now Task.CompletedTask which is more explicit in its purpose, but not only does Task.Delay(0) still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask.

The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0) was better than the accepted answer.

VS 2017 Git Local Commit DB.lock error on every commit

Just add the .vs folder to the .gitignore file.

Here is the template for Visual Studio from GitHub's collection of .gitignore templates, as an example:
https://github.com/github/gitignore/blob/master/VisualStudio.gitignore


If you have any trouble adding the .gitignore file, just follow these steps:

  1. On the Team Explorer's window, go to Settings.

Team Explorer - Settings

  1. Then access Repository Settings.

Repository Settings

  1. Finally, click Add in the Ignore File section.

enter image description here

Done. ;)
This default file already includes the .vs folder.

enter image description here

Git: Remove committed file after push

  1. Get the hash code of last commit.

    • git log
  2. Revert the commit
    • git revert <hash_code_from_git_log>
  3. Push the changes
    • git push

check out in the GHR. you might get what ever you need, hope you this is useful

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

What is referencedColumnName used for in JPA?

Quoting API on referencedColumnName:

The name of the column referenced by this foreign key column.

Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.

Q/A

Where this would be used?

When there is a composite PK in referenced table, then you need to specify column name you are referencing.

How to get Javascript Select box's selected text

this.options[this.selectedIndex].innerHTML

should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

What are the undocumented features and limitations of the Windows FINDSTR command?

The findstr command sets the ErrorLevel (or exit code) to one of the following values, given that there are no invalid or incompatible switches and no search string exceeds the applicable length limit:

  • 0 when at least a single match is encountered in one line throughout all specified files;
  • 1 otherwise;

A line is considered to contain a match when:

  • no /V option is given and the search expression occurs at least once;
  • the /V option is given and the search expression does not occur;

This means that the /V option also changes the returned ErrorLevel, but it does not just revert it!

For example, when you have got a file test.txt with two lines, one of which contains the string text but the other one does not, both findstr "text" "test.txt" and findstr /V "text" "test.txt" return an ErrorLevel of 0.

Basically you can say: if findstr returns at least a line, ErrorLevel is set to 0, else to 1.

Note that the /M option does not affect the ErrorLevel value, it just alters the output.

(Just for the sake of completeness: the find command behaves exactly the same way with respect to the /V option and ErrorLevel; the /C option does not affect ErrorLevel.)

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

How to work offline with TFS

See this reference for information on how to bind/unbind your solution or project from source control. NOTE: this doesn't apply if you are using GIT and may not apply to versions later than VS2008.

Quoting from the reference:

To disconnect a solution or project from source control

  1. In Visual Studio, open Solution Explorer and select the item(s) to disconnect.

  2. On the File menu, click Source Control, then Change Source Control.

  3. In the Change Source Control dialog box, click Disconnect.

  4. Click OK.

How to determine the number of days in a month in SQL Server?

DECLARE @date nvarchar(20)
SET @date ='2012-02-09 00:00:00'
SELECT DATEDIFF(day,cast(replace(cast(YEAR(@date) as char)+'-'+cast(MONTH(@date) as char)+'-01',' ','')+' 00:00:00' as datetime),dateadd(month,1,cast(replace(cast(YEAR(@date) as char)+'-'+cast(MONTH(@date) as char)+'-01',' ','')+' 00:00:00' as datetime)))

On - window.location.hash - Change?

You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.

Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.

The code will look like this:

window.location.watch(
    'hash',
    function(id,oldVal,newVal){
        console.log("the window's hash value has changed from "+oldval+" to "+newVal);
    }
);

Then you can test it:

var myHashLink = "home";
window.location = window.location + "#" + myHashLink;

And of course that will trigger your observer function.

How to provide animation when calling another activity in Android?

Since API 16 you can supply an activity options bundle when calling Context.startActivity(Intent, Bundle) or related methods. It is created via the ActivityOptions builder:

Intent myIntent = new Intent(context, MyActivity.class);
ActivityOptions options = 
   ActivityOptions.makeCustomAnimation(context, R.anim.fade_in, R.anim.fade_out);
context.startActivity(myIntent, options.toBundle());

Don't forget to check out the other methods of the ActivityOptions builder and the ActivityOptionsCompat if you are using the Support Library.



API 5+:

For apps targeting API level 5+ there is the Activities overridePendingTransition method. It takes two resource IDs for the incoming and outgoing animations. An id of 0 will disable the animations. Call this immediately after the startActivity call.

i.e.:

startActivity(new Intent(this, MyActivity.class));
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

API 3+:

You can prevent the default animation (Slide in from the right) with the Intent.FLAG_ACTIVITY_NO_ANIMATION flag in your intent.

i.e.:

Intent myIntent = new Intent(context, MyActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(myIntent);

then in your Activity you simply have to specify your own animation.

This also works for the 1.5 API (Level 3).

linux: kill background task

You can kill by job number. When you put a task in the background you'll see something like:

$ ./script &
[1] 35341

That [1] is the job number and can be referenced like:

$ kill %1
$ kill %%  # Most recent background job

To see a list of job numbers use the jobs command. More from man bash:

There are a number of ways to refer to a job in the shell. The character % introduces a job name. Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification) also refers to the current job.

ReactJS lifecycle method inside a function Component

According to the documentation:

import React, { useState, useEffect } from 'react'
// Similar to componentDidMount and componentDidUpdate:

useEffect(() => {


});

see React documentation

How can I push a specific commit to a remote, and not previous commits?

You could also, in another directory:

  • git clone [your repository]
  • Overwrite the .git directory in your original repository with the .git directory of the repository you just cloned right now.
  • git add and git commit your original

Stop handler.postDelayed()

You can use:

 Handler handler = new Handler()
 handler.postDelayed(new Runnable())

Or you can use:

 handler.removeCallbacksAndMessages(null);

Docs

public final void removeCallbacksAndMessages (Object token)

Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Or you could also do like the following:

Handler handler =  new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
    // do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);

Then:

handler.removeCallbacks(myRunnable);

Docs

public final void removeCallbacks (Runnable r)

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

public final void removeCallbacks (Runnable r, Object token)

Edit:

Change this:

@Override
public void onClick(View v) {
    Handler handler =  new Handler();
    Runnable myRunnable = new Runnable() {

To:

@Override
public void onClick(View v) {
    handler = new Handler();
    myRunnable = new Runnable() { /* ... */}

Because you have the below. Declared before onCreate but you re-declared and then initialized it in onClick leading to a NPE.

Handler handler; // declared before onCreate
Runnable myRunnable;

Use of alloc init instead of new

Very old question, but I've written some example just for fun — maybe you'll find it useful ;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

In main function both statements:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

result in the same output:

2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating...
2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...

Checking whether the pip is installed?

pip list is a shell command. You should run it in your shell (bash/cmd), rather than invoke it from python interpreter.

pip does not provide a stable API. The only supported way of calling it is via subprocess, see docs and the code at the end of this answer.

However, if you want to just check if pip exists locally, without running it, and you are running Linux, I would suggest that you use bash's which command:

which pip

It should show you whether the command can be found in bash's PATH/aliases, and if it does, what does it actually execute.

If running pip is not an issue, you could just do:

python -m pip --version

If you really need to do it from a python script, you can always put the import statement into a try...except block:

try:
    import pip
except ImportError:
    print("Pip not present.")

Or check what's the output of a pip --version using subprocess module:

subprocess.check_call([sys.executable, '-m', 'pip', '--version'])

Generate a random number in the range 1 - 10

If you are using SQL Server then correct way to get integer is

SELECT Cast(RAND()*(b-a)+a as int);

Where

  • 'b' is the upper limit
  • 'a' is lower limit

Range of values in C Int and Long 32 - 64 bits

In fact, unsigned int on most modern processors (ARM, Intel/AMD, Alpha, SPARC, Itanium ,PowerPC) will have a range of 0 to 2^32 - 1 which is 4,294,967,295 = 0xffffffff because int (both signed and unsigned) will be 32 bits long and the largest one is as stated.

(unsigned short will have maximal value 2^16 - 1 = 65,535 )

(unsigned) long long int will have a length of 64 bits (long int will be enough under most 64 bit Linuxes, etc, but the standard promises 64 bits for long long int). Hence these have the range 0 to 2^64 - 1 = 18446744073709551615

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

JQuery create new select option

What about

var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);

Can't use modulus on doubles?

Use fmod() from <cmath>. If you do not want to include the C header file:

template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
    return !mod ? x : x - mod * static_cast<long long>(x / mod);
}

//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

Vertically centering Bootstrap modal window

This is what I did for my app. If you take a look at the following classes in the bootstrap.css file .modal-dialog has a default padding of 10px and @media screen and (min-width: 768px) .modal-dialog has a top padding set to 30px. So in my custom css file I set my top padding to be 15% for all screens without specifying a media screen width. Hope this helps.

.modal-dialog {
  padding-top: 15%;
}

Wget output document and headers to STDOUT

Try the following, no extra headers

wget -qO- www.google.com

Note the trailing -. This is part of the normal command argument for -O to cat out to a file, but since we don't use > to direct to a file, it goes out to the shell. You can use -qO- or -qO -.

querySelector, wildcard element match?

There is a way by saying what is is not. Just make the not something it never will be. A good css selector reference: https://www.w3schools.com/cssref/css_selectors.asp which shows the :not selector as follows:

:not(selector)  :not(p) Selects every element that is not a <p> element

Here is an example: a div followed by something (anything but a z tag)

div > :not(z){
 border:1px solid pink;
}

SQL Delete Records within a specific Range

you can also just change your delete to a select *

and test your selection

the records selected will be the same as the ones deleted

you can also wrap your statement in a begin / rollback if you are not sure - test the statement then if all is good remove rollback

for example

SELECT * FROM table WHERE id BETWEEN 79 AND 296

will show all the records matching the where if they are the wants you 'really' want to delete then use

DELETE FROM table WHERE id BETWEEN 79 AND 296

You can also create a trigger / which catches deletes and puts them into a history table

so if you delete something by mistake you can always get it back

(keep your history table records no older than say 6 months or whatever business rules say)

Change value of input placeholder via model?

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';

Standardize data columns in R

@BBKim pretty much gave the best answer, but it can just be done shorter. I'm surprised noone came up with it yet.

dat <- data.frame(x = rnorm(10, 30, .2), y = runif(10, 3, 5)) dat <- apply(dat, 2, function(x) (x - mean(x)) / sd(x))

How can I String.Format a TimeSpan object with a custom format in .NET?

You can also go with:

Dim ts As New TimeSpan(35, 21, 59, 59)  '(11, 22, 30, 30)    '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")

EDIT:

You can also look at Strings.Format.

    Dim ts As New TimeSpan(23, 30, 59)
    Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")

Why std::cout instead of simply cout?

If you are working in ROOT, you do not even have to write #include<iostream> and using namespace std; simply start from int filename().

This will solve the issue.

Basic text editor in command prompt?

vim may be challenging for beginners. For a quick-and-dirty Windows console-mode text editor, I would suggest Kinesics Text Editor.

Can I pass parameters in computed properties in Vue.Js

Computed could be consider has a function. So for an exemple on valdiation you could clearly do something like :

    methods: {
        validation(attr){
            switch(attr) {
                case 'email':
                    const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
                    return re.test(this.form.email);
                case 'password':
                    return this.form.password.length > 4
            }
        },
        ...
    }

Which you'll be using like :

  <b-form-input
            id="email"
            v-model="form.email"
            type="email"
            :state="validation('email')"
            required
            placeholder="Enter email"
    ></b-form-input>

Just keep in mind that you will still miss the caching specific to computed.

Java Object Null Check for method

This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.

For JDK 7 users, Here using

Objects.requireNotNull(object[, optionalMessage]);

is not safe. This function throws NullPointerException if it finds null object and which is a RunTimeException.

That will terminate the whole program!!. So better check null using == or !=.

Also, use List instead of Array. Although access speed is same, yet using Collections over Array has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector without rewriting all your code.

public static double calculateInventoryTotal(List<Book> books) {
    if (books == null || books.isEmpty()) {
        return 0;
    }

    double total = 0;

    for (Book book : books) {
        if (book != null) {
            total += book.getPrice();
        }
    }
    return total;
}

Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.

Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException. It defined a new class called Optional. Have a look at this for detail

Finally, Pardon my bad English.

Java: Local variable mi defined in an enclosing scope must be final or effectively final

Yes this is happening because you are accessing mi variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi so that's why its telling you to set it to final.

Remove the last character from a string

You can use substr:

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Python: how can I check whether an object is of type datetime.date?

In Python 3.5, isinstance(x, date) works to me:

>>> from datetime import date
>>> x = date(2012, 9, 1)
>>> type(x)
<class 'datetime.date'>
>>> isinstance(x, date)
True
>>> type(x) is date
True

Is it possible to use jQuery .on and hover?

If you need it to have as a condition in an other event, I solved it this way:

$('.classname').hover(
     function(){$(this).data('hover',true);},
     function(){$(this).data('hover',false);}
);

Then in another event, you can easily use it:

 if ($(this).data('hover')){
      //...
 }

(I see some using is(':hover') to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)

How do I properly escape quotes inside HTML attributes?

Another option is replacing double quotes with single quotes if you don't mind whatever it is. But I don't mention this one:

<option value='"asd'>test</option>

I mention this one:

<option value="'asd">test</option>

In my case I used this solution.

Implement touch using Python?

If you don't mind the try-except then...

def touch_dir(folder_path):
    try:
        os.mkdir(folder_path)
    except FileExistsError:
        pass

One thing to note though, if a file exists with the same name then it won't work and will fail silently.

Stop Chrome Caching My JS Files

Hold shift while clicking the reload button.

How do I prevent and/or handle a StackOverflowException?

If you application depends on 3d-party code (in Xsl-scripts) then you have to decide first do you want to defend from bugs in them or not. If you really want to defend then I think you should execute your logic which prone to external errors in separate AppDomains. Catching StackOverflowException is not good.

Check also this question.

Save bitmap to location

Save Bitmap to your Gallery Without Compress.

private File saveBitMap(Context context, Bitmap Final_bitmap) {
    File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Your Folder Name");
    if (!pictureFileDir.exists()) {
        boolean isDirectoryCreated = pictureFileDir.mkdirs();
        if (!isDirectoryCreated)
            Log.i("TAG", "Can't create directory to save the image");
        return null;
    }
    String filename = pictureFileDir.getPath() + File.separator + System.currentTimeMillis() + ".jpg";
    File pictureFile = new File(filename);
    try {
        pictureFile.createNewFile();
        FileOutputStream oStream = new FileOutputStream(pictureFile);
        Final_bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
        oStream.flush();
        oStream.close();
        Toast.makeText(Full_Screen_Activity.this, "Save Image Successfully..", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TAG", "There was an issue saving the image.");
    }
    scanGallery(context, pictureFile.getAbsolutePath());
    return pictureFile;
}
private void scanGallery(Context cntx, String path) {
    try {
        MediaScannerConnection.scanFile(cntx, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Toast.makeText(Full_Screen_Activity.this, "Save Image Successfully..", Toast.LENGTH_SHORT).show();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        Log.i("TAG", "There was an issue scanning gallery.");
    }
}

How to convert numpy arrays to standard TensorFlow format?

You can use tf.convert_to_tensor():

import tensorflow as tf
import numpy as np

data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)

data_tf = tf.convert_to_tensor(data_np, np.float32)

sess = tf.InteractiveSession()  
print(data_tf.eval())

sess.close()

Here's a link to the documentation for this method:

https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor

Force youtube embed to start in 720p

I've managed to get this working by the following fix:

//www.youtube.com/embed/_YOUR_VIDEO_CODE_/?vq=hd720

You video should have the hd720 resolution to do so.

I was using the embedding via iframe, BTW. Hope someone will find this helpful.

CFNetwork SSLHandshake failed iOS 9

In iOS 10+, the TLS string MUST be of the form "TLSv1.0". It can't just be "1.0". (Sigh)


The following combination of the other Answers works.

Let's say you are trying to connect to a host (YOUR_HOST.COM) that only has TLS 1.0.

Add these to your app's Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>YOUR_HOST.COM</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>

How to give a pattern for new line in grep?

As for the workaround (without using non-portable -P), you can temporary replace a new-line character with the different one and change it back, e.g.:

grep -o "_foo_" <(paste -sd_ file) | tr -d '_'

Basically it's looking for exact match _foo_ where _ means \n (so __ = \n\n). You don't have to translate it back by tr '_' '\n', as each pattern would be printed in the new line anyway, so removing _ is enough.

How can I get a side-by-side diff when I do "git diff"?

I personally really like icdiff !

If you're on Mac OS X with HomeBrew, just do brew install icdiff.

To get the file labels correctly, plus other cool features, I have in my ~/.gitconfig:

[pager]
    difftool = true
[diff]
    tool = icdiff
[difftool "icdiff"]
    cmd = icdiff --head=5000 --highlight --line-numbers -L \"$BASE\" -L \"$REMOTE\" \"$LOCAL\" \"$REMOTE\"

And I use it like: git difftool

WHERE Clause to find all records in a specific month

Can I just ask to compare based on the year and month?

You can. Here's a simple example using the AdventureWorks sample database...

DECLARE @Year       INT
DECLARE @Month      INT

SET @Year = 2002
SET @Month = 6

SELECT 
    [pch].* 
FROM 
    [Production].[ProductCostHistory]   pch
WHERE
    YEAR([pch].[ModifiedDate]) = @Year
AND MONTH([pch].[ModifiedDate]) = @Month

Static nested class in Java, why?

Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.

As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.

How to enable bulk permission in SQL Server

Try GRANT ADMINISTER BULK OPERATIONS TO [server_login]. It is a server level permission, not a database level. This has fixed a similar issue for me in that past (using OPENROWSET I believe).

htaccess remove index.php from url

Steps to remove index.php from url for your wordpress website.

  1. Check you should have mod_rewrite enabled at your server. To check whether it's enabled or not - Create 1 file phpinfo.php at your root folder with below command.
 <?php
   phpinfo?();
 ?>

Now run this file - www.yoursite.com/phpinfo.php and it will show mod_rewrite at Load modules section. If not enabled then perform below commands at your terminal.

sudo a2enmod rewrite
sudo service apache2 restart
  1. Make sure your .htaccess is existing in your WordPress root folder, if not create one .htaccess file Paste this code at your .htaccess file :-
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
</IfModule>  
  1. Further make permission of .htaccess to 666 so that it become writable and now you can do changes in your wordpress permalinks.

  2. Now go to Settings -> permalinks -> and change to your needed url format. Remove this code /index.php/%year%/%monthnum%/%day%/%postname%/ and insert this code on Custom Structure: /%postname%/

  3. If still not succeeded then check your hosting, mine was digitalocean server, so I cleared it myself

Edited the file /etc/apache2/sites-enabled/000-default.conf

Added this line after DocumentRoot /var/www/html

<Directory /var/www/html>
   AllowOverride All
</Directory>

Restart your apache server

Note: /var/www/html will be your document root

Indentation shortcuts in Visual Studio

You can just use Tab and Shift+Tab

How do you rename a Git tag?

Here is how I rename a tag old to new:

git tag new old
git tag -d old
git push origin new :old

The colon in the push command removes the tag from the remote repository. If you don't do this, Git will create the old tag on your machine when you pull. Finally, make sure that the other users remove the deleted tag. Please tell them (co-workers) to run the following command:

git pull --prune --tags

Note that if you are changing an annotated tag, you need ensure that the new tag name is referencing the underlying commit and not the old annotated tag object that you're about to delete. Therefore, use git tag -a new old^{} instead of git tag new old (this is because annotated tags are objects while lightweight tags are not, more info in this answer).

how to display a javascript var in html body

Try This...

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    function myFunction() {_x000D_
      var number = "123";_x000D_
      document.getElementById("myText").innerHTML = number;_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="myFunction()">_x000D_
_x000D_
  <h1>"The value for number is: " <span id="myText"></span></h1>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Amazon Interview Question: Design an OO parking lot

public class ParkingLot 
{
    Vector<ParkingSpace> vacantParkingSpaces = null;
    Vector<ParkingSpace> fullParkingSpaces = null;

    int parkingSpaceCount = 0;

    boolean isFull;
    boolean isEmpty;

    ParkingSpace findNearestVacant(ParkingType type)
    {
        Iterator<ParkingSpace> itr = vacantParkingSpaces.iterator();

        while(itr.hasNext())
        {
            ParkingSpace parkingSpace = itr.next();

            if(parkingSpace.parkingType == type)
            {
                return parkingSpace;
            }
        }
        return null;
    }

    void parkVehicle(ParkingType type, Vehicle vehicle)
    {
        if(!isFull())
        {
            ParkingSpace parkingSpace = findNearestVacant(type);

            if(parkingSpace != null)
            {
                parkingSpace.vehicle = vehicle;
                parkingSpace.isVacant = false;

                vacantParkingSpaces.remove(parkingSpace);
                fullParkingSpaces.add(parkingSpace);

                if(fullParkingSpaces.size() == parkingSpaceCount)
                    isFull = true;

                isEmpty = false;
            }
        }
    }

    void releaseVehicle(Vehicle vehicle)
    {
        if(!isEmpty())
        {
            Iterator<ParkingSpace> itr = fullParkingSpaces.iterator();

            while(itr.hasNext())
            {
                ParkingSpace parkingSpace = itr.next();

                if(parkingSpace.vehicle.equals(vehicle))
                {
                    fullParkingSpaces.remove(parkingSpace);
                    vacantParkingSpaces.add(parkingSpace);

                    parkingSpace.isVacant = true;
                    parkingSpace.vehicle = null;

                    if(vacantParkingSpaces.size() == parkingSpaceCount)
                        isEmpty = true;

                    isFull = false;
                }
            }
        }
    }

    boolean isFull()
    {
        return isFull;
    }

    boolean isEmpty()
    {
        return isEmpty;
    }
}

public class ParkingSpace 
{
    boolean isVacant;
    Vehicle vehicle;
    ParkingType parkingType;
    int distance;
}

public class Vehicle 
{
    int num;
}

public enum ParkingType
{
    REGULAR,
    HANDICAPPED,
    COMPACT,
    MAX_PARKING_TYPE,
}

How to get a substring of text?

If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)

Zero-pad digits in string

The performance of str_pad heavily depends on the length of padding. For more consistent speed you can use str_repeat.

$padded_string = str_repeat("0", $length-strlen($number)) . $number;

Also use string value of the number for better performance.

$number = strval(123);

Tested on PHP 7.4

str_repeat: 0.086055040359497   (number: 123, padding: 1)
str_repeat: 0.085798978805542   (number: 123, padding: 3)
str_repeat: 0.085641145706177   (number: 123, padding: 10)
str_repeat: 0.091305017471313   (number: 123, padding: 100)

str_pad:    0.086184978485107   (number: 123, padding: 1)
str_pad:    0.096981048583984   (number: 123, padding: 3)
str_pad:    0.14874792098999    (number: 123, padding: 10)
str_pad:    0.85979700088501    (number: 123, padding: 100)

Add primary key to existing table

Necromancing.
Just in case anybody has as good a schema to work with as me...
Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists (it is very possible it does not have the name you think it has...)
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 
        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';

        -- Check if they keys are unique (it is very possible they might not be)        
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

What is the difference between Promises and Observables?

Promises

  1. Definition: Helps you run functions asynchronously, and use their return values (or exceptions) but only once when executed.
  2. Not Lazy
  3. Not cancellable( There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far). The two possible decisions are
    • Reject
    • Resolve
  4. Cannot be retried(Promises should have access to the original function that returned the promise to have a retry capability, which is a bad practice)

Observables

  1. Definition: Helps you run functions asynchronously, and use their return values in a continuous sequence(multiple times) when executed.
  2. By default, it is Lazy as it emits values when time progresses.
  3. Has a lot of operators which simplifies the coding effort.
  4. One operator retry can be used to retry whenever needed, also if we need to retry the observable based on some conditions retryWhen can be used.

    Note: A list of operators along with their interactive diagrams is available here at RxMarbles.com

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Adding script tag to React/JSX

My favorite way is to use React Helmet – it's a component that allows for easy manipulation of the document head in a way you're probably already used to.

e.g.

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <script src="https://use.typekit.net/foobar.js"></script>
                <script>try{Typekit.load({ async: true });}catch(e){}</script>
            </Helmet>
            ...
        </div>
    );
  }
};

https://github.com/nfl/react-helmet

How to update values using pymongo?

in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})

How to get JS variable to retain value after page refresh?

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage

Ex: using localStorage and cookies library

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

What does "&" at the end of a linux command mean?

When not told otherwise commands take over the foreground. You only have one "foreground" process running in a single shell session. The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.

sh my_script.sh &

A background process will not stay alive after the shell session is closed. SIGHUP terminates all running processes. By default anyway. If your command is long-running or runs indefinitely (ie: microservice) you need to pr-pend it with nohup so it remains running after you disconnect from the session:

nohup sh my_script.sh &

EDIT: There does appear to be a gray area regarding the closing of background processes when & is used. Just be aware that the shell may close your process depending on your OS and local configurations (particularly on CENTOS/RHEL): https://serverfault.com/a/117157.

Angular and debounce

DebounceTime in Angular 7 with RxJS v6

Source Link

Demo Link

enter image description here

In HTML Template

<input type="text" #movieSearchInput class="form-control"
            placeholder="Type any movie name" [(ngModel)]="searchTermModel" />

In component

    ....
    ....
    export class AppComponent implements OnInit {

    @ViewChild('movieSearchInput') movieSearchInput: ElementRef;
    apiResponse:any;
    isSearching:boolean;

        constructor(
        private httpClient: HttpClient
        ) {
        this.isSearching = false;
        this.apiResponse = [];
        }

    ngOnInit() {
        fromEvent(this.movieSearchInput.nativeElement, 'keyup').pipe(
        // get value
        map((event: any) => {
            return event.target.value;
        })
        // if character length greater then 2
        ,filter(res => res.length > 2)
        // Time in milliseconds between key events
        ,debounceTime(1000)        
        // If previous query is diffent from current   
        ,distinctUntilChanged()
        // subscription for response
        ).subscribe((text: string) => {
            this.isSearching = true;
            this.searchGetCall(text).subscribe((res)=>{
            console.log('res',res);
            this.isSearching = false;
            this.apiResponse = res;
            },(err)=>{
            this.isSearching = false;
            console.log('error',err);
            });
        });
    }

    searchGetCall(term: string) {
        if (term === '') {
        return of([]);
        }
        return this.httpClient.get('http://www.omdbapi.com/?s=' + term + '&apikey=' + APIKEY,{params: PARAMS.set('search', term)});
    }

    }

Breaking a list into multiple columns in Latex

By combining the multicol package and enumitem package packages it is easy to define environments that are multi-column analogues of the enumerate and itemize environments:

\documentclass{article}
\usepackage{enumitem}
\usepackage{multicol}

\newlist{multienum}{enumerate}{1}
\setlist[multienum]{
    label=\alph*),
    before=\begin{multicols}{2},
    after=\end{multicols}
}

\newlist{multiitem}{itemize}{1}
\setlist[multiitem]{
    label=\textbullet,
    before=\begin{multicols}{2},
    after=\end{multicols}
}

\begin{document}

  \textsf{Two column enumerate}
  \begin{multienum}
    \item item 1
    \item item 2
    \item item 3
    \item item 4
    \item item 5
    \item item 6
  \end{multienum}

  \textsf{Two column itemize}
  \begin{multiitem}
    \item item 1
    \item item 2
    \item item 3
    \item item 4
    \item item 5
    \item item 6
  \end{multiitem}

\end{document}

The output is what you would hope for:

enter image description here

How to manually set an authenticated user in Spring Security / SpringMVC

I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method.

public String registerUser(UserRegistrationFormBean userRegistrationFormBean,
                           RequestContext requestContext,
                           ExternalContext externalContext) {

    try {
        Locale userLocale = requestContext.getExternalContext().getLocale();
        this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID);
        String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress();
        String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword();
        doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest());
        return "success";

    } catch (EmailAddressNotUniqueException e) {
        MessageResolver messageResolvable 
                = new MessageBuilder().error()
                                      .source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS)
                                      .code("userRegistration.emailAddress.not.unique")
                                      .build();
        requestContext.getMessageContext().addMessage(messageResolvable);
        return "error";
    }

}


private void doAutoLogin(String username, String password, HttpServletRequest request) {

    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = this.authenticationProvider.authenticate(token);
        logger.debug("Logging in with [{}]", authentication.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        logger.error("Failure in autoLogin", e);
    }

}

Selector on background color of TextView

Benoit's solution works, but you really don't need to incur the overhead to draw a shape. Since colors can be drawables, just define a color in a /res/values/colors.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="semitransparent_white">#77ffffff</color>
</resources>

And then use as such in your selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@color/semitransparent_white" />
</selector>

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

Moving all files from one directory to another using Python

For example, if I wanted to move all .txt files from one location to another ( on a Windows OS for instance ) I would do it something like this:

import shutil
import os,glob

inpath = 'R:/demo/in' 
outpath = 'R:/demo/out'

os.chdir(inpath)
for file in glob.glob("*.txt"):

    shutil.move(inpath+'/'+file,outpath)

Where can I find WcfTestClient.exe (part of Visual Studio)

C:\Program Files (x86)\Microsoft Visual Studio (Your Version Here)\Common7\IDE

Import python package from local directory into interpreter

You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course from . import (which means "import from the same package I got imported from") doesn't work. import mypackage will be fine once you ensure the parent directory of mypackage is in sys.path (how you managed to get your current directory away from sys.path I don't know -- do you have something strange in site.py, or...?)

To get your current directory back into sys.path there is in fact no better way than putting it there.

Make elasticsearch only return certain fields?

response_filtering

All REST APIs accept a filter_path parameter that can be used to reduce the response returned by elasticsearch. This parameter takes a comma separated list of filters expressed with the dot notation.

https://stackoverflow.com/a/35647027/844700

How to insert Records in Database using C# language?

There are many problems in your query.
This is a modified version of your code

string connetionString = null;
string sql = null;

// All the info required to reach your db. See connectionstrings.com
connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;

// Prepare a proper parameterized query 
sql = "insert into Main ([Firt Name], [Last Name]) values(@first,@last)";

// Create the connection (and be sure to dispose it at the end)
using(SqlConnection cnn = new SqlConnection(connetionString))
{
    try
    {
       // Open the connection to the database. 
       // This is the first critical step in the process.
       // If we cannot reach the db then we have connectivity problems
       cnn.Open();

       // Prepare the command to be executed on the db
       using(SqlCommand cmd = new SqlCommand(sql, cnn))
       {
           // Create and set the parameters values 
           cmd.Parameters.Add("@first", SqlDbType.NVarChar).Value = textbox2.text;
           cmd.Parameters.Add("@last", SqlDbType.NVarChar).Value = textbox3.text;

           // Let's ask the db to execute the query
           int rowsAdded = cmd.ExecuteNonQuery();
           if(rowsAdded > 0) 
              MessageBox.Show ("Row inserted!!" + );
           else
              // Well this should never really happen
              MessageBox.Show ("No row inserted");

       }
    }
    catch(Exception ex)
    {
        // We should log the error somewhere, 
        // for this example let's just show a message
        MessageBox.Show("ERROR:" + ex.Message);
    }
}
  • The column names contain spaces (this should be avoided) thus you need square brackets around them
  • You need to use the using statement to be sure that the connection will be closed and resources released
  • You put the controls directly in the string, but this don't work
  • You need to use a parametrized query to avoid quoting problems and sqlinjiection attacks
  • No need to use a DataAdapter for a simple insert query
  • Do not use AddWithValue because it could be a source of bugs (See link below)

Apart from this, there are other potential problems. What if the user doesn't input anything in the textbox controls? Do you have done any checking on this before trying to insert? As I have said the fields names contain spaces and this will cause inconveniences in your code. Try to change those field names.

This code assumes that your database columns are of type NVARCHAR, if not, then use the appropriate SqlDbType enum value.

Please plan to switch to a more recent version of NET Framework as soon as possible. The 1.1 is really obsolete now.

And, about AddWithValue problems, this article explain why we should avoid it. Can we stop using AddWithValue() already?

Prevent any form of page refresh using jQuery/Javascript

Although its not a good idea to disable F5 key you can do it in JQuery as below.

<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).ready(function(){
     $(document).on("keydown", disableF5);
});
</script>

Hope this will help!

How can I get the named parameters from a URL using Flask?

Template Code

<table>
     <tr>
      <th style="min-width: 70px;">Sl No.</th>
      <th style="min-width: 350px;">Description</th>
      <th style="min-width: 100px;">Date</th>
      <th style="min-width: 50px;">Time</th>
      <th style="min-width: 50px;">Status</th>
      <th style="min-width: 50px;">Action</th>
      </tr>
      {% set count = [0] %}
      {% for val in data['todos']%}
      {% if count.append(count.pop() + 1) %}{% endif %}
      <tr>
      <td>{{count[0]}}</td>
      <td>{{val['description']}}</td>
      <td>{{val['date']}}</td>
      <td>{{val['time']}}</td>
      <td>{{val['status']}}</td>
      <td>
        <a class="fa fa-edit" href="#" style=" color: rgb(32, 252, 43);" ></a>
        <a class="fa fa-trash-alt" href="http://localhost:5000/delete?todoid={{val['_id']}}" onmouseout="this.style.color=' rgb(248, 153, 153)'" onmouseover="this.style.color='rgb(241, 74, 74)'" style="padding-left:8%; color: rgb(248, 153, 153);"></a>
      </td>
     </tr>
     {% endfor %}
    </table>

Route code

@app.route('/delete', methods=["GET"])
def deleteTodo():
id = request.args.get('todoid')
print(id)

Structs in Javascript

The only difference between object literals and constructed objects are the properties inherited from the prototype.

var o = {
  'a': 3, 'b': 4,
  'doStuff': function() {
    alert(this.a + this.b);
  }
};
o.doStuff(); // displays: 7

You could make a struct factory.

function makeStruct(names) {
  var names = names.split(' ');
  var count = names.length;
  function constructor() {
    for (var i = 0; i < count; i++) {
      this[names[i]] = arguments[i];
    }
  }
  return constructor;
}

var Item = makeStruct("id speaker country");
var row = new Item(1, 'john', 'au');
alert(row.speaker); // displays: john

Call a Javascript function every 5 seconds continuously

As best coding practices suggests, use setTimeout instead of setInterval.

function foo() {

    // your function code here

    setTimeout(foo, 5000);
}

foo();

Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout function that will be later call the same function again.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

Eclipse change project files location

If you have your project saved as a local copy of a repository, it may be better to import from git. Select local, and then browse to your git repository folder. That worked better for me than importing it as an existing project. Attempting the latter did not allow me to "finish".

Android - get children inside a View?

You can always access child views via View.findViewById() http://developer.android.com/reference/android/view/View.html#findViewById(int).

For example, within an activity / view:

...
private void init() {
  View child1 = findViewById(R.id.child1);
}
...

or if you have a reference to a view:

...
private void init(View root) {
  View child2 = root.findViewById(R.id.child2);
}

what does numpy ndarray shape do?

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

enter image description here

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

I have same problem but with different situation. I can compile without any issue with maven in command line (mvn clean install), but in Intellij I always got "java: diamond operator is not supported in -source 1.5" compile error despite I have set the maven-compiler-plugin with java 1.8 in the pom.xml.

It turned out I have remote repository setting in my maven's settings.xml which the project depends on, but Intellij uses his own maven which doesn't have same setting with my local maven.

So my solution was changing the Intellij's maven setting (Settings -> Build, execution, Deployment -> Maven -> Maven home directory) to use the local maven.

How to use java.net.URLConnection to fire and handle HTTP requests?

You can also use JdkRequest from jcabi-http (I'm a developer), which does all this work for you, decorating HttpURLConnection, firing HTTP requests and parsing responses, for example:

String html = new JdkRequest("http://www.google.com").fetch().body();

Check this blog post for more info: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html

Determine if a String is an Integer in Java

public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}

Disable button in angular with two conditions?

In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.

Your problem started like this:

enabled  = A and B
disabled = not ( A and B )

So far so good, but you went one step further and tried to remove the braces. And that's a little tricky, because you have to replace the and/&& with an or/||.

not ( A and B ) = not(A) OR not(B)

Or in a more mathematical notation:

enter image description here

I always keep this law in mind whenever I simplify conditions or work with probabilities.

Change column type in pandas

How about creating two dataframes, each with different data types for their columns, and then appending them together?

d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))

Results

In[8}:  d1.dtypes
Out[8]: 
float_column     float64
string_column     object
dtype: object

After the dataframe is created, you can populate it with floating point variables in the 1st column, and strings (or any data type you desire) in the 2nd column.

How do you subtract Dates in Java?

You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

How to remove underline from a name on hover

To keep the color and prevent an underline on the link:

legend.green-color a{
    color:green;
    text-decoration: none;
}

Up, Down, Left and Right arrow keys do not trigger KeyDown event

The best way to do, I think, is to handle it like the MSDN said on http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx

But handle it, how you really need it. My way (in the example below) is to catch every KeyDown ;-)

    /// <summary>
    /// onPreviewKeyDown
    /// </summary>
    /// <param name="e"></param>
    protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
    {
        e.IsInputKey = true;
    }

    /// <summary>
    /// onKeyDown
    /// </summary>
    /// <param name="e"></param>
    protected override void OnKeyDown(KeyEventArgs e)
    {
        Input.SetFlag(e.KeyCode);
        e.Handled = true;
    }

    /// <summary>
    /// onKeyUp
    /// </summary>
    /// <param name="e"></param>
    protected override void OnKeyUp(KeyEventArgs e)
    {
        Input.RemoveFlag(e.KeyCode);
        e.Handled = true;
    }

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

jQuery select child element by class with unknown path

This should do the trick:

$('#thisElement').find('.classToSelect')

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

For Pycharm CE 2018.3 and Ubuntu 18.04 with snap installation:

env BAMF_DESKTOP_FILE_HINT=/var/lib/snapd/desktop/applications/pycharm-community_pycharm-community.desktop /snap/bin/pycharm-community %f

I get this command from KDE desktop launch icon.

pychar-ce-command

Sorry for the language but I am a Spanish developer so I have my system in Spanish.

How can I get client information such as OS and browser

Update: The project is EOL and not maintained anymore. He recommends switching to the Browscap project.

You can use the bitwalker useragentutils library: https://github.com/HaraldWalker/user-agent-utils. It will provide you information about the Browser (name, type, version, manufacturer, etc.) and about the OperatingSystem. A good thing about it is that it is maintained. Access the link that I have provided to see the Maven dependency that you need to add to you project in order to use it.

See below sample code that returns the browser name and browser version.

    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    Browser browser = userAgent.getBrowser();

    String browserName = browser.getName();
    //or 
    // String browserName = browser.getGroup().getName();
    Version browserVersion = userAgent.getBrowserVersion();
    System.out.println("The user is using browser " + browserName + " - version " + browserVersion);

Is it safe to clean docker/overlay2/

I found this worked best for me:

docker image prune --all

By default Docker will not remove named images, even if they are unused. This command will remove unused images.

Note each layer in an image is a folder inside the /usr/lib/docker/overlay2/ folder.

How can I disable inherited css styles?

Give the div you don't want him inheriting the property background too.

How to place a div below another div?

You have set #slider as absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

You can read about CSS positioning here

If you set both to relative, the divs will be one after the other, as shown here:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

Echoing the last command run in Bash?

After reading the answer from Gilles, I decided to see if the $BASH_COMMAND var was also available (and the desired value) in an EXIT trap - and it is!

So, the following bash script works as expected:

#!/bin/bash

exit_trap () {
  local lc="$BASH_COMMAND" rc=$?
  echo "Command [$lc] exited with code [$rc]"
}

trap exit_trap EXIT
set -e

echo "foo"
false 12345
echo "bar"

The output is

foo
Command [false 12345] exited with code [1]

bar is never printed because set -e causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345 passed to false is just there to show that the arguments to the failed command are captured as well (the false command ignores any arguments passed to it)

How do I declare a namespace in JavaScript?

I use the approach found on the Enterprise jQuery site:

Here is their example showing how to declare private & public properties and functions. Everything is done as a self-executing anonymous function.

(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }
}( window.skillet = window.skillet || {}, jQuery ));

So if you want to access one of the public members you would just go skillet.fry() or skillet.ingredients.

What's really cool is that you can now extend the namespace using the exact same syntax.

//Adding new Functionality to the skillet
(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + " " +
                     skillet.ingredient + " & " +
                     amountOfGrease + " of Grease" );
        console.log( isHot ? "Hot" : "Cold" );
    };
}( window.skillet = window.skillet || {}, jQuery ));

The third undefined argument

The third, undefined argument is the source of the variable of value undefined. I'm not sure if it's still relevant today, but while working with older browsers / JavaScript standards (ecmascript 5, javascript < 1.8.5 ~ firefox 4), the global-scope variable undefined is writable, so anyone could rewrite its value. The third argument (when not passed a value) creates a variable named undefined which is scoped to the namespace/function. Because no value was passed when you created the name space, it defaults to the value undefined.

Access 2013 - Cannot open a database created with a previous version of your application

Non-Programming Answer: Download and install an older version of the Access Database Engine (2010 or 2007 for example, rather than 2013). Open Excel, navigate to the "Data" tab on the Ribbon and click "From Access". Import the data into Excel, and then Export to an accdb file or do whatever with it. NOTE! opening Access 2013 will trigger a re-install of the 2013 engine, so keep the 2007/2010 installation .exe around.

Programming Answer: Having installed an older version of Access Database Engine, you can use an OLEDB connection in multiple programming environments (C#, VBA, VBScript, etc.) to read/write and move Access data. Gord Thompson's answer also presents the option of jumping to SQL server and back.

See This post for a similar problem using an OLEDB connection

Connectionstrings.com is a great resource

See this post for how to setup an OLEDB connection using C#

Remove xticks in a matplotlib plot?

Those of you looking for a short command to switch off all ticks and labels should be fine with

plt.tick_params(top=False, bottom=False, left=False, right=False,
                labelleft=False, labelbottom=False)

which allows type bool for respective parameters since version matplotlib>=2.1.1

For custom tick settings, the docs are helpful:

https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html

How to concatenate strings in twig

The operator you are looking for is Tilde (~), like Alessandro said, and here it is in the documentation:

~: Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is 'John') Hello John!. – http://twig.sensiolabs.org/doc/templates.html#other-operators

And here is an example somewhere else in the docs:

{% set greeting = 'Hello' %}
{% set name = 'Fabien' %}

{{ greeting ~ name|lower }}   {# Hello fabien #}

{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

Just had this happen to me.

Apparently Java's automatic updater installed and configured a new version of the JRE for me, while leaving the old JDK intact. So even though I did have a JDK, it didn't match the currently "active" JRE, which was causing the error.

Download a matching version of the JDK to the JRE you currently have installed, (In OP's case 151) That should do the trick.

Tomcat starts but home page cannot open with url http://localhost:8080

If you have your tomcat started (in linux check with ps -ef | grep java) and you see it opened the port 8080 or the one you configured in server.xml (check with netstat --tcp -na | grep <port number>) but you still cannot access it in your browser check the following:

  1. It may start but with a delay of 3-5 minutes. Check the logs/catalina.out. You should see something like this when the server started completely.
    INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 38442 ms
    If you don't have this INFO line your server startup is not complete yet. The problem may occur due to the SecureRandom class responsible to provide random Session IDs and which can cause big delays during startup. Check more details and the solution here.
  2. Check your firewall (on linux iptables -L -n): You can try to reset your firewall completely iptables -F if you are not into an exposed environment. However, pay attention, that leaves you without protection therefore it can be dangerous.
  3. Check your selinux (if you are on linux).

These are some of the most forgotten and not obvious issues in having your Apache Tomcat up and running.

C# adding a character in a string

You can use this:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;

for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

Works perfectly with any string. As always, the size doesn't matter. ;)

The type arguments for method cannot be inferred from the usage

I received this error because I had made a mistake in the definition of my method. I had declared the method to accept a generic type (notice the "T" after the method name):

protected int InsertRecord<T>(CoasterModel model, IDbConnection con)

However, when I called the method, I did not use the type which, in my case, was the correct usage:

int count = InsertRecord(databaseToMigrateFrom, con);

I just removed the generic casting and it worked.

What is your most productive shortcut with Vim?

The Control+R mechanism is very useful :-) In either insert mode or command mode (i.e. on the : line when typing commands), continue with a numbered or named register:

  • a - z the named registers
  • " the unnamed register, containing the text of the last delete or yank
  • % the current file name
  • # the alternate file name
  • * the clipboard contents (X11: primary selection)
  • + the clipboard contents
  • / the last search pattern
  • : the last command-line
  • . the last inserted text
  • - the last small (less than a line) delete
  • =5*5 insert 25 into text (mini-calculator)

See :help i_CTRL-R and :help c_CTRL-R for more details, and snoop around nearby for more CTRL-R goodness.

Work with a time span in Javascript

/**
 * ??????????????,???????? 
 * English: Calculating the difference between the given time and the current time and then showing the results.
 */
function date2Text(date) {
    var milliseconds = new Date() - date;
    var timespan = new TimeSpan(milliseconds);
    if (milliseconds < 0) {
        return timespan.toString() + "??";
    }else{
        return timespan.toString() + "?";
    }
}

/**
 * ???????????
 * English: Using a function to calculate the time interval
 * @param milliseconds ???
 */
var TimeSpan = function (milliseconds) {
    milliseconds = Math.abs(milliseconds);
    var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
    milliseconds -= days * (1000 * 60 * 60 * 24);

    var hours = Math.floor(milliseconds / (1000 * 60 * 60));
    milliseconds -= hours * (1000 * 60 * 60);

    var mins = Math.floor(milliseconds / (1000 * 60));
    milliseconds -= mins * (1000 * 60);

    var seconds = Math.floor(milliseconds / (1000));
    milliseconds -= seconds * (1000);
    return {
        getDays: function () {
            return days;
        },
        getHours: function () {
            return hours;
        },
        getMinuts: function () {
            return mins;
        },
        getSeconds: function () {
            return seconds;
        },
        toString: function () {
            var str = "";
            if (days > 0 || str.length > 0) {
                str += days + "?";
            }
            if (hours > 0 || str.length > 0) {
                str += hours + "??";
            }
            if (mins > 0 || str.length > 0) {
                str += mins + "??";
            }
            if (days == 0 && (seconds > 0 || str.length > 0)) {
                str += seconds + "?";
            }
            return str;
        }
    }
}

How do I scroll to an element within an overflowed Div?

After playing with it for a very long time, this is what I came up with:

    jQuery.fn.scrollTo = function (elem) {
        var b = $(elem);
        this.scrollTop(b.position().top + b.height() - this.height());
    };

and I call it like this

$("#basketListGridHolder").scrollTo('tr[data-uid="' + basketID + '"]');

Running Java Program from Command Line Linux

What is the package name of your class? If there is no package name, then most likely the solution is:

java -cp FileManagement Main

Best way to do a split pane in HTML

I wrote simple code for it without any third-party library. This code is only for a horizontal splitter (vertical is the same).

_x000D_
_x000D_
function onload()
{
    dragElement( document.getElementById("separator"), "H" );
}

// This function is used for dragging and moving
function dragElement( element, direction, handler )
{
  // Two variables for tracking positions of the cursor
  const drag = { x : 0, y : 0 };
  const delta = { x : 0, y : 0 };
  /* If present, the handler is where you move the DIV from
     otherwise, move the DIV from anywhere inside the DIV */
  handler ? ( handler.onmousedown = dragMouseDown ): ( element.onmousedown = dragMouseDown );

  // A function that will be called whenever the down event of the mouse is raised
  function dragMouseDown( e )
  {
    drag.x = e.clientX;
    drag.y = e.clientY;
    document.onmousemove = onMouseMove;
    document.onmouseup = () => { document.onmousemove = document.onmouseup = null; }
  }

  // A function that will be called whenever the up event of the mouse is raised
  function onMouseMove( e )
  {
    const currentX = e.clientX;
    const currentY = e.clientY;

    delta.x = currentX - drag.x;
    delta.y = currentY - drag.y;

    const offsetLeft = element.offsetLeft;
    const offsetTop = element.offsetTop;


    const first = document.getElementById("first");
    const second = document.getElementById("second");
    let firstWidth = first.offsetWidth;
    let secondWidth = second.offsetWidth;
    if (direction === "H" ) // Horizontal
    {
        element.style.left = offsetLeft + delta.x + "px";
        firstWidth += delta.x;
        secondWidth -= delta.x;
    }
    drag.x = currentX;
    drag.y = currentY;
    first.style.width = firstWidth + "px";
    second.style.width = secondWidth + "px";
  }
}
_x000D_
.splitter {
    width: 500px;
    height: 100px;
    display: flex;
}

#separator {
    cursor: col-resize;
    background: url(https://raw.githubusercontent.com/RickStrahl/jquery-resizable/master/assets/vsizegrip.png) center center no-repeat #535353;
    width: 10px;
    height: 100px;
    min-width: 10px;
}

#first {
    background-color: green;
    width: 100px;
    height: 100px;
    min-width: 10px;
}

#second {
    background-color: red;
    width: 390px;
    height: 100px;
    min-width: 10px;
}
_x000D_
<html>

    <head>
        <link rel="stylesheet" href="T10-Splitter.css">
        <script src="T10-Splitter.js"></script>
    </head>

    <body onload="onload()">
        <div class="splitter">
            <div id="first"></div>
            <div id="separator"></div>
            <div id="second"></div>
        </div>
    </body>

</html>
_x000D_
_x000D_
_x000D_

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.

Copy multiple files with Ansible

You can use the with_fileglob loop for this:

- copy:
    src: "{{ item }}"
    dest: /etc/fooapp/
    owner: root
    mode: 600
  with_fileglob:
    - /playbooks/files/fooapp/*

Google access token expiration time

Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse

It says:

Other parameters included in the response include expires_in and token_type. These parameters describe the lifetime of the token in seconds...

How to tell if a file is git tracked (by shell exit code)?

using git log will give info about this. If the file is tracked in git the command shows some results(logs). Else it is empty.

For example if the file is git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
commit ad9180b772d5c64dcd79a6cbb9487bd2ef08cbfc
Author: User <[email protected]>
Date:   Mon Feb 20 07:45:04 2017 -0600

    fix eslint indentation errors
....
....

If the file is not git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
root@user-ubuntu:~/project-repo-directory#

Alert after page load

There are three ways.
The first is to put the script tag on the bottom of the page:

<body>
<!--Body content-->
<script type="text/javascript">
alert('<%: TempData["Resultat"]%>');
</script>
</body>

The second way is to create an onload event:

<head>
<script type="text/javascript">
window.onload = function(){//window.addEventListener('load',function(){...}); (for Netscape) and window.attachEvent('onload',function(){...}); (for IE and Opera) also work
    alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

It will execute a function when the window loads.
Finally, the third way is to create a readystatechange event and check the current document.readystate:

<head>
<script type="text/javascript">
document.onreadystatechange = function(){//window.addEventListener('readystatechange',function(){...}); (for Netscape) and window.attachEvent('onreadystatechange',function(){...}); (for IE and Opera) also work
    if(document.readyState=='loaded' || document.readyState=='complete')
        alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

Installing R with Homebrew

brew install cask
brew cask install xquartz
brew tap homebrew/science
brew install r

This way, everything is packager managed, so there's no need to manually download and install anything.

Emulator: ERROR: x86 emulation currently requires hardware acceleration

Right click on your my computer icon and the CPU will be listed on the properties page. Or open device manager and look at the CPU. It must be an Intel processor that supports VT and NX bit (XD) - you can check your CPU # at http://ark.intel.com
Also make sure hyperV off bcdedit /set hypervisorlaunchtype off
XD bit is on bcdedit /set nx AlwaysOn
Use the installer from https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager
If you're using Avast, disable "Enable hardware-assisted virtualization" under: Settings > Troubleshooting. Restart the PC and try to run the HAXM installation again

Why is processing a sorted array faster than processing an unsorted array?

No doubt some of us would be interested in ways of identifying code that is problematic for the CPU's branch-predictor. The Valgrind tool cachegrind has a branch-predictor simulator, enabled by using the --branch-sim=yes flag. Running it over the examples in this question, with the number of outer loops reduced to 10000 and compiled with g++, gives these results:

Sorted:

==32551== Branches:        656,645,130  (  656,609,208 cond +    35,922 ind)
==32551== Mispredicts:         169,556  (      169,095 cond +       461 ind)
==32551== Mispred rate:            0.0% (          0.0%     +       1.2%   )

Unsorted:

==32555== Branches:        655,996,082  (  655,960,160 cond +  35,922 ind)
==32555== Mispredicts:     164,073,152  (  164,072,692 cond +     460 ind)
==32555== Mispred rate:           25.0% (         25.0%     +     1.2%   )

Drilling down into the line-by-line output produced by cg_annotate we see for the loop in question:

Sorted:

          Bc    Bcm Bi Bim
      10,001      4  0   0      for (unsigned i = 0; i < 10000; ++i)
           .      .  .   .      {
           .      .  .   .          // primary loop
 327,690,000 10,016  0   0          for (unsigned c = 0; c < arraySize; ++c)
           .      .  .   .          {
 327,680,000 10,006  0   0              if (data[c] >= 128)
           0      0  0   0                  sum += data[c];
           .      .  .   .          }
           .      .  .   .      }

Unsorted:

          Bc         Bcm Bi Bim
      10,001           4  0   0      for (unsigned i = 0; i < 10000; ++i)
           .           .  .   .      {
           .           .  .   .          // primary loop
 327,690,000      10,038  0   0          for (unsigned c = 0; c < arraySize; ++c)
           .           .  .   .          {
 327,680,000 164,050,007  0   0              if (data[c] >= 128)
           0           0  0   0                  sum += data[c];
           .           .  .   .          }
           .           .  .   .      }

This lets you easily identify the problematic line - in the unsorted version the if (data[c] >= 128) line is causing 164,050,007 mispredicted conditional branches (Bcm) under cachegrind's branch-predictor model, whereas it's only causing 10,006 in the sorted version.


Alternatively, on Linux you can use the performance counters subsystem to accomplish the same task, but with native performance using CPU counters.

perf stat ./sumtest_sorted

Sorted:

 Performance counter stats for './sumtest_sorted':

  11808.095776 task-clock                #    0.998 CPUs utilized          
         1,062 context-switches          #    0.090 K/sec                  
            14 CPU-migrations            #    0.001 K/sec                  
           337 page-faults               #    0.029 K/sec                  
26,487,882,764 cycles                    #    2.243 GHz                    
41,025,654,322 instructions              #    1.55  insns per cycle        
 6,558,871,379 branches                  #  555.455 M/sec                  
       567,204 branch-misses             #    0.01% of all branches        

  11.827228330 seconds time elapsed

Unsorted:

 Performance counter stats for './sumtest_unsorted':

  28877.954344 task-clock                #    0.998 CPUs utilized          
         2,584 context-switches          #    0.089 K/sec                  
            18 CPU-migrations            #    0.001 K/sec                  
           335 page-faults               #    0.012 K/sec                  
65,076,127,595 cycles                    #    2.253 GHz                    
41,032,528,741 instructions              #    0.63  insns per cycle        
 6,560,579,013 branches                  #  227.183 M/sec                  
 1,646,394,749 branch-misses             #   25.10% of all branches        

  28.935500947 seconds time elapsed

It can also do source code annotation with dissassembly.

perf record -e branch-misses ./sumtest_unsorted
perf annotate -d sumtest_unsorted
 Percent |      Source code & Disassembly of sumtest_unsorted
------------------------------------------------
...
         :                      sum += data[c];
    0.00 :        400a1a:       mov    -0x14(%rbp),%eax
   39.97 :        400a1d:       mov    %eax,%eax
    5.31 :        400a1f:       mov    -0x20040(%rbp,%rax,4),%eax
    4.60 :        400a26:       cltq   
    0.00 :        400a28:       add    %rax,-0x30(%rbp)
...

See the performance tutorial for more details.

How good is Java's UUID.randomUUID?

The original generation scheme for UUIDs was to concatenate the UUID version with the MAC address of the computer that is generating the UUID, and with the number of 100-nanosecond intervals since the adoption of the Gregorian calendar in the West. By representing a single point in space (the computer) and time (the number of intervals), the chance of a collision in values is effectively nil.

How can I get the active screen dimensions?

WinForms

For multi-monitor setups you will also need account for the X and Y position:

Rectangle activeScreenDimensions = Screen.FromControl(this).Bounds;
this.Size = new Size(activeScreenDimensions.Width + activeScreenDimensions.X, activeScreenDimensions.Height + activeScreenDimensions.Y);

How to restart a rails server on Heroku?

Go into your application directory on terminal and run following command:

heroku restart

Get selected row item in DataGrid WPF

If you're using the MVVM pattern you can bind a SelectedRecord property of your VM with SelectedItem of the DataGrid, this way you always have the SelectedValue in you VM. Otherwise you should use the SelectedIndex property of the DataGrid.

Pandas get the most frequent values of a column

To get the top five most common names:

dataframe['name'].value_counts().head()

Process to convert simple Python script into Windows executable

Using py2exe, include this in your setup.py:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1}},
    windows = [{'script': "YourScript.py"}],
    zipfile = None,
)

then you can run it through command prompt / Idle, both works for me. Hope it helps

Hide Button After Click (With Existing Form on Page)

CSS code:

.hide{
display:none;
}

.show{
display:block;
}

Html code:

<button onclick="block_none()">Check Availability</button>

Javascript Code:

function block_none(){
 document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}

JQUERY ajax passing value from MVC View to Controller

Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".

$.ajax({
      url:/ControllerName/ActionName,
      data: "id=" + Id + "&param2=" + param2,
      type: "GET",
      success: function(data){
            // code here
      },
      error: function(passParams){
           // code here
      }
});

Another alternative will be to use the data-ajax on a link.

<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>

Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.

<div id="_content"></div>

Not really a direct answer to ur question but its some info u should be aware of ;).

Adding git branch on the Bash command prompt

Follow the below steps to show the name of the branch of your GIT repo in ubuntu terminal:

step1: open terminal and edit .bashrc using the following command.

vi .bashrc

step2: add the following line at the end of the .bashrc file :

parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' }

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

step3: source .bashrc in the root (home) directory by doing:

/rootfolder:~$ source .bashrc

Step4: Restart and open the terminal and check the cmd. Navigate to your GIt repo directory path and you are done. :)

How to export a table dataframe in PySpark to csv?

If you cannot use spark-csv, you can do the following:

df.rdd.map(lambda x: ",".join(map(str, x))).coalesce(1).saveAsTextFile("file.csv")

If you need to handle strings with linebreaks or comma that will not work. Use this:

import csv
import cStringIO

def row2csv(row):
    buffer = cStringIO.StringIO()
    writer = csv.writer(buffer)
    writer.writerow([str(s).encode("utf-8") for s in row])
    buffer.seek(0)
    return buffer.read().strip()

df.rdd.map(row2csv).coalesce(1).saveAsTextFile("file.csv")

Cannot implicitly convert type from Task<>

Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

How do I style a <select> dropdown with only CSS?

The largest inconsistency I've noticed when styling select dropdowns is Safari and Google Chrome rendering (Firefox is fully customizable through CSS). After some searching through obscure depths of the Internet I came across the following, which nearly completely resolves my qualms with WebKit:

Safari and Google Chrome fix:

select {
  -webkit-appearance: none;
}

This does, however, remove the dropdown arrow. You can add a dropdown arrow using a nearby div with a background, negative margin or absolutely positioned over the select dropdown.

*More information and other variables are available in CSS property: -webkit-appearance.

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

Difference between del, remove, and pop on lists

While pop and delete both take indices to remove an element as stated in above comments. A key difference is the time complexity for them. The time complexity for pop() with no index is O(1) but is not the same case for deletion of last element.

If your use case is always to delete the last element, it's always preferable to use pop() over delete(). For more explanation on time complexities, you can refer to https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Java Byte Array to String to Byte Array

What I did:

return to clients:

byte[] result = ****encrypted data****;

String str = Base64.encodeBase64String(result);

return str;

receive from clients:

 byte[] bytes = Base64.decodeBase64(str);

your data will be transferred in this format:

OpfyN9paAouZ2Pw+gDgGsDWzjIphmaZbUyFx5oRIN1kkQ1tDbgoi84dRfklf1OZVdpAV7TonlTDHBOr93EXIEBoY1vuQnKXaG+CJyIfrCWbEENJ0gOVBr9W3OlFcGsZW5Cf9uirSmx/JLLxTrejZzbgq3lpToYc3vkyPy5Y/oFWYljy/3OcC/S458uZFOc/FfDqWGtT9pTUdxLDOwQ6EMe0oJBlMXm8J2tGnRja4F/aVHfQddha2nUMi6zlvAm8i9KnsWmQG//ok25EHDbrFBP2Ia/6Bx/SGS4skk/0couKwcPVXtTq8qpNh/aYK1mclg7TBKHfF+DHppwd30VULpA== 

How to focus on a form input text field on page load using jQuery?

place after input

<script type="text/javascript">document.formname.inputname.focus();</script>

Is it possible to specify a different ssh port when using rsync?

Another option, in the host you run rsync from, set the port in the ssh config file, ie:

cat ~/.ssh/config
Host host
    Port 2222

Then rsync over ssh will talk to port 2222:

rsync -rvz --progress --remove-sent-files ./dir user@host:/path

Why does sudo change the PATH?

I think it is in fact desirable to have sudo reset the PATH: otherwise an attacker having compromised your user account could put backdoored versions of all kinds of tools on your users' PATH, and they would be executed when using sudo.

(of course having sudo reset the PATH is not a complete solution to these kinds of problems, but it helps)

This is indeed what happens when you use

Defaults env_reset

in /etc/sudoers without using exempt_group or env_keep.

This is also convenient because you can add directories that are only useful for root (such as /sbin and /usr/sbin) to the sudo path without adding them to your users' paths. To specify the path to be used by sudo:

Defaults secure_path="/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin"

Rename multiple files in a folder, add a prefix (Windows)

The problem with the two Powershell answers here is that the prefix can end up being duplicated since the script will potentially run over the file both before and after it has been renamed, depending on the directory being resorted as the renaming process runs. To get around this, simply use the -Exclude option:

Get-ChildItem -Exclude "house chores-*" | rename-item -NewName { "house chores-" + $_.Name }

This will prevent the process from renaming any one file more than once.

Checking if a string is empty or null in Java

You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

"Are you missing an assembly reference?" compile error - Visual Studio

In my case, I had to change the Copy Local setting to true (right-click assembly in solution explorer, select properties, locate and change value of Copy Local property). Once this setting was changed, publication of my WCF service copied the file to the server and the error went away.

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

How is the default max Java heap size determined?

A number of parameters affect generation size. The following diagram illustrates the difference between committed space and virtual space in the heap. At initialization of the virtual machine, the entire space for the heap is reserved. The size of the space reserved can be specified with the -Xmx option. If the value of the -Xms parameter is smaller than the value of the -Xmx parameter, not all of the space that is reserved is immediately committed to the virtual machine. The uncommitted space is labeled "virtual" in this figure. The different parts of the heap (permanent generation, tenured generation and young generation) can grow to the limit of the virtual space as needed.

enter image description here

By default, the virtual machine grows or shrinks the heap at each collection to try to keep the proportion of free space to live objects at each collection within a specific range. This target range is set as a percentage by the parameters -XX:MinHeapFreeRatio=<minimum> and -XX:MaxHeapFreeRatio=<maximum>, and the total size is bounded below by -Xms<min> and above by -Xmx<max>.

Parameter Default Value

MinHeapFreeRatio 40

MaxHeapFreeRatio 70

-Xms 3670k

-Xmx 64m

Default values of heap size parameters on 64-bit systems have been scaled up by approximately 30%. This increase is meant to compensate for the larger size of objects on a 64-bit system.

With these parameters, if the percent of free space in a generation falls below 40%, the generation will be expanded to maintain 40% free space, up to the maximum allowed size of the generation. Similarly, if the free space exceeds 70%, the generation will be contracted so that only 70% of the space is free, subject to the minimum size of the generation.

Large server applications often experience two problems with these defaults. One is slow startup, because the initial heap is small and must be resized over many major collections. A more pressing problem is that the default maximum heap size is unreasonably small for most server applications. The rules of thumb for server applications are:

  • Unless you have problems with pauses, try granting as much memory as possible to the virtual machine. The default size (64MB) is often too small.
  • Setting -Xms and -Xmx to the same value increases predictability by removing the most important sizing decision from the virtual machine. However, the virtual machine is then unable to compensate if you make a poor choice.
  • In general, increase the memory as you increase the number of processors, since allocation can be parallelized.

    There is the full article

SDK Location not found Android Studio + Gradle

In my specific case I tried to create a React Native app using the react-native init installation process, when I encountered the discussed problem.

FAILURE: Build failed with an exception.

* What went wrong:

A problem occurred configuring project ':app'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\***\android\local.properties'.

I add this, because when developing an android app using react native, the 'root directory' to which so many answers refer, is actually the root of the android folder (and not the project's root folder, where App.js resides). This is also made clear by the directory marked in the error message.

To solve it, just add a local.properties file to the android folder, and type:

sdk.dir=C:/Users/{user name}/AppData/Local/Android/Sdk

Be sure to add the local disk's reference ('C:/'), because it did not work otherwise in my case.

(SC) DeleteService FAILED 1072

I had the same error due to a typo in the service name, i was trying to delete the service display name instead of the service name. Once I used the right service name it worked fine

What is the App_Data folder used for in Visual Studio?

It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.

how to rotate text left 90 degree and cell size is adjusted according to text in html

You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>.

Also make sure you change your id #rotate to a class since you have multiple.

A 4x3 table with the headers in the first column rotated by 90 degrees

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
  border-collapse: collapse;_x000D_
  border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
  visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
  /* FF3.5+ */_x000D_
  -moz-transform: rotate(-90.0deg);_x000D_
  /* Opera 10.5 */_x000D_
  -o-transform: rotate(-90.0deg);_x000D_
  /* Saf3.1+, Chrome */_x000D_
  -webkit-transform: rotate(-90.0deg);_x000D_
  /* IE6,IE7 */_x000D_
  filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
  /* IE8 */_x000D_
  -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
  /* Standard */_x000D_
  transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>10kg</div>_x000D_
    </td>_x000D_
    <td>B</td>_x000D_
    <td>C</td>_x000D_
    <td>D</td>_x000D_
    <td>E</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>20kg</div>_x000D_
    </td>_x000D_
    <td>G</td>_x000D_
    <td>H</td>_x000D_
    <td>I</td>_x000D_
    <td>J</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>30kg</div>_x000D_
    </td>_x000D_
    <td>L</td>_x000D_
    <td>M</td>_x000D_
    <td>N</td>_x000D_
    <td>O</td>_x000D_
  </tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

JavaScript

The equivalent to the above in pure JavaScript is as follows:

jsFiddle

window.addEventListener('load', function () {
    var rotates = document.getElementsByClassName('rotate');
    for (var i = 0; i < rotates.length; i++) {
        rotates[i].style.height = rotates[i].offsetWidth + 'px';
    }
});

How to close Browser Tab After Submitting a Form?

This worked brilliantly for me, :

 $query = "INSERT INTO `table` (...or put your preferred sql stuff)" 
 $result = mysqli_query($connect, $query); 
 if($result){
  // If everything runs fine with your sql query you will see a message and then the window
  //closes
        echo '<script language="javascript">';
        echo 'alert("Successful!")';
        echo '</script>';
        echo "<script>window.close();</script>";
        }
 else {
        echo '<script language="javascript">';
        echo 'alert("Problem with database or something!")';
        echo '</script>';           
        }

HTML5 record audio to file

You can use Recordmp3js from GitHub to achieve your requirements. You can record from user's microphone and then get the file as an mp3. Finally upload it to your server.

I used this in my demo. There is a already a sample available with the source code by the author in this location : https://github.com/Audior/Recordmp3js

The demo is here: http://audior.ec/recordmp3js/

But currently works only on Chrome and Firefox.

Seems to work fine and pretty simple. Hope this helps.

How to enable Ad Hoc Distributed Queries

You may check the following command

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added        
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link

When creating a service with sc.exe how to pass in context parameters?

it is not working in the Powershell and should use CMD in my case

Sending mail from Python using SMTP

Here's a working example for Python 3.x

#!/usr/bin/env python3

from email.message import EmailMessage
from getpass import getpass
from smtplib import SMTP_SSL
from sys import exit

smtp_server = 'smtp.gmail.com'
username = '[email protected]'
password = getpass('Enter Gmail password: ')

sender = '[email protected]'
destination = '[email protected]'
subject = 'Sent from Python 3.x'
content = 'Hello! This was sent to you via Python 3.x!'

# Create a text/plain message
msg = EmailMessage()
msg.set_content(content)

msg['Subject'] = subject
msg['From'] = sender
msg['To'] = destination

try:
    s = SMTP_SSL(smtp_server)
    s.login(username, password)
    try:
        s.send_message(msg)
    finally:
        s.quit()

except Exception as E:
    exit('Mail failed: {}'.format(str(E)))

How can I get the error message for the mail() function?

sending mail in php is not a one-step process. mail() returns true/false, but even if it returns true, it doesn't mean the message is going to be sent. all mail() does is add the message to the queue(using sendmail or whatever you set in php.ini)

there is no reliable way to check if the message has been sent in php. you will have to look through the mail server logs.

Best way to test exceptions with Assert to ensure they will be thrown

Unfortunately MSTest STILL only really has the ExpectedException attribute (just shows how much MS cares about MSTest) which IMO is pretty awful because it breaks the Arrange/Act/Assert pattern and it doesnt allow you to specify exactly which line of code you expect the exception to occur on.

When I'm using (/forced by a client) to use MSTest I always use this helper class:

public static class AssertException
{
    public static void Throws<TException>(Action action) where TException : Exception
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
            return;
        }
        Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
    }

    public static void Throws<TException>(Action action, string expectedMessage) where TException : Exception
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
            Assert.AreEqual(expectedMessage, ex.Message, "Expected exception with a message of '" + expectedMessage + "' but exception with message of '" + ex.Message + "' was thrown instead.");
            return;
        }
        Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
    }
}

Example of usage:

AssertException.Throws<ArgumentNullException>(() => classUnderTest.GetCustomer(null));

How unique is UUID?

UUID schemes generally use not only a pseudo-random element, but also the current system time, and some sort of often-unique hardware ID if available, such as a network MAC address.

The whole point of using UUID is that you trust it to do a better job of providing a unique ID than you yourself would be able to do. This is the same rationale behind using a 3rd party cryptography library rather than rolling your own. Doing it yourself may be more fun, but it's typically less responsible to do so.

Why do we assign a parent reference to the child object in Java?

When you compile your program the reference variable of the base class gets memory and compiler checks all the methods in that class. So it checks all the base class methods but not the child class methods. Now at runtime when the object is created, only checked methods can run. In case a method is overridden in the child class that function runs. Child class other functions aren't run because the compiler hasn't recognized them at the compile time.

"Cannot GET /" with Connect on Node.js

You typically want to render templates like this:

app.get('/', function(req, res){
  res.render('index.ejs');
});

However you can also deliver static content - to do so use:

app.use(express.static(__dirname + '/public'));

Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

Take a look through the express API and Connect Static middleware docs for more info.

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

How to get all selected values of a multiple select box?

You can use [].reduce for a more compact implementation of RobG's approach:

var getSelectedValues =  function(selectElement) {
  return [].reduce.call(selectElement.options, function(result, option) {
    if (option.selected) result.push(option.value);
    return result;
  }, []);
};

Counter increment in Bash loop not working

There were two conditions that caused the expression ((var++)) to fail for me:

  1. If I set bash to strict mode (set -euo pipefail) and if I start my increment at zero (0).

  2. Starting at one (1) is fine but zero causes the increment to return "1" when evaluating "++" which is a non-zero return code failure in strict mode.

I can either use ((var+=1)) or var=$((var+1)) to escape this behavior

Display string as html in asp.net mvc view

You are close you want to use @Html.Raw(str)

@Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces.

Why is a div with "display: table-cell;" not affected by margin?

Table cells don't respect margin, but you could use transparent borders instead:

div {
  display: table-cell;
  border: 5px solid transparent;
}

Note: you can't use percentages here... :(

Where am I? - Get country

First, get the LocationManager. Then, call LocationManager.getLastKnownPosition. Then create a GeoCoder and call GeoCoder.getFromLocation. Do this is in a separate thread!! This will give you a list of Address objects. Call Address.getCountryName and you got it.

Keep in mind that the last known position can be a bit stale, so if the user just crossed the border, you may not know about it for a while.

How to remove focus without setting focus to another control?

android:focusableInTouchMode="true"
android:focusable="true"
android:clickable="true"

Add them to your ViewGroup that includes your EditTextView. It works properly to my Constraint Layout. Hope this help

Can I change the name of `nohup.out`?

Above methods will remove your output file data whenever you run above nohup command.

To Append output in user defined file you can use >> in nohup command.

nohup your_command >> filename.out &

This command will append all output in your file without removing old data.

How to clear Flutter's Build cache?

Build cache is generated on application run time when a temporary file automatically generated in dart-tools folder, android folder and iOS folder. Clear command will delete the build tools and dart directories in flutter project so when we re-compile the project it will start from beginning. This command is mostly used when our project is showing debug error or running related error. In this answer we would Clear Build Cache in Flutter Android iOS App and Rebuild Project structure again.

  1. Open your flutter project folder in Command Prompt or Terminal. and type flutter clean command and press enter.

  2. After executing flutter clean command we would see that it will delete the dart-tools folder, android folder and iOS folder in our application with debug file. This might take some time depending upon your system speed to clean the project.

For more info, see https://flutter-examples.com/clear-build-cache-in-flutter-app/

How can I use a JavaScript variable as a PHP variable?

You can take all values like this:

$abc = "<script>document.getElementByID('yourid').value</script>";

Anaconda vs. miniconda

Brief

conda is both a command line tool, and a python package.

Miniconda installer = Python + conda

Anaconda installer = Python + conda + meta package anaconda

meta Python pkg anaconda = about 160 Python pkgs for daily use in data science

Anaconda installer = Miniconda installer + conda install anaconda

Detail

  1. conda is a python manager and an environment manager, which makes it possible to

    • install package with conda install flake8
    • create an environment with any version of Python with conda create -n myenv python=3.6
  2. Miniconda installer = Python + conda

    conda, the package manager and environment manager, is a Python package. So Python is installed. Cause conda distribute Python interpreter with its own libraries/dependencies but not the existing ones on your operating system, other minimal dependencies like openssl, ncurses, sqlite, etc are installed as well.

    Basically, Miniconda is just conda and its minimal dependencies. And the environment where conda is installed is the "base" environment, which is previously called "root" environment.

  3. Anaconda installer = Python + conda + meta package anaconda

  4. meta Python package anaconda = about 160 Python pkgs for daily use in data science

    Meta packages, are packages that do NOT contain actual softwares and simply depend on other packages to be installed.

    Download an anaconda meta package from Anaconda Cloud and extract the content from it. The actual 160+ packages to be installed are listed in info/recipe/meta.yaml.

    package:
        name: anaconda
        version: '2019.07'
    build:
        ignore_run_exports:
            - '*'
        number: '0'
        pin_depends: strict
        string: py36_0
    requirements:
        build:
            - python 3.6.8 haf84260_0
        is_meta_pkg:
            - true
        run:
            - alabaster 0.7.12 py36_0
            - anaconda-client 1.7.2 py36_0
            - anaconda-project 0.8.3 py_0
            # ...
            - beautifulsoup4 4.7.1 py36_1
            # ...
            - curl 7.65.2 ha441bb4_0
            # ...
            - hdf5 1.10.4 hfa1e0ec_0
            # ...
            - ipykernel 5.1.1 py36h39e3cac_0
            - ipython 7.6.1 py36h39e3cac_0
            - ipython_genutils 0.2.0 py36h241746c_0
            - ipywidgets 7.5.0 py_0
            # ...
            - jupyter 1.0.0 py36_7
            - jupyter_client 5.3.1 py_0
            - jupyter_console 6.0.0 py36_0
            - jupyter_core 4.5.0 py_0
            - jupyterlab 1.0.2 py36hf63ae98_0
            - jupyterlab_server 1.0.0 py_0
            # ...
            - matplotlib 3.1.0 py36h54f8f79_0
            # ...
            - mkl 2019.4 233
            - mkl-service 2.0.2 py36h1de35cc_0
            - mkl_fft 1.0.12 py36h5e564d8_0
            - mkl_random 1.0.2 py36h27c97d8_0
            # ...
            - nltk 3.4.4 py36_0
            # ...
            - numpy 1.16.4 py36hacdab7b_0
            - numpy-base 1.16.4 py36h6575580_0
            - numpydoc 0.9.1 py_0
            # ...
            - pandas 0.24.2 py36h0a44026_0
            - pandoc 2.2.3.2 0
            # ...
            - pillow 6.1.0 py36hb68e598_0
            # ...
            - pyqt 5.9.2 py36h655552a_2
            # ...
            - qt 5.9.7 h468cd18_1
            - qtawesome 0.5.7 py36_1
            - qtconsole 4.5.1 py_0
            - qtpy 1.8.0 py_0
            # ...
            - requests 2.22.0 py36_0
            # ...
            - sphinx 2.1.2 py_0
            - sphinxcontrib 1.0 py36_1
            - sphinxcontrib-applehelp 1.0.1 py_0
            - sphinxcontrib-devhelp 1.0.1 py_0
            - sphinxcontrib-htmlhelp 1.0.2 py_0
            - sphinxcontrib-jsmath 1.0.1 py_0
            - sphinxcontrib-qthelp 1.0.2 py_0
            - sphinxcontrib-serializinghtml 1.1.3 py_0
            - sphinxcontrib-websupport 1.1.2 py_0
            - spyder 3.3.6 py36_0
            - spyder-kernels 0.5.1 py36_0
            # ...
    

    The pre-installed packages from meta pkg anaconda are mainly for web scraping and data science. Like requests, beautifulsoup, numpy, nltk, etc.

    If you have a Miniconda installed, conda install anaconda will make it same as an Anaconda installation, except that the installation folder names are different.

  5. Miniconda2 v.s. Miniconda. Anaconda2 v.s. Anaconda.

    2 means the bundled Python interpreter for conda in the "base" environment is Python 2, but not Python 3.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Django - "no module named django.core.management"

File and Directory ownership conflict will cause issues here. Make sure the ownership of the directories and files under the project are to the current user. (You can change them using the chown command with the -R option.) Try rerunning the command: this solved the problem for me when running through the "First Django App" sample:

python manage.py startapp polls

Convert JS date time to MySQL datetime

Using toJSON() date function as below:

_x000D_
_x000D_
var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
console.log(sqlDatetime);
_x000D_
_x000D_
_x000D_

how to access iFrame parent page using jquery?

in parent window put :

<script>
function ifDoneChildFrame(val)
{
   $('#parentPrice').html(val);
}
</script>

and in iframe src file put :

<script>window.parent.ifDoneChildFrame('Your value here');</script>

How to call another components function in angular2

Using Dataservice we can call the function from another component

Component1: The component which we are calling the function

constructor( public bookmarkRoot: dataService ) { } 

onClick(){
     this.bookmarkRoot.callToggle.next( true );
}

dataservice.ts

import { Injectable } from '@angular/core';
@Injectable()
export class dataService {
     callToggle = new Subject();
}

Component2:The component which contains the function

constructor( public bookmarkRoot: dataService ) { 
  this.bookmarkRoot.callToggle.subscribe(( data ) => {
            this.closeDrawer();
        } )
} 

 closeDrawer() {
        console.log("this is called")
    }

Ignore outliers in ggplot2 boxplot

The "coef" option of the geom_boxplot function allows to change the outlier cutoff in terms of interquartile ranges. This option is documented for the function stat_boxplot. To deactivate outliers (in other words they are treated as regular data), one can instead of using the default value of 1.5 specify a very high cutoff value:

library(ggplot2)
# generate data with outliers:
df = data.frame(x=1, y = c(-10, rnorm(100), 10)) 
# generate plot with increased cutoff for outliers:
ggplot(df, aes(x, y)) + geom_boxplot(coef=1e30)

click() event is calling twice in jquery

It means your code included the jquery script twice. But try this:

$("#btn").unbind("click").click(function(){

//your code

});