Programs & Examples On #Java1.4

Java 2 SE version 1.4 was released in February 2002, and has reached its End of Service Life on October 30th 2008.

How/when to use ng-click to call a route?

Remember that if you use ng-click for routing you will not be able to right-click the element and choose 'open in new tab' or ctrl clicking the link. I try to use ng-href when in comes to navigation. ng-click is better to use on buttons for operations or visual effects like collapse. But About I would not recommend. If you change the route you might need to change in a lot of placed in the application. Have a method returning the link. ex: About. This method you place in a utility

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

How to Sort Multi-dimensional Array by Value?

I use this function :

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
}


array_sort_by_column($array, 'order');

Closing database connections in Java

Yes, you need to close Connection. Otherwise, the database client will typically keep the socket connection and other resources open.

How can I find all of the distinct file extensions in a folder hierarchy?

I tried a bunch of the answers here, even the "best" answer. They all came up short of what I specifically was after. So besides the past 12 hours of sitting in regex code for multiple programs and reading and testing these answers this is what I came up with which works EXACTLY like I want.

 find . -type f -name "*.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{2,16}" | awk '{print tolower($0)}' | sort -u
  • Finds all files which may have an extension.
  • Greps only the extension
  • Greps for file extensions between 2 and 16 characters (just adjust the numbers if they don't fit your need). This helps avoid cache files and system files (system file bit is to search jail).
  • Awk to print the extensions in lower case.
  • Sort and bring in only unique values. Originally I had attempted to try the awk answer but it would double print items that varied in case sensitivity.

If you need a count of the file extensions then use the below code

find . -type f -name "*.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{2,16}" | awk '{print tolower($0)}' | sort | uniq -c | sort -rn

While these methods will take some time to complete and probably aren't the best ways to go about the problem, they work.

Update: Per @alpha_989 long file extensions will cause an issue. That's due to the original regex "[[:alpha:]]{3,6}". I have updated the answer to include the regex "[[:alpha:]]{2,16}". However anyone using this code should be aware that those numbers are the min and max of how long the extension is allowed for the final output. Anything outside that range will be split into multiple lines in the output.

Note: Original post did read "- Greps for file extensions between 3 and 6 characters (just adjust the numbers if they don't fit your need). This helps avoid cache files and system files (system file bit is to search jail)."

Idea: Could be used to find file extensions over a specific length via:

 find . -type f -name "*.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{4,}" | awk '{print tolower($0)}' | sort -u

Where 4 is the file extensions length to include and then find also any extensions beyond that length.

How to get element by class name?

Another option is to use querySelector('.foo') or querySelectorAll('.foo') which have broader browser support than getElementsByClassName.

http://caniuse.com/#feat=queryselector

http://caniuse.com/#feat=getelementsbyclassname

OnItemCLickListener not working in listview

I just found a solution from here, but by deep clicking.

If any row item of list contains focusable or clickable view then OnItemClickListener won't work.

The row item must have a param like android:descendantFocusability = "blocksDescendants".

Here you can see an example of how your list item should look like. Your list item xml should be... row_item.xml (your_xml_file.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:descendantFocusability="blocksDescendants"
    android:gravity="center_vertical" >

    // your other widgets here

</LinearLayout>

MongoDB vs. Cassandra

I'm probably going to be an odd man out, but I think you need to stay with MySQL. You haven't described a real problem you need to solve, and MySQL/InnoDB is an excellent storage back-end even for blob/json data.

There is a common trick among Web engineers to try to use more NoSQL as soon as realization comes that not all features of an RDBMS are used. This alone is not a good reason, since most often NoSQL databases have rather poor data engines (what MySQL calls a storage engine).

Now, if you're not of that kind, then please specify what is missing in MySQL and you're looking for in a different database (like, auto-sharding, automatic failover, multi-master replication, a weaker data consistency guarantee in cluster paying off in higher write throughput, etc).

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

You should probably stop using launch images in iOS 8 and use a storyboard or nib/xib.

  • In Xcode 6, open the File menu and choose New ? File... ? iOS ? User Interface ? Launch Screen.

  • Then open the settings for your project by clicking on it.

  • In the General tab, in the section called App Icons and Launch Images, set the Launch Screen File to the files you just created (this will set UILaunchStoryboardName in info.plist).

Note that for the time being the simulator will only show a black screen, so you need to test on a real device.

Adding a Launch Screen xib file to your project:

Adding a new Launch Screen xib file

Configuring your project to use the Launch Screen xib file instead of the Asset Catalog:

Configure project to use Launch Screen xob

Python base64 data decode

Note Slipstream's response, that base64.b64encode and base64.b64decode need bytes-like object, not string.

>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.6/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

OR, AND Operator

If what interests you is bitwise operations look here for a brief tutorial : http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)

If you want logical operation answers are already given.

Scripting Language vs Programming Language

I think that what you are stating as the "difference" is actually a consequence of the real difference.

The actual difference is the target of the code written. Who is going to run this code.

A scripting language is used to write code that is going to target a software system. It's going to automate operations on that software system. The script is going to be a sequence of instructions to the target software system.

A programming language targets the computing system, which can be a real or virtual machine. The instructions are executed by the machine.

Of course, a real machine understands only binary code so you need to compile the code of a programming language. But this is a consequence of targeting a machine instead of a program.

In the other hand, the target software system of an script may compile the code or interpret it. Is up to the software system.

If we say that the real difference is whether it is compiled or not, then we have a problem because when Javascript runs in V8 is compiled and when it runs in Rhino is not.

It gets more confusing since scripting languages have evolved to become very powerful. So they are not limited to create small scripts to automate operations on another software system, you can create any rich applications with them.

Python code targets an interpreter so we can say that it "scripts" operations on that interpreter. But when you write Python code you don't see it as scripting an interpreter, you see it as creating an application. The interpreter is just there to code at a higher level among other things. So for me Python is more a programming language than an scripting language.

Why has it failed to load main-class manifest attribute from a JAR file?

I discovered that I was also having this error in NetBeans. I hope the following is helpful.

  1. Make sure that when you go to Project Configuration you set the main class you intend for running.
  2. Do a Build or Clean Build
  3. Place the jar file where you wish and try: java -jar "YourProject.jar" again at the command line.

This was the problem I was getting because I had other "test" programs I was using in NetBeans and I had to make sure the Main Class under the Run portion of the Project configuration was set correctly.

many blessings, John P

How to Specify "Vary: Accept-Encoding" header in .htaccess

if anyone needs this for NGINX configuration file here is the snippet:

location ~* \.(js|css|xml|gz)$ {
    add_header Vary "Accept-Encoding";
    (... other headers or rules ...)
}

Difference between Convert.ToString() and .ToString()

In C# if you declare a string variable and if you don’t assign any value to that variable, then by default that variable takes a null value. In such a case, if you use the ToString() method then your program will throw the null reference exception. On the other hand, if you use the Convert.ToString() method then your program will not throw an exception.

Starting the week on Monday with isoWeekday()

For those who want isoWeek to be the default you can modify moment's behaviour as such:

const moment = require('moment');
const proto = Object.getPrototypeOf(moment());

const {startOf, endOf} = proto;
proto.startOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return startOf.call(this, period);
};
proto.endOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return endOf.call(this, period);
};

Now you can simply use someDate.startOf('week') without worrying you'll get sunday or having to think about whether to use isoweek or isoWeek etc.

Plus you can store this in a variable like const period = 'week' and use it safely in subtract() or add() operations, e.g. moment().subtract(1, period).startOf(period);. This won't work with period being isoWeek.

"The page has expired due to inactivity" - Laravel 5.5

I have figured out two solution to avoid these error 1)by adding protected $except = ['/yourroute'] possible disable csrf token inspection from defined root. 2)just comment \App\Http\Middleware\VerifyCsrfToken::class line in protected middleware group in kernel

HTML5 iFrame Seamless Attribute

Use the frameborder attribute on your iframe and set it to frameborder="0" . That produces the seamless look. Now you maybe saying I want the nested iframe to control rather I have scroll bars. Then you need to whip up a JavaScript script file that calculates height minus any headers and set the height. Debounce is javascript plugin needed to make sure resize works appropriately in older browsers and sometimes chrome. That will get you in the right direction.

Basic HTTP and Bearer Token Authentication

If you are using a reverse proxy such as nginx in between, you could define a custom token, such as X-API-Token.

In nginx you would rewrite it for the upstream proxy (your rest api) to be just auth:

proxy_set_header Authorization $http_x_api_token;

... while nginx can use the original Authorization header to check HTTP AUth.

How to make exe files from a node.js app?

By default, Windows associates .js files with the Windows Script Host, Microsoft's stand-alone JS runtime engine. If you type script.js at a command prompt (or double-click a .js file in Explorer), the script is executed by wscript.exe.

This may be solving a local problem with a global setting, but you could associate .js files with node.exe instead, so that typing script.js at a command prompt or double-clicking/dragging items onto scripts will launch them with Node.

Of course, if—like me—you've associated .js files with an editor so that double-clicking them opens up your favorite text editor, this suggestion won't do much good. You could also add a right-click menu entry of "Execute with Node" to .js files, although this alternative doesn't solve your command-line needs.


The simplest solution is probably to just use a batch file – you don't have to have a copy of Node in the folder your script resides in. Just reference the Node executable absolutely:

"C:\Program Files (x86)\nodejs\node.exe" app.js %*

Another alternative is this very simple C# app which will start Node using its own filename + .js as the script to run, and pass along any command line arguments.

class Program
{
    static void Main(string[] args)
    {
        var info = System.Diagnostics.Process.GetCurrentProcess();
        var proc = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\nodejs\node.exe", "\"" + info.ProcessName + ".js\" " + String.Join(" ", args));
        proc.UseShellExecute = false;
        System.Diagnostics.Process.Start(proc);
    }
}

So if you name the resulting EXE "app.exe", you can type app arg1 ... and Node will be started with the command line "app.js" arg1 .... Note the C# bootstrapper app will immediately exit, leaving Node in charge of the console window.

Since this is probably of relatively wide interest, I went ahead and made this available on GitHub, including the compiled exe if getting in to vans with strangers is your thing.

UITableView Cell selected Color?

If you are using a custom TableViewCell, you can also override awakeFromNib:

override func awakeFromNib() {
    super.awakeFromNib()

    // Set background color
    let view = UIView()
    view.backgroundColor = UIColor.redColor()
    selectedBackgroundView = view
}

How to modify existing, unpushed commit messages?

Use

git commit --amend

To understand it in detail, an excellent post is 4. Rewriting Git History. It also talks about when not to use git commit --amend.

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file

~/.bash_profile 

and append those lines

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

Hidden TextArea

<textarea name="hide" style="display:none;"></textarea>

This sets the css display property to none, which prevents the browser from rendering the textarea.

How to sort 2 dimensional array by column value?

The best approach would be to use the following, as there may be repetitive values in the first column.

var arr = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];

arr.sort(function(a,b) {
    return a[0]-b[0]
});

Creating a selector from a method name with parameters

Beyond what's been said already about selectors, you may want to look at the NSInvocation class.

An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.

An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.

Keep in mind that while it's useful in certain situations, you don't use NSInvocation in a normal day of coding. If you're just trying to get two objects to talk to each other, consider defining an informal or formal delegate protocol, or passing a selector and target object as has already been mentioned.

Jersey stopped working with InjectionManagerFactory not found

Here is the new dependency (August 2017)

    <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-common</artifactId>
    <version>2.0-m03</version>
</dependency>

Open URL in Java to get the content

If you just want to open up the webpage, I think less is more in this case:

import java.awt.Desktop;
import java.net.URI; //Note this is URI, not URL

class BrowseURL{
    public static void main(String args[]) throws Exception{
        // Create Desktop object
        Desktop d=Desktop.getDesktop();

        // Browse a URL, say google.com
        d.browse(new URI("http://google.com"));

        }
    }
}

Package php5 have no installation candidate (Ubuntu 16.04)

You must use prefix "php5.6-" instead of "php5-" as in ubuntu 14.04 and olders:

sudo apt-get install php5.6 php5.6-mcrypt

How to press/click the button using Selenium if the button does not have the Id?

For Next button you can use xpath or cssSelector as below:

xpath for Next button: //input[@value='Next']

cssPath for Next button: input[value=Next]

iOS 7 status bar overlapping UI

If you're using Cordova with Sencha Touch and you're using the normal Sencha Touch navigation/title bars, you can just stretch the navbar and reposition the content within the navbar so it looks at home on iOS 7. Just add this into app.js (after your last Ext.Viewport.add line) :

// Adjust toolbar height when running in iOS to fit with new iOS 7 style
if (Ext.os.is.iOS && Ext.os.version.major >= 7) {
  Ext.select(".x-toolbar").applyStyles("height: 62px; padding-top: 15px;");
}

(Source: http://lostentropy.com/2013/09/22/ios-7-status-bar-fix-for-sencha-touch-apps/)

This is a bit hacky, I know, but it saves dealing with it at the Objective-C level. It won't be much good for those not using Sencha Touch with Cordova, though.

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

Download File to server from URL

Try using cURL

set_time_limit(0); // unlimited max execution time
$options = array(
  CURLOPT_FILE    => '/path/to/download/the/file/to.zip',
  CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
  CURLOPT_URL     => 'http://remoteserver.com/path/to/big/file.zip',
);

$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);

I'm not sure but I believe with the CURLOPT_FILE option it writes as it pulls the data, ie. not buffered.

Polynomial time and exponential time

polynomial time O(n)^k means Number of operations are proportional to power k of the size of input

exponential time O(k)^n means Number of operations are proportional to the exponent of the size of input

Javascript: How to remove the last character from a div or a string?

$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

demo --> http://jsfiddle.net/d72ML/8/

HTML5 Email input pattern attribute

Unfortunately, all suggestions except from B-Money are invalid for most cases.

Here is a lot of valid emails like:

Because of complexity to get validation right, I propose a very generic solution:

<input type="text" pattern="[^@\s]+@[^@\s]+\.[^@\s]+" title="Invalid email address" />

It checks if email contains at least one character (also number or whatever except another "@" or whitespace) before "@", at least two characters (or whatever except another "@" or whitespace) after "@" and one dot in between. This pattern does not accept addresses like lol@company, sometimes used in internal networks. But this one could be used, if required:

<input type="text" pattern="[^@\s]+@[^@\s]+" title="Invalid email address" />

Both patterns accepts also less valid emails, for example emails with vertical tab. But for me it's good enough. Stronger checks like trying to connect to mail-server or ping domain should happen anyway on the server side.

BTW, I just wrote angular directive (not well tested yet) for email validation with novalidate and without based on pattern above to support DRY-principle:

.directive('isEmail', ['$compile', '$q', 't', function($compile, $q, t) {
    var EMAIL_PATTERN = '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$';
    var EMAIL_REGEXP = new RegExp(EMAIL_PATTERN, 'i');
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel){
            function validate(value) {
                var valid = angular.isUndefined(value)
                    || value.length === 0
                    || EMAIL_REGEXP.test(value);
                ngModel.$setValidity('email', valid);
                return valid ? value : undefined;
            }
            ngModel.$formatters.unshift(validate);
            ngModel.$parsers.unshift(validate);
            elem.attr('pattern', EMAIL_PATTERN);
            elem.attr('title', 'Invalid email address');
        }
    };
}])

Usage:

<input type="text" is-email />

For B-Money's pattern is "@" just enough. But it decline two or more "@" and all spaces.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I think its related with jdbc.

I have a similar problem (missing param) when I have a where condition like this:

a = :namedparameter and b = :namedparameter

It's ok, When I have like this:

a = :namedparameter and b = :namedparameter2  (the two param has the same value)

So it's a problem with named parameters. I think there is a bug around named parameter handling, it looks like if only the first parameter get the right value, the second is not set by driver classes. Maybe its not a bug, only I don't know something, but anyway I guess that's the reason for the difference between the SQL dev and the sqlplus running for you, because as far as I know SQL developer uses jdbc driver.

SVN change username

You could ask your colleague to create a patch, which will collapse all the changes that have been made into a single file that you can apply to your own check out. This will update all of your files appropriately and then you can revert the changes on his side and check yours in.

Oracle - how to remove white spaces?

If I understand correctly, this is what you want

select (trim(a) || trim(b))as combinedStrings from yourTable

replace NULL with Blank value or Zero in sql server

The coalesce() is the best solution when there are multiple columns [and]/[or] values and you want the first one. However, looking at books on-line, the query optimize converts it to a case statement.

MSDN excerpt

The COALESCE expression is a syntactic shortcut for the CASE expression.

That is, the code COALESCE(expression1,...n) is rewritten by the query optimizer as the following CASE expression:

CASE
   WHEN (expression1 IS NOT NULL) THEN expression1
   WHEN (expression2 IS NOT NULL) THEN expression2
   ...
   ELSE expressionN
END

With that said, why not a simple ISNULL()? Less code = better solution?

Here is a complete code snippet.

-- drop the test table
drop table #temp1
go

-- create test table
create table #temp1
(
    issue varchar(100) NOT NULL,
    total_amount int NULL
); 
go

-- create test data
insert into #temp1 values
    ('No nulls here', 12),
    ('I am a null', NULL);
go

-- isnull works fine
select
    isnull(total_amount, 0) as total_amount  
from #temp1

Last but not least, how are you getting null values into a NOT NULL column?

I had to change the table definition so that I could setup the test case. When I try to alter the table to NOT NULL, it fails since it does a nullability check.

-- this alter fails
alter table #temp1 alter column total_amount int NOT NULL

Could not resolve all dependencies for configuration ':classpath'

6 years later here, but for them who are stil facing this issue, I solved it as following. It happened when my module had a different gradle version than the main project. I had gradle version 3.5.3 in project and an older version in module. So, I Just updated that version. The file is here:

./node-modules/[module-name]/android/build.gradle

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

Using C++ filestreams (fstream), how can you determine the size of a file?

I'm a novice, but this is my self taught way of doing it:

ifstream input_file("example.txt", ios::in | ios::binary)

streambuf* buf_ptr =  input_file.rdbuf(); //pointer to the stream buffer

input.get(); //extract one char from the stream, to activate the buffer
input.unget(); //put the character back to undo the get()

size_t file_size = buf_ptr->in_avail();
//a value of 0 will be returned if the stream was not activated, per line 3.

How to rename uploaded file before saving it into a directory?

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Binary Data in JSON String. Something better than Base64

I ran into the same problem, and thought I'd share a solution: multipart/form-data.

By sending a multipart form you send first as string your JSON meta-data, and then separately send as raw binary (image(s), wavs, etc) indexed by the Content-Disposition name.

Here's a nice tutorial on how to do this in obj-c, and here is a blog article that explains how to partition the string data with the form boundary, and separate it from the binary data.

The only change you really need to do is on the server side; you will have to capture your meta-data which should reference the POST'ed binary data appropriately (by using a Content-Disposition boundary).

Granted it requires additional work on the server side, but if you are sending many images or large images, this is worth it. Combine this with gzip compression if you want.

IMHO sending base64 encoded data is a hack; the RFC multipart/form-data was created for issues such as this: sending binary data in combination with text or meta-data.

CSS grid wrapping

You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Enter image description here

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Enter image description here

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

How can I define an interface for an array of objects with Typescript?

You can define an interface with an indexer:

interface EnumServiceGetOrderBy {
    [index: number]: { id: number; label: string; key: any };
}

C# List<> Sort by x then y

The trick is to implement a stable sort. I've created a Widget class that can contain your test data:

public class Widget : IComparable
{
    int x;
    int y;
    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Widget(int argx, int argy)
    {
        x = argx;
        y = argy;
    }

    public int CompareTo(object obj)
    {
        int result = 1;
        if (obj != null && obj is Widget)
        {
            Widget w = obj as Widget;
            result = this.X.CompareTo(w.X);
        }
        return result;
    }

    static public int Compare(Widget x, Widget y)
    {
        int result = 1;
        if (x != null && y != null)                
        {                
            result = x.CompareTo(y);
        }
        return result;
    }
}

I implemented IComparable, so it can be unstably sorted by List.Sort().

However, I also implemented the static method Compare, which can be passed as a delegate to a search method.

I borrowed this insertion sort method from C# 411:

 public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
        {           
            int count = list.Count;
            for (int j = 1; j < count; j++)
            {
                T key = list[j];

                int i = j - 1;
                for (; i >= 0 && comparison(list[i], key) > 0; i--)
                {
                    list[i + 1] = list[i];
                }
                list[i + 1] = key;
            }
    }

You would put this in the sort helpers class that you mentioned in your question.

Now, to use it:

    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();

        widgets.Add(new Widget(0, 1));
        widgets.Add(new Widget(1, 1));
        widgets.Add(new Widget(0, 2));
        widgets.Add(new Widget(1, 2));

        InsertionSort<Widget>(widgets, Widget.Compare);

        foreach (Widget w in widgets)
        {
            Console.WriteLine(w.X + ":" + w.Y);
        }
    }

And it outputs:

0:1
0:2
1:1
1:2
Press any key to continue . . .

This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.

EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

"<pre>" is an HTML tag. If you insert this line of code in your program

echo "<pre>";

then you will enable the viewing of multiple spaces and line endings. Without this, all \n, \r and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with <br> you would be able to break the line and go to the next one.

For example,

the code below would be displayed on multiple lines, due to \n line ending specifier.

<?php
    echo "<pre>";
    printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
    printf("Goodbye");
?>

However the following code, would be displayed in one line only (line endings are disregarded).

<?php
    printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
    printf("Goodbye");
?>

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

php REQUEST_URI

perhaps

$id = isset($_GET['id'])?$_GET['id']:null;

and

$other_var = isset($_GET['othervar'])?$_GET['othervar']:null;

Java integer to byte array

integer & 0xFF

for the first byte

(integer >> 8) & 0xFF

for the second and loop etc., writing into a preallocated byte array. A bit messy, unfortunately.

Can Python test the membership of multiple values in a list?

how can you be pythonic without lambdas! .. not to be taken seriously .. but this way works too:

orig_array = [ ..... ]
test_array = [ ... ]

filter(lambda x:x in test_array, orig_array) == test_array

leave out the end part if you want to test if any of the values are in the array:

filter(lambda x:x in test_array, orig_array)

Case insensitive searching in Oracle

select user_name
from my_table
where nlssort(user_name, 'NLS_SORT = Latin_CI') = nlssort('%AbC%', 'NLS_SORT = Latin_CI')

How to identify object types in java

You forgot the .class:

if (value.getClass() == Integer.class) {
    System.out.println("This is an Integer");
} 
else if (value.getClass() == String.class) {
    System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
    System.out.println("This is a Float");
}

Note that this kind of code is usually the sign of a poor OO design.

Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:

"foo".getClass() == Object.class

is false, whereas

"foo" instanceof Object

is true.

Whether one or the other must be used depends on your requirements.

Function Pointers in Java

There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.

Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.

Example:

class MyComponent extends JPanel {
    private JButton button;
    public MyComponent() {
        button = new JButton("click me");
        button.addActionListener(buttonAction);
        add(button);
    }

    private ActionListener buttonAction = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // handle the event...
            // note how the handler instance can access 
            // members of the surrounding class
            button.setText("you clicked me");
        }
    }
}

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

If you are starting out a react-native app and seeing this issue, then you have to follow all the instructions listed in firebase (when you setup iOS/android app) or the instructions @ React-native google auth android DEVELOPER_ERROR Code 10 question

enter image description here

Is there a way to specify a default property value in Spring XML?

Also i find another solution which work for me. In our legacy spring project we use this method for give our users possibilities to use this own configurations:

<bean id="appUserProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="ignoreResourceNotFound" value="false"/>
    <property name="locations">
        <list>
            <value>file:./conf/user.properties</value>
        </list>
    </property>
</bean>

And in our code to access this properties need write something like that:

@Value("#{appUserProperties.userProperty}")
private String userProperty

And if a situation arises when you need to add a new property but right now you don't want to add it in production user config it very fast become a hell when you need to patch all your test contexts or your application will be fail on startup.

To handle this problem you can use the next syntax to add a default value:

@Value("#{appUserProperties.get('userProperty')?:'default value'}")
private String userProperty

It was a real discovery for me.

How to call shell commands from Ruby

This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link.

First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems.

Here are ways to execute a shell script:

cmd = "echo 'hi'" # Sample string that can be used
  1. Kernel#` , commonly called backticks – `cmd`

    This is like many other languages, including Bash, PHP, and Perl.

    Returns the result (i.e. standard output) of the shell command.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-60

    value = `echo 'hi'`
    value = `#{cmd}`
    
  2. Built-in syntax, %x( cmd )

    Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{ ... } is allowed.

    Returns the result (i.e. standard output) of the shell command, just like the backticks.

    Docs: https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings

    value = %x( echo 'hi' )
    value = %x[ #{cmd} ]
    
  3. Kernel#system

    Executes the given command in a subshell.

    Returns true if the command was found and run successfully, false otherwise.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-system

    wasGood = system( "echo 'hi'" )
    wasGood = system( cmd )
    
  4. Kernel#exec

    Replaces the current process by running the given external command.

    Returns none, the current process is replaced and never continues.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec

    exec( "echo 'hi'" )
    exec( cmd ) # Note: this will never be reached because of the line above
    

Here's some extra advice: $?, which is the same as $CHILD_STATUS, accesses the status of the last system executed command if you use the backticks, system() or %x{}. You can then access the exitstatus and pid properties:

$?.exitstatus

For more reading see:

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

python JSON object must be str, bytes or bytearray, not 'dict

You are passing a dictionary to a function that expects a string.

This syntax:

{"('Hello',)": 6, "('Hi',)": 5}

is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

If you pass this string to loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

then it will return a dictionary that looks a lot like the one you are trying to pass to it.

You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.


Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

C-like structures in Python

Personally, I like this variant too. It extends @dF's answer.

class struct:
    def __init__(self, *sequential, **named):
        fields = dict(zip(sequential, [None]*len(sequential)), **named)
        self.__dict__.update(fields)
    def __repr__(self):
        return str(self.__dict__)

It supports two modes of initialization (that can be blended):

# Struct with field1, field2, field3 that are initialized to None.
mystruct1 = struct("field1", "field2", "field3") 
# Struct with field1, field2, field3 that are initialized according to arguments.
mystruct2 = struct(field1=1, field2=2, field3=3)

Also, it prints nicer:

print(mystruct2)
# Prints: {'field3': 3, 'field1': 1, 'field2': 2}

How to set HTTP headers (for cache-control)?

OWASP recommends the following,

Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.

<IfModule mod_headers.c>
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</IfModule>

Anybody knows any knowledge base open source?

I believe that phpMyFAQ is the most useful KB I have seen so far ( from open-source ). It is simple, straight-forward KB software, is it PHP => can be easily installed on any server and can be customized if you know a bit of php. In addition it is made simple enough but with correct priorities and logic. I suggest to install it and play with it, I did and I decided to stay with this KB.

How to create the branch from specific commit in different branch

You have to do:

git branch <branch_name> <commit>

(you were interchanging the branch name and commit)

Or you can do:

git checkout -b <branch_name> <commit>

If in place of you use branch name, you get a branch out of tip of the branch.

Python __call__ special method practical example

Django forms module uses __call__ method nicely to implement a consistent API for form validation. You can write your own validator for a form in Django as a function.

def custom_validator(value):
    #your validation logic

Django has some default built-in validators such as email validators, url validators etc., which broadly fall under the umbrella of RegEx validators. To implement these cleanly, Django resorts to callable classes (instead of functions). It implements default Regex Validation logic in a RegexValidator and then extends these classes for other validations.

class RegexValidator(object):
    def __call__(self, value):
        # validation logic

class URLValidator(RegexValidator):
    def __call__(self, value):
        super(URLValidator, self).__call__(value)
        #additional logic

class EmailValidator(RegexValidator):
    # some logic

Now both your custom function and built-in EmailValidator can be called with the same syntax.

for v in [custom_validator, EmailValidator()]:
    v(value) # <-----

As you can see, this implementation in Django is similar to what others have explained in their answers below. Can this be implemented in any other way? You could, but IMHO it will not be as readable or as easily extensible for a big framework like Django.

How do I capture all of my compiler's output to a file?

Based on an earlier reply by @dmckee

make | tee makelog.txt

This gives you real-time scrolling output while compiling, and simultaneously write to the makelog.txt file.

How to get week number in Python?

There are many systems for week numbering. The following are the most common systems simply put with code examples:

  • ISO: First week starts with Monday and must contain the January 4th. The ISO calendar is already implemented in Python:

    >>> from datetime import date
    >>> date(2014, 12, 29).isocalendar()[:2]
    (2015, 1)
    
  • North American: First week starts with Sunday and must contain the January 1st. The following code is my modified version of Python's ISO calendar implementation for the North American system:

    from datetime import date
    
    def week_from_date(date_object):
        date_ordinal = date_object.toordinal()
        year = date_object.year
        week = ((date_ordinal - _week1_start_ordinal(year)) // 7) + 1
        if week >= 52:
            if date_ordinal >= _week1_start_ordinal(year + 1):
                year += 1
                week = 1
        return year, week
    
    def _week1_start_ordinal(year):
        jan1 = date(year, 1, 1)
        jan1_ordinal = jan1.toordinal()
        jan1_weekday = jan1.weekday()
        week1_start_ordinal = jan1_ordinal - ((jan1_weekday + 1) % 7)
        return week1_start_ordinal
    
    >>> from datetime import date
    >>> week_from_date(date(2014, 12, 29))
    (2015, 1)
    
  • MMWR (CDC): First week starts with Sunday and must contain the January 4th. I created the epiweeks package specifically for this numbering system (also has support for the ISO system). Here is an example:
    >>> from datetime import date
    >>> from epiweeks import Week
    >>> Week.fromdate(date(2014, 12, 29))
    (2014, 53)
    

How to join two JavaScript Objects, without using JQUERY

Just another solution using underscore.js:

_.extend({}, obj1, obj2);

Excel date to Unix timestamp

Here's my ultimate answer to this.

Also apparently javascript's new Date(year, month, day) constructor doesn't account for leap seconds too.

// Parses an Excel Date ("serial") into a
// corresponding javascript Date in UTC+0 timezone.
//
// Doesn't account for leap seconds.
// Therefore is not 100% correct.
// But will do, I guess, since we're
// not doing rocket science here.
//
// https://www.pcworld.com/article/3063622/software/mastering-excel-date-time-serial-numbers-networkdays-datevalue-and-more.html
// "If you need to calculate dates in your spreadsheets,
//  Excel uses its own unique system, which it calls Serial Numbers".
//
lib.parseExcelDate = function (excelSerialDate) {
  // "Excel serial date" is just
  // the count of days since `01/01/1900`
  // (seems that it may be even fractional).
  //
  // The count of days elapsed
  // since `01/01/1900` (Excel epoch)
  // till `01/01/1970` (Unix epoch).
  // Accounts for leap years
  // (19 of them, yielding 19 extra days).
  const daysBeforeUnixEpoch = 70 * 365 + 19;

  // An hour, approximately, because a minute
  // may be longer than 60 seconds, see "leap seconds".
  const hour = 60 * 60 * 1000;

  // "In the 1900 system, the serial number 1 represents January 1, 1900, 12:00:00 a.m.
  //  while the number 0 represents the fictitious date January 0, 1900".
  // These extra 12 hours are a hack to make things
  // a little bit less weird when rendering parsed dates.
  // E.g. if a date `Jan 1st, 2017` gets parsed as
  // `Jan 1st, 2017, 00:00 UTC` then when displayed in the US
  // it would show up as `Dec 31st, 2016, 19:00 UTC-05` (Austin, Texas).
  // That would be weird for a website user.
  // Therefore this extra 12-hour padding is added
  // to compensate for the most weird cases like this
  // (doesn't solve all of them, but most of them).
  // And if you ask what about -12/+12 border then
  // the answer is people there are already accustomed
  // to the weird time behaviour when their neighbours
  // may have completely different date than they do.
  //
  // `Math.round()` rounds all time fractions
  // smaller than a millisecond (e.g. nanoseconds)
  // but it's unlikely that an Excel serial date
  // is gonna contain even seconds.
  //
  return new Date(Math.round((excelSerialDate - daysBeforeUnixEpoch) * 24 * hour) + 12 * hour);
};

Less aggressive compilation with CSS3 calc

There is several escaping options with same result:

body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

Unit testing with Spring Security

I would take a look at Spring's abstract test classes and mock objects which are talked about here. They provide a powerful way of auto-wiring your Spring managed objects making unit and integration testing easier.

Bootstrap 3: how to make head of dropdown link clickable in navbar

This topic is super old, but I needed a solution that worked on desktop AND mobile and none of these seemed to work for me. Unfortunately, this is the solution I came up with that involves checking the window width and comparing it to the mobile menu breakpoint:

$( 'a.dropdown-toggle' ).on( 'click', function( e ) {
    var $a = $( this ),
        $parent = $a.parent( 'li' ),
        mobile_bp = 767, // Default breakpoint, may need to change this.
        window_width = $( window ).width(),
        is_mobile = window_width <= mobile_bp;

    if ( is_mobile && ! $parent.hasClass( 'open' ) ) {
        e.preventDefault();
        return false;
    }

    location.href = $a.attr( 'href' );
    return true;
});

Android Studio how to run gradle sync manually?

I think ./gradlew tasks is same with Android studio sync. Why? I will explain it.

I meet a problem when I test jacoco coverage report. When I run ./gradlew clean :Test:testDebugUnitTest in command line directly , error appear.

Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.2.jar_5bdiis3s7lm1rcnv0gawjjfxc/jacocoagent.jar

However, if I click android studio sync firstly , it runs OK. Because the build/../jacocoagent.jar appear naturally. I dont know why, maybe there is bug in jacoco plugin. Unit I find running .gradlew tasks makes the jar appear as well. So I can get the same result in gralde script.

Besides, gradle --recompile-scripts does not work for the problem.

How to create a inner border for a box in html?

Take a look at this , we can simply do this with outline-offset property

Output image look like

enter image description here

_x000D_
_x000D_
.black_box {_x000D_
    width:500px;_x000D_
    height:200px;_x000D_
    background:#000;_x000D_
    float:left;_x000D_
    border:2px solid #000;_x000D_
    outline: 1px dashed #fff;_x000D_
    outline-offset: -10px;_x000D_
}
_x000D_
<div class="black_box"></div>
_x000D_
_x000D_
_x000D_

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This can happen if you have a newline (or other control character) in a JSON string literal.

{"foo": "bar
baz"}

If you are the one producing the data, replace actual newlines with escaped ones "\\n" when creating your string literals.

{"foo": "bar\nbaz"}

Setting up Gradle for api 26 (Android)

Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.

MySQL Removing Some Foreign keys

As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.

ALTER TABLE your_table_with_fk
  drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
  drop KEY the_same_name_as_above

How to place two forms on the same page?

Here are two form with two submit button:

<form method="post" action="page.php">
  <input type="submit" name="btnPostMe1" value="Confirm"/>
</form>

<form method="post" action="page.php">
  <input type="submit" name="btnPostMe2" value="Confirm"/>
</form>

And here is your PHP code:

if (isset($_POST['btnPostMe1'])) { //your code 1 }
if (isset($_POST['btnPostMe2'])) { //your code 2 }

git visual diff between branches

Have a look at git show-branch

There's a lot you can do with core git functionality. It might be good to specify what you'd like to include in your visual diff. Most answers focus on line-by-line diffs of commits, where your example focuses on names of files affected in a given commit.

One visual that seems not to be addressed is how to see the commits that branches contain (whether in common or uniquely).

For this visual, I'm a big fan of git show-branch; it breaks out a well organized table of commits per branch back to the common ancestor. - to try it on a repo with multiple branches with divergences, just type git show-branch and check the output - for a writeup with examples, see Compare Commits Between Git Branches

Nesting optgroups in a dropdownlist/select

The HTML spec here is really broken. It should allow nested optgroups and recommend user agents render them as nested menus. Instead, only one optgroup level is allowed. However, they do have to say the following on the subject:

Note. Implementors are advised that future versions of HTML may extend the grouping mechanism to allow for nested groups (i.e., OPTGROUP elements may nest). This will allow authors to represent a richer hierarchy of choices.

And user agents could start using submenus to render optgoups instead of displaying titles before the first option element in an optgroup as they do now.

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

I've searched around, and only this solution helped me:

mysql -u root -p

set global net_buffer_length=1000000; --Set network buffer length to a large byte number

set global max_allowed_packet=1000000000; --Set maximum allowed packet size to a large byte number

SET foreign_key_checks = 0; --Disable foreign key checking to avoid delays,errors and unwanted behaviour

source file.sql --Import your sql dump file

SET foreign_key_checks = 1; --Remember to enable foreign key checks when procedure is complete!

The answer is found here.

How to handle errors with boto3?

Or a comparison on the class name e.g.

except ClientError as e:
    if 'EntityAlreadyExistsException' == e.__class__.__name__:
        # handle specific error

Because they are dynamically created you can never import the class and catch it using real Python.

Getting a list of all subdirectories in the current directory

Since I stumbled upon this problem using Python 3.4 and Windows UNC paths, here's a variant for this environment:

from pathlib import WindowsPath

def SubDirPath (d):
    return [f for f in d.iterdir() if f.is_dir()]

subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$'))
print(subdirs)

Pathlib is new in Python 3.4 and makes working with paths under different OSes much easier: https://docs.python.org/3.4/library/pathlib.html

How do you test to see if a double is equal to NaN?

You can check for NaN by using var != var. NaN does not equal NaN.

EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.

How can I replace a regex substring match in Javascript?

I think the simplest way to achieve your goal is this:

var str   = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);

How to find a whole word in a String in java

The solution seems to be long accepted, but the solution could be improved, so if someone has a similar problem:

This is a classical application for multi-pattern-search-algorithms.

Java Pattern Search (with Matcher.find) is not qualified for doing that. Searching for exactly one keyword is optimized in java, searching for an or-expression uses the regex non deterministic automaton which is backtracking on mismatches. In worse case each character of the text will be processed l times (where l is the sum of the pattern lengths).

Single pattern search is better, but not qualified, too. One will have to start the whole search for every keyword pattern. In worse case each character of the text will be processed p times where p is the number of patterns.

Multi pattern search will process each character of the text exactly once. Algorithms suitable for such a search would be Aho-Corasick, Wu-Manber, or Set Backwards Oracle Matching. These could be found in libraries like Stringsearchalgorithms or byteseek.

// example with StringSearchAlgorithms

AhoCorasick stringSearch = new AhoCorasick(asList("123woods", "woods"));

CharProvider text = new StringCharProvider("I will come and meet you at the woods 123woods and all the woods", 0);

StringFinder finder = stringSearch.createFinder(text);

List<StringMatch> all = finder.findAll();

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Foreign keys in mongo?

Short answer: You should to use "weak references" between collections, using ObjectId properties:

References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.

https://docs.mongodb.com/manual/core/data-modeling-introduction/#references

This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).

.includes() not working in Internet Explorer

includes() is not supported by most browsers. Your options are either to use

-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

or to use

-indexof()

var str = "abcde";
var n = str.indexOf("cd");

Which gives you n=2

This is widely supported.

Why use the params keyword?

One more important thing needs to be highlighted. It's better to use params because it is better for performance. When you call a method with params argument and passed to it nothing:

public void ExampleMethod(params string[] args)
{
// do some stuff
}

call:

ExampleMethod();

Then a new versions of the .Net Framework do this (from .Net Framework 4.6):

ExampleMethod(Array.Empty<string>());

This Array.Empty object can be reused by framework later, so there are no needs to do redundant allocations. These allocations will occur when you call this method like this:

 ExampleMethod(new string[] {});

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
    </c:forEach>
</select>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>
</select>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

Using two CSS classes on one element

If you have 2 classes i.e. .indent and .font, class="indent font" works.

You dont have to have a .indent.font{} in css.

You can have the classes separate in css and still call both just using the class="class1 class2" in the html. You just need a space between one or more class names.

Installing MySQL-python

Reread the error message. It says:

sh: mysql_config: not found

If you are on Ubuntu Natty, mysql_config belongs to package libmysqlclient-dev

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

Copy text from nano editor to shell

Nano to Shell:

1. Using mouse to mark the text.

2. Right-Click the mouse in the Shell.

Within Nano:

1. CTRL+6 (or hold Shift and move cursor) for Mark Set and mark what you want (the end could do some extra help).

2. ALT+6 for copying the marked text.

3. CTRL+u at the place you want to paste.

or

1. CTRL+6 (or hold Shift and move cursor) for Mark Set and mark what you want (the end could do some extra help).

2. CTRL+k for cutting what you want to copy

3. CTRL+u for pasting what you have just cut because you just want to copy.

4. CTRL+u at the place you want to paste.

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

How do I remove all .pyc files from a project?

To delete all the python compiled files in current directory.

find . -name "__pycache__"|xargs rm -rf
find . -name "*.pyc"|xargs rm -rf

destination path already exists and is not an empty directory

I got same issue while using cygwin to install nvm

In fact, the target directory where empty but the git binary used was the one from windows (and not git from cygwin git package).

After installing cygwin git package, the git clone from nvm install was ok!

How can I uninstall Ruby on ubuntu?

I have tried many include sudo apt-get purge ruby , sudo apt-get remove ruby and sudo aptitude purpe ruby, both with and without '*' at the end. But none of them worked, it's may be I've installed more than one version ruby.

Finally, when I triedsudo apt-get purge ruby1.9(with the version), then it works.

T-SQL query to show table definition?

There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.

SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'

SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

gcc error: wrong ELF class: ELFCLASS64

sudo apt-get install ia32-libs 

How to convert buffered image to image and vice-versa?

You can try saving (or writing) the Buffered Image with the changes you made and then opening it as an Image.

EDIT:

try {
    // Retrieve Image
    BufferedImage buffer = ImageIO.read(new File("old.png"));;
    // Here you can rotate your image as you want (making your magic)
    File outputfile = new File("saved.png");
    ImageIO.write(buffer, "png", outputfile); // Write the Buffered Image into an output file
    Image image  = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
    ...
}

Make HTML5 video poster be same size as video itself

My solution combines user2428118 and Veiko Jääger's answers, allowing for preloading but without requiring a separate transparent image. We use a base64 encoded 1px transparent image instead.

<style type="text/css" >
    video{
        background: transparent url("poster.jpg") 50% 50% / cover no-repeat ;
    }
</style>
<video controls poster="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" >
    <source src="movie.mp4" type="video/mp4">
    <source src="movie.ogg" type="video/ogg">
</video>

Javascript use variable as object name

var micro=[{'test':'hello'}];

var device = 'test';

console.log(micro[device]);

How do I start my app on startup?

Listen for the ACTION_BOOT_COMPLETE and do what you need to from there. There is a code snippet here.

Update:

Original link on answer is down, so based on the comments, here it is linked code, because no one would ever miss the code when the links are down.

In AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

...

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

...

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  //MyActivity can be anything which you want to start on bootup...
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

Source: https://web.archive.org/web/20150520124552/http://www.androidsnippets.com/autostart-an-application-at-bootup

How to extract the n-th elements from a list of tuples?

Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method

setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))

Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499

So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.

Excel Date to String conversion

In Excel 2010, marg's answer only worked for some of the data I had in my spreadsheet (it was imported). The following solution worked on all data.

Sub change()
    toText Selection
End Sub

Sub toText(target As range)
Dim cell As range
Dim txt As String
    For Each cell In target
        txt = cell.text
        cell.NumberFormat = "@"
        cell.Value2 = txt
    Next cell
End Sub

How to add include path in Qt Creator?

For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:

enter image description here

Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.

PowerShell equivalent to grep -f

The -Pattern parameter in Select-String supports an array of patterns. So the one you're looking for is:

Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)

This searches through the textfile doc.txt by using every regex(one per line) in regex.txt

Pass a password to ssh in pure bash

Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage

which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh "thought" that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

FileProvider - IllegalArgumentException: Failed to find configured root

If you are using internal cache then use.

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="cache" path="/" />
</paths>

How to calculate percentage when old value is ZERO

use below code, as this is 100% growth rate in case of 0 to any number :

IFERROR((NEW-OLD)/OLD,100%)

Invalidating JSON Web Tokens

In this example, I am assuming the end user also has an account. If this isn't he case, then the rest of the approach is unlikely to work.

When you create the JWT, persist it in the database, associated with the account that is logging in. This does mean that just from the JWT you could pull out additional information about the user, so depending on the environment, this may or may not be OK.

On every request after, not only do you perform the standard validation that (I hope) comes with what ever framework you use (that validates the JWT is valid), it also includes soemthing like the user ID or another token (that needs to match that in the database).

When you log out, delete the cookie (if using) and invalidate the JWT (string) from the database. If the cookie can't be deleted from the client side, then at least the log out process will ensure the token is destroyed.

I found this approach, coupled with another unique identifier (so there are 2 persist items in the database and are available to the front end) with the session to be very resilient

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

It depends. See the MySQL Performance Blog post on this subject: To SQL_CALC_FOUND_ROWS or not to SQL_CALC_FOUND_ROWS?

Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that SQL_CALC_FOUND_ROWS is almost always slower - sometimes up to 10x slower - than running two queries.

C# how to use enum with switch

Two things. First, you need to qualify the enum reference in your test - rather than "PLUS", it should be "Operator.PLUS". Second, this code would be a lot more readable if you used the enum member names rather than their integral values in the switch statement. I've updated your code:

public enum Operator
{
    PLUS, MINUS, MULTIPLY, DIVIDE
}

public static double Calculate(int left, int right, Operator op)
{
    switch (op)
    {
        default:
        case Operator.PLUS:
            return left + right;

        case Operator.MINUS:
            return left - right;

        case Operator.MULTIPLY:
            return left * right;

        case Operator.DIVIDE:
            return left / right;
    }
}

Call this with:

Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));

What to do about Eclipse's "No repository found containing: ..." error messages?

Eclipse Kepler (at least) allows to specifically reload a software site in the Preferences > Install/Update > Available Software Sites dialog.

It is a cleaner / simpler solution than the workaround explained above (add trailing slash) and it worked for me...

Note: a link to this dialog is also available in the Install New Software dialog.

How to convert std::string to LPCWSTR in C++ (Unicode)

I prefer using standard converters:

#include <codecvt>

std::string s = "Hi";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(s);
LPCWSTR result = wide.c_str();

Please find more details in this answer: https://stackoverflow.com/a/18597384/592651


Update 12/21/2020 : My answer was commented on by @Andreas H . I thought his comment is valuable, so I updated my answer accordingly:

  1. codecvt_utf8_utf16 is deprecated in C++17.
  2. Also the code implies that source encoding is UTF-8 which it usually isn't.
  3. In C++20 there is a separate type std::u8string for UTF-8 because of that.

But it worked for me because I am still using an old version of C++ and it happened that my source encoding was UTF-8 .

Hiding the R code in Rmarkdown/knit and just showing the results

Sure, just do

```{r someVar, echo=FALSE}
someVariable
```

to show some (previously computed) variable someVariable. Or run code that prints etc pp.

So for plotting, I have eg

### Impact of choice of ....
```{r somePlot, echo=FALSE}
plotResults(Res, Grid, "some text", "some more text")
```

where the plotting function plotResults is from a local package.

Fatal error: Call to a member function prepare() on null

In ---- model: Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

Change the class ----- extends Model to class ----- extends Eloquent

git pull error "The requested URL returned error: 503 while accessing"

I received the same error when trying to clone a heroku git repository.

Upon accessing heroku dashboard I saw a warning that the tool was under maintenance, and should come back in a few hours.

Cloning into 'foo-repository'...
remote: !        Heroku has temporarily disabled this feature, please try again shortly. See https://status.heroku.com for current Heroku platform status.
fatal: unable to access 'https://git.heroku.com/foo-repository.git/': The requested URL returned error: 503

If you receive the same error, check the service status

Get height of div with no height set in css

Just a note in case others have the same problem.

I had the same problem and found a different answer. I found that getting the height of a div that's height is determined by its contents needs to be initiated on window.load, or window.scroll not document.ready otherwise i get odd heights/smaller heights, i.e before the images have loaded. I also used outerHeight().

var currentHeight = 0;
$(window).load(function() {
    //get the natural page height -set it in variable above.

    currentHeight = $('#js_content_container').outerHeight();

    console.log("set current height on load = " + currentHeight)
    console.log("content height function (should be 374)  = " + contentHeight());   

});

Specify an SSH key for git push for a given domain

Even if the user and host are the same, they can still be distinguished in ~/.ssh/config. For example, if your configuration looks like this:

Host gitolite-as-alice
  HostName git.company.com
  User git
  IdentityFile /home/whoever/.ssh/id_rsa.alice
  IdentitiesOnly yes

Host gitolite-as-bob
  HostName git.company.com
  User git
  IdentityFile /home/whoever/.ssh/id_dsa.bob
  IdentitiesOnly yes

Then you just use gitolite-as-alice and gitolite-as-bob instead of the hostname in your URL:

git remote add alice git@gitolite-as-alice:whatever.git
git remote add bob git@gitolite-as-bob:whatever.git

Note

You want to include the option IdentitiesOnly yes to prevent the use of default ids. Otherwise, if you also have id files matching the default names, they will get tried first because unlike other config options (which abide by "first in wins") the IdentityFile option appends to the list of identities to try. See: https://serverfault.com/questions/450796/how-could-i-stop-ssh-offering-a-wrong-key/450807#450807

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

How to make a promise from setTimeout

Implementation:

// Promisify setTimeout
const pause = (ms, cb, ...args) =>
  new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        resolve(await cb?.(...args))
      } catch (error) {
        reject(error)
      }
    }, ms)
  })

Tests:

// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
  throw Error('foo')
}).catch(error => console.error(error))

How to set locale in DatePipe in Angular 2?

Solution with LOCALE_ID is great if you want to set the language for your app once. But it doesn’t work, if you want to change the language during runtime. For this case you can implement custom date pipe.

import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'localizedDate',
  pure: false
})
export class LocalizedDatePipe implements PipeTransform {

  constructor(private translateService: TranslateService) {
  }

  transform(value: any, pattern: string = 'mediumDate'): any {
    const datePipe: DatePipe = new DatePipe(this.translateService.currentLang);
    return datePipe.transform(value, pattern);
  }

}

Now if you change the app display language using TranslateService (see ngx-translate)

this.translateService.use('en');

the formats within your app should automatically being updated.

Example of use:

<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p>
<p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>

or check my simple "Notes" project here.

enter image description here

select certain columns of a data table

First store the table in a view, then select columns from that view into a new table.

// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
    table.Columns.Add("col" + i.ToString());

// Load the table with contrived data
for (int i = 0; i < 100; i++)
{
    System.Data.DataRow row = table.NewRow();
    for (int j = 0; j < 11; j++)
        row[j] = i.ToString() + ", " + j.ToString();
    table.Rows.Add(row);
}

// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");

Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns

Excel VBA - select multiple columns not in sequential order

Range("A:B,D:E,G:H").Select can help

Edit note: I just saw you have used different column sequence, I have updated my answer

Cancel split window in Vim

Okay I just detached and reattach to the screen session and I am back to normal screen I wanted

XPath Query: get attribute href from a tag

The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.

If someone is using frameworks like scrapy the you will have to use /html/body//a[contains(@href,'com')][2]/@href along with get() like this:

response.xpath('//a[contains(@href,'com')][2]/@href').get()

Extract time from moment js object

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');

How to set cursor to input box in Javascript?

One of the things that can bite you is if you are using .onmousedown as your user interaction; when you do that, and then an attempt is immediately made to select a field, it won't happen, because the mouse is being held down on something else. So change to .onmouseup and viola, now focus() works, because the mouse is in an un-clicked state when the attempt to change focus is made.

How to select some rows with specific rownames from a dataframe?

df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <-  letters[1:10]
df[c('a','b'),]

private constructor

Private constructor means a user cannot directly instantiate a class. Instead, you can create objects using something like the Named Constructor Idiom, where you have static class functions that can create and return instances of a class.

The Named Constructor Idiom is for more intuitive usage of a class. The example provided at the C++ FAQ is for a class that can be used to represent multiple coordinate systems.

This is pulled directly from the link. It is a class representing points in different coordinate systems, but it can used to represent both Rectangular and Polar coordinate points, so to make it more intuitive for the user, different functions are used to represent what coordinate system the returned Point represents.

 #include <cmath>               // To get std::sin() and std::cos()

 class Point {
 public:
   static Point rectangular(float x, float y);      // Rectangular coord's
   static Point polar(float radius, float angle);   // Polar coordinates
   // These static methods are the so-called "named constructors"
   ...
 private:
   Point(float x, float y);     // Rectangular coordinates
   float x_, y_;
 };

 inline Point::Point(float x, float y)
   : x_(x), y_(y) { }

 inline Point Point::rectangular(float x, float y)
 { return Point(x, y); }

 inline Point Point::polar(float radius, float angle)
 { return Point(radius*std::cos(angle), radius*std::sin(angle)); }

There have been a lot of other responses that also fit the spirit of why private constructors are ever used in C++ (Singleton pattern among them).

Another thing you can do with it is to prevent inheritance of your class, since derived classes won't be able to access your class' constructor. Of course, in this situation, you still need a function that creates instances of the class.

PHP: Show yes/no confirmation dialog

<a onclick="javascript:return confirm('Are You Confirm Deletion');" href="delete_customer.php?a=<?php echo $row['id']; ?>"  class="btn btn-danger a-btn-slide-text" style="color: white; width:86px; height:37px;" > <span class="glyphicon glyphicon-remove" aria-hidden="true"></span><span><strong></a></strong></span> 

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

Remove Top Line of Text File with PowerShell

For smaller files you could use this:

& C:\windows\system32\more +1 oldfile.csv > newfile.csv | out-null

... but it's not very effective at processing my example file of 16MB. It doesn't seem to terminate and release the lock on newfile.csv.

Vim multiline editing like in sublimetext?

if you use the "global" command, you can repeat what you can do on one online an any number of lines.

:g/<search>/.<your ex command>

example:

:g/foo/.s/bar/baz/g

The above command finds all lines that have foo, and replace all occurrences of bar on that line with baz.

:g/.*/

will do on every line

Object not found! The requested URL was not found on this server. localhost

One thing I found out is that your folder holding your php/html files cannot be named the same name as the folder in your HTDOCS carrying your project.

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

Display help message with python argparse when script is called without any arguments

This isn't good (also, because intercepts all errors), but:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)

    parser.add_argument(...)
    ...

Here is definition of the error function of the ArgumentParser class:

https://github.com/python/cpython/blob/276eb67c29d05a93fbc22eea5470282e73700d20/Lib/argparse.py#L2374

. As you see, following signature, it takes two arguments. However, functions outside the class nothing knows about first argument: self, because, roughly speaking, this is parameter for the class. (I know, that you know...) Thereby, just pass own self and message in _error(...) can't (

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error
    ...
...

will output:

...
"AttributeError: 'str' object has no attribute 'print_help'"

). You can pass parser (self) in _error function, by calling it:

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)
    ...
...

, but you don't want exit the program, right now. Then return it:

def _error(parser):
    def wrapper():
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Nonetheless, parser doesn't know, that it has been modified, thus when an error occurs, it will send cause of it (by the way, its localized translation). Well, then intercept it:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Now, when error occurs and parser will send cause of it, you'll intercept it, look at this, and... throw out.

How to set background color of HTML element using css properties in JavaScript

$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

so many ways are there I think it is very easy and simple

Demo On Plunker

How to load json into my angular.js ng-model?

As Kris mentions, you can use the $resource service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http service. In this case you can call its get method.

If you have the following JSON

[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

You can load it like this

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;                
        });
});

The get method returns a promise object which first argument is a success callback and the second an error callback.

When you add $http as a parameter of a function Angular does it magic and injects the $http resource into your controller.

I've put some examples here

SQL Server: the maximum number of rows in table

It's hard to give a generic answer to this. It really depends on number of factors:

  • what size your row is
  • what kind of data you store (strings, blobs, numbers)
  • what do you do with your data (just keep it as archive, query it regularly)
  • do you have indexes on your table - how many
  • what's your server specs

etc.

As answered elsewhere here, 100,000 a day and thus per table is overkill - I'd suggest monthly or weekly perhaps even quarterly. The more tables you have the bigger maintenance/query nightmare it will become.

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

I'm an occasional iOS dev (soon to be more) but I still couldn't find the setting as guided by the other answer (since I did not have that Keychain item the answer shows), so now that I found it I thought I might just add this snapshot with the highlighted locations that you will need to click and find.

  1. Start in the upper left
  2. Choose the project folder icon
  3. Choose your main project name below the project folder icon.
  4. Choose Build Settings on the right side.
  5. Choose your project under TARGETS.
  6. Scroll very far down (or search for the word inference in search text box)

Finding the setting

How do I convert an interval into a number of hours with postgres?

If you want integer i.e. number of days:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int

In a Git repository, how to properly rename a directory?

For case sensitive renaming, git mv somefolder someFolder has worked for me before but didn't today for some reason. So as a workaround I created a new folder temp, moved all the contents of somefolder into temp, deleted somefolder, committed the temp, then created someFolder, moved all the contents of temp into someFolder, deleted temp, committed and pushed someFolder and it worked! Shows up as someFolder in git.

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

Which @NotNull Java annotation should I use?

There are already too many answers here, but (a) it's 2019, and there's still no "standard" Nullable and (b) no other answer references Kotlin.

The reference to Kotlin is important, because Kotlin is 100% interoperable with Java and it has a core Null Safety feature. When calling Java libraries, it can take advantage of those annotations to let Kotlin tools know if a Java API can accept or return null.

As far as I know, the only Nullable packages compatible with Kotlin are org.jetbrains.annotations and android.support.annotation (now androidx.annotation). The latter is only compatible with Android so it can't be used in non-Android JVM/Java/Kotlin projects. However, the JetBrains package works everywhere.

So if you develop Java packages that should also work in Android and Kotlin (and be supported by Android Studio and IntelliJ), your best choice is probably the JetBrains package.

Maven:

<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations-java5</artifactId>
    <version>15.0</version>
</dependency>

Gradle:

implementation 'org.jetbrains:annotations-java5:15.0'

How to embed a .mov file in HTML?

Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag

Example:

<video controls="controls" width="800" height="600" 
       name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>

This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)

Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)

Adding items in a Listbox with multiple columns

By using the List property.

ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"

Change MySQL root password in phpMyAdmin

Change It like this, It worked for me. Hope It helps. firs I did

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

Then I Changed Like this...

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

Check if a JavaScript string is a URL

A related question with an answer:

Javascript regex URL matching

Or this Regexp from Devshed:

function validURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return !!pattern.test(str);
}

How to save DataFrame directly to Hive?

Sorry writing late to the post but I see no accepted answer.

df.write().saveAsTable will throw AnalysisException and is not HIVE table compatible.

Storing DF as df.write().format("hive") should do the trick!

However, if that doesn't work, then going by the previous comments and answers, this is what is the best solution in my opinion (Open to suggestions though).

Best approach is to explicitly create HIVE table (including PARTITIONED table),

def createHiveTable: Unit ={
spark.sql("CREATE TABLE $hive_table_name($fields) " +
  "PARTITIONED BY ($partition_column String) STORED AS $StorageType")
}

save DF as temp table,

df.createOrReplaceTempView("$tempTableName")

and insert into PARTITIONED HIVE table:

spark.sql("insert into table default.$hive_table_name PARTITION($partition_column) select * from $tempTableName")
spark.sql("select * from default.$hive_table_name").show(1000,false)

Offcourse the LAST COLUMN in DF will be the PARTITION COLUMN so create HIVE table accordingly!

Please comment if it works! or not.


--UPDATE--

df.write()
  .partitionBy("$partition_column")
  .format("hive")
  .mode(SaveMode.append)
  .saveAsTable($new_table_name_to_be_created_in_hive)  //Table should not exist OR should be a PARTITIONED table in HIVE

How to set Java environment path in Ubuntu

You need to set the $JAVA_HOME variable

In my case while setting up Maven, I had to set it up to where JDK is installed.

First find out where JAVA is installed:

$ whereis java

java: /usr/bin/java /usr/share/java /usr/share/man/man1/java.1.gz

Now dig deeper-

$ ls -l /usr/bin/java

lrwxrwxrwx 1 root root 46 Aug 25 2018 /etc/alternatives/java -> /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java Dig deeper:

$ ls -l /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java

-rwxr-xr-x 1 root root 6464 Mar 14 18:28 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java

As it is not being referenced to any other directory, we'll use this.

Open /etc/environment using nano

$ sudo nano /etc/environment

Append the following lines

JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64

export JAVA_HOME

Reload PATH using

$. /etc/environment

Now,

$ echo $JAVA_HOME

Here is your output:

/usr/lib/jvm/java-1.8.0-openjdk-amd64

Sources I referred to:

https://askubuntu.com/a/175519

https://stackoverflow.com/a/23427862/6297483

Excel - Sum column if condition is met by checking other column in same table

SUMIF didn't worked for me, had to use SUMIFS.

=SUMIFS(TableAmount,TableMonth,"January")

TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.

Hope this can help someone!

What represents a double in sql server?

float in SQL Server actually has [edit:almost] the precision of a "double" (in a C# sense).

float is a synonym for float(53). 53 is the bits of the mantissa.

.NET double uses 54 bits for the mantissa.

Deprecated Java HttpClient - How hard can it be?

It got deprecated in version 4.3-alpha1 which you use because of the LATEST version specification. If you take a look at the javadoc of the class, it tells you what to use instead: HttpClientBuilder.

In the latest stable version (4.2.3) the DefaultHttpClient is not deprecated yet.

push multiple elements to array

There are many answers recommend to use: Array.prototype.push(a, b). It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.

typedef fixed length array

From R..'s answer:

However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.

Users who don't see that it's an array will most likely write something like this (which fails):

#include <stdio.h>

typedef int twoInts[2];

void print(twoInts *twoIntsPtr);
void intermediate (twoInts twoIntsAppearsByValue);

int main () {
    twoInts a;
    a[0] = 0;
    a[1] = 1;
    print(&a);
    intermediate(a);
    return 0;
}
void intermediate(twoInts b) {
    print(&b);
}

void print(twoInts *c){
    printf("%d\n%d\n", (*c)[0], (*c)[1]);
}

It will compile with the following warnings:

In function ‘intermediate’:
warning: passing argument 1 of ‘print’ from incompatible pointer type [enabled by default]
    print(&b);
     ^
note: expected ‘int (*)[2]’ but argument is of type ‘int **’
    void print(twoInts *twoIntsPtr);
         ^

And produces the following output:

0
1
-453308976
32767

#pragma mark in Swift?

//# MARK: - Spinner Class Methods

Add a line between the colon and your description to insert a separator line. This helps to organize your code even more. The code and screenshot above make use of the MARK comment with a line included.

  1. //# MARK: – Text Methods (LINE)
  2. //# MARK: Text Methods (NO LINE)

This only works with the MARK comment.

enter image description here

How to see tomcat is running or not

for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running

What is a Python equivalent of PHP's var_dump()?

So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.

def dump(obj):
  '''return a printable representation of an object for debugging'''
  newobj=obj
  if '__dict__' in dir(obj):
    newobj=obj.__dict__
    if ' object at ' in str(obj) and not newobj.has_key('__type__'):
      newobj['__type__']=str(obj)
    for attr in newobj:
      newobj[attr]=dump(newobj[attr])
  return newobj

Here is the usage

class stdClass(object): pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.subObj=stdClass()
obj.subObj.value='foobar'

from pprint import pprint
pprint(dump(obj))

and the results.

{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
 'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
 'int': 1,
 'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
 'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
            'value': 'foobar'},
 'tup': (1, 2, 3, 4)}

DIV height set as percentage of screen?

If you want it based on the screen height, and not the window height:

const height = 0.7 * screen.height

// jQuery
$('.header').height(height)

// Vanilla JS
document.querySelector('.header').style.height = height + 'px'

// If you have multiple <div class="header"> elements
document.querySelectorAll('.header').forEach(function(node) {
  node.style.height = height + 'px'
})

HTML img onclick Javascript

I think your error was in calling the function.

In your HTML code, onclick is calling the image() function. However, in your script the function is named imgWindow(). Try changing the onclick to imgWindow().

I don't do much JavaScript so if I have missed something, please let me know.

Good Luck!

C#: easiest way to populate a ListBox from a List

This also could be easiest way to add items in ListBox.

for (int i = 0; i < MyList.Count; i++)
{
        listBox1.Items.Add(MyList.ElementAt(i));
}

Further improvisation of this code can add items at runtime.

How do I print an IFrame from javascript in Safari/Chrome

Put a print function in the iframe and call it from the parent.

iframe:

function printMe() {
  window.print()
}

parent:

document.frame1.printMe()

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

initialize mysql before start on windows.

mysqld --initialize

Open window in JavaScript with HTML inserted

When you create a new window using open, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document object.

Here is an example:

var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');

Inner join of DataTables in C#

If you are allowed to use LINQ, take a look at the following example. It creates two DataTables with integer columns, fills them with some records, join them using LINQ query and outputs them to Console.

    DataTable dt1 = new DataTable();
    dt1.Columns.Add("CustID", typeof(int));
    dt1.Columns.Add("ColX", typeof(int));
    dt1.Columns.Add("ColY", typeof(int));

    DataTable dt2 = new DataTable();
    dt2.Columns.Add("CustID", typeof(int));
    dt2.Columns.Add("ColZ", typeof(int));

    for (int i = 1; i <= 5; i++)
    {
        DataRow row = dt1.NewRow();
        row["CustID"] = i;
        row["ColX"] = 10 + i;
        row["ColY"] = 20 + i;
        dt1.Rows.Add(row);

        row = dt2.NewRow();
        row["CustID"] = i;
        row["ColZ"] = 30 + i;
        dt2.Rows.Add(row);
    }

    var results = from table1 in dt1.AsEnumerable()
                 join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"]
                 select new
                 {
                     CustID = (int)table1["CustID"],
                     ColX = (int)table1["ColX"],
                     ColY = (int)table1["ColY"],
                     ColZ = (int)table2["ColZ"]
                 };
    foreach (var item in results)
    {
        Console.WriteLine(String.Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ));
    }
    Console.ReadLine();

// Output:
// ID = 1, ColX = 11, ColY = 21, ColZ = 31
// ID = 2, ColX = 12, ColY = 22, ColZ = 32
// ID = 3, ColX = 13, ColY = 23, ColZ = 33
// ID = 4, ColX = 14, ColY = 24, ColZ = 34
// ID = 5, ColX = 15, ColY = 25, ColZ = 35

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

How about playing with these two properties?

disableClose: boolean - Whether the user can use escape or clicking on the backdrop to close the modal.

hasBackdrop: boolean - Whether the dialog has a backdrop.

https://material.angular.io/components/dialog/api

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

Turn on torch/flash on iPhone

Swift 2.0 version:

func setTorchLevel(torchLevel: Float)
{
    self.captureSession?.beginConfiguration()
    defer {
        self.captureSession?.commitConfiguration()
    }

    if let device = backCamera?.device where device.hasTorch && device.torchAvailable {
        do {
            try device.lockForConfiguration()
            defer {
                device.unlockForConfiguration()
            }

            if torchLevel <= 0.0 {
                device.torchMode = .Off
            }
            else if torchLevel >= 1.0 {
                try device.setTorchModeOnWithLevel(min(torchLevel, AVCaptureMaxAvailableTorchLevel))
            }
        }
        catch let error {
            print("Failed to set up torch level with error \(error)")
            return
        }
    }
}

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

Printing 1 to 1000 without loop or conditionals

We can launch 1000 threads, each printing one of the numbers. Install OpenMPI, compile using mpicxx -o 1000 1000.cpp and run using mpirun -np 1000 ./1000. You will probably need to increase your descriptor limit using limit or ulimit. Note that this will be rather slow, unless you have loads of cores!

#include <cstdio>
#include <mpi.h>
using namespace std;

int main(int argc, char **argv) {
  MPI::Init(argc, argv);
  cout << MPI::COMM_WORLD.Get_rank() + 1 << endl;
  MPI::Finalize();
}

Of course, the numbers won't necessarily be printed in order, but the question doesn't require them to be ordered.

How to insert an element after another element in JavaScript without using a library?

I know this question has far too many answers already, but none of them met my exact requirements.

I wanted a function that has the exact opposite behavior of parentNode.insertBefore - that is, it must accept a null referenceNode (which the accepted answer does not) and where insertBefore would insert at the end of the children this one must insert at the start, since otherwise there'd be no way to insert at the start location with this function at all; the same reason insertBefore inserts at the end.

Since a null referenceNode requires you to locate the parent, we need to know the parent - insertBefore is a method of the parentNode, so it has access to the parent that way; our function doesn't, so we'll need to pass the parent as a parameter.

The resulting function looks like this:

function insertAfter(parentNode, newNode, referenceNode) {
  parentNode.insertBefore(
    newNode,
    referenceNode ? referenceNode.nextSibling : parentNode.firstChild
  );
}

Or (if you must, I don't recommend it) you can of course enhance the Node prototype:

if (! Node.prototype.insertAfter) {
  Node.prototype.insertAfter = function(newNode, referenceNode) {
    this.insertBefore(
      newNode,
      referenceNode ? referenceNode.nextSibling : this.firstChild
    );
  };
}

Jquery click event not working after append method

This problem could be solved as mentioned using the .on on jQuery 1.7+ versions.

Unfortunately, this didn't work within my code (and I have 1.11) so I used:

$('body').delegate('.logout-link','click',function() {

http://api.jquery.com/delegate/

As of jQuery 3.0, .delegate() has been deprecated. It was superseded by the .on() method since jQuery 1.7, so its use was already discouraged. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method. In general, these are the equivalent templates for the two methods:

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

This comment might help others :) !

How to check empty DataTable

Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.

if (DetailTable != null && DetailTable.Rows.Count>0)

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Using different Web.config in development and production environment

You can also use the extension "Configuration Transform" works the same as "SlowCheetah",

How can I replace every occurrence of a String in a file with PowerShell?

Small correction for the Set-Content command. If the searched string is not found the Set-Content command will blank (empty) the target file.

You can first verify if the string you are looking for exist or not. If not it will not replace anything.

If (select-string -path "c:\Windows\System32\drivers\etc\hosts" -pattern "String to look for") `
    {(Get-Content c:\Windows\System32\drivers\etc\hosts).replace('String to look for', 'String to replace with') | Set-Content c:\Windows\System32\drivers\etc\hosts}
    Else{"Nothing happened"}

How do you run your own code alongside Tkinter's event loop?

When writing your own loop, as in the simulation (I assume), you need to call the update function which does what the mainloop does: updates the window with your changes, but you do it in your loop.

def task():
   # do something
   root.update()

while 1:
   task()  

How to use the priority queue STL for objects?

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

Is there an operator to calculate percentage in Python?

Very quickly and sortly-code implementation by using the lambda operator.

In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
In [18]: percent(5,400)
Out[18]: 20.0
In [19]: percent(5,435)
Out[19]: 21.75

Determine if char is a num or letter

<ctype.h> includes a range of functions for determining if a char represents a letter or a number, such as isalpha, isdigit and isalnum.

The reason why int a = (int)theChar won't do what you want is because a will simply hold the integer value that represents a specific character. For example the ASCII number for '9' is 57, and for 'a' it's 97.

Also for ASCII:

  • Numeric - if (theChar >= '0' && theChar <= '9')
  • Alphabetic -
    if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')

Take a look at an ASCII table to see for yourself.

How to output MySQL query results in CSV format?

If you are getting this error while you try to export your file

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

and you are not able to solve this error. You can do one thing by simply running this python script

import mysql.connector
import csv

con = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="Your Password"
)

cur = con.cursor()

cur.execute("USE DbName")
cur.execute("""
select col1,col2 from table
where <cond>
""")

with open('Filename.csv',mode='w') as data:
    fieldnames=["Field1","Field2"]
    writer=csv.DictWriter(data,fieldnames=fieldnames)
    writer.writeheader()
    for i in cur:
        writer.writerow({'Field1':i[0],'Field2':i[1]})

How to pass data to all views in Laravel 5?

Inside your config folder you can create a php file name it for example "variable.php" with content below:

<?php

  return [
    'versionNumber' => '122231',
  ];

Now inside all the views you can use it like

config('variable.versionNumber')

Make Frequency Histogram for Factor Variables

Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country

barplot(summary(df$Country))

Tensorflow import error: No module named 'tensorflow'

In Windows 64, if you did this sequence correctly:

Anaconda prompt:

conda create -n tensorflow python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow

Be sure you still are in tensorflow environment. The best way to make Spyder recognize your tensorflow environment is to do this:

conda install spyder

This will install a new instance of Spyder inside Tensorflow environment. Then you must install scipy, matplotlib, pandas, sklearn and other libraries. Also works for OpenCV.

Always prefer to install these libraries with "conda install" instead of "pip".

Can I convert long to int?

Just do (int)myLongValue. It'll do exactly what you want (discarding MSBs and taking LSBs) in unchecked context (which is the compiler default). It'll throw OverflowException in checked context if the value doesn't fit in an int:

int myIntValue = unchecked((int)myLongValue);

How to set image on QPushButton?

Just use this code

QPixmap pixmap("path_to_icon");
QIcon iconBack(pixmap);

Note that:"path_to_icon" is the path of image icon in file .qrc of your project You can find how to add .qrc file here