Programs & Examples On #Web inf

WEB-INF is the name of a folder found in Java web applications. It is used to store deployment information such as the web.xml, required library files and compiled class files. It is normally not accessible from web. Any files which you want to put on war but do not want to make to public then web-inf is the place where you can keep those files.

What is WEB-INF used for in a Java EE web application?

This convention is followed for security reasons. For example if unauthorized person is allowed to access root JSP file directly from URL then they can navigate through whole application without any authentication and they can access all the secured data.

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Using Xcode 4.2 on Snow Leopard, I used the following settings to build an app that worked on both armv6 (Iphone 3G and lower) AND armv7 (everything newer than 3G including 3GS).

architectures: armv6 and armv7 (removed $(ARCHS_STANDARD_32_BIT))
build active architecture only: no
required device capabilities: armv6

do not put armv7 in required device capabilities if you want the app to run on 3G and lower as well.

jQuery see if any or no checkboxes are selected

Rahul's answer is best fit for your question. Anyway, if you have a group of checkboxes to be checked and not all the checkbox in your form, you can go for it.

Put a classname for all the checkboxes you want to check, say for example, a classname test_check and now you can check if any of the checkbox is checked belonging to the group by:

$("#formID .test_check:checked").length > 0

If it returns true, assume that one or more checkboxes are checked having the classname test_check and none checked if returns false.

Hope it helps someone. Thanks :)-

filter out multiple criteria using excel vba

Alternative using VBA's Filter function

As an innovative alternative to @schlebe 's recent answer, I tried to use the Filter function integrated in VBA, which allows to filter out a given search string setting the third argument to False. All "negative" search strings (e.g. A, B, C) are defined in an array. I read the criteria in column A to a datafield array and basicly execute a subsequent filtering (A - C) to filter these items out.

Code

Sub FilterOut()
Dim ws  As Worksheet
Dim rng As Range, i As Integer, n As Long, v As Variant
' 1) define strings to be filtered out in array
  Dim a()                    ' declare as array
  a = Array("A", "B", "C")   ' << filter out values
' 2) define your sheetname and range (e.g. criteria in column A)
  Set ws = ThisWorkbook.Worksheets("FilterOut")
  n = ws.Range("A" & ws.Rows.Count).End(xlUp).row
  Set rng = ws.Range("A2:A" & n)
' 3) hide complete range rows temporarily
  rng.EntireRow.Hidden = True
' 4) set range to a variant 2-dim datafield array
  v = rng
' 5) code array items by appending row numbers
  For i = 1 To UBound(v): v(i, 1) = v(i, 1) & "#" & i + 1: Next i
' 6) transform to 1-dim array and FILTER OUT the first search string, e.g. "A"
  v = Filter(Application.Transpose(Application.Index(v, 0, 1)), a(0), False, False)
' 7) filter out each subsequent search string, i.e. "B" and "C"
  For i = 1 To UBound(a): v = Filter(v, a(i), False, False): Next i
' 8) get coded row numbers via split function and unhide valid rows
  For i = LBound(v) To UBound(v)
      ws.Range("A" & Split(v(i) & "#", "#")(1)).EntireRow.Hidden = False
  Next i
End Sub

Flexbox Not Centering Vertically in IE

Here is my working solution (SCSS):

.item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 120px;
  &:after{
    content:'';
    min-height:inherit;
    font-size:0;
  }
}

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Simply use Window.Maximize() command

WebDriver driver= new ChromeDriver()
driver.Manage().Window.Maximize();  

What does getActivity() mean?

I to had a similar doubt what I got to know was getActivity() returns the Activity to which the fragment is associated.

The getActivity() method is used generally in static fragment as the associated activity will not be static and non static member cannot be used in static member.

I used <code>getActivity()</code> here to get non-static activity to which the the placeholder fragment is associated.

How to manually include external aar package using new Gradle Android Build System

Currently referencing a local .aar file is not supported (as confirmed by Xavier Ducrochet)

What you can do instead is set up a local Maven repository (much more simple than it sounds) and reference the .aar from there.

I've written a blogpost detailing how to get it working here:

http://www.flexlabs.org/2013/06/using-local-aar-android-library-packages-in-gradle-builds

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

The error is because there is some non-ascii character in the dictionary and it can't be encoded/decoded. One simple way to avoid this error is to encode such strings with encode() function as follows (if a is the string with non-ascii character):

a.encode('utf-8').strip()

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I've updated com.google.gms:google-services from 3.1.1 to 3.2.0 and the warning stopped appearing.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

    classpath 'com.google.gms:google-services:3.2.0'
    }
}

What exactly does big ? notation represent?

First of All Theory

  1. Big O = Upper Limit O(n)

  2. Theta = Order Function - theta(n)

  3. Omega = Q-Notation(Lower Limit) Q(n)

Why People Are so Confused?

In many Blogs & Books How this Statement is emphasised is Like

"This is Big O(n^3)" etc.

and people often Confuse like weather

O(n) == theta(n) == Q(n)

But What Worth keeping in mind is They Are Just Mathematical Function With Names O, Theta & Omega

so they have same General Formula of Polynomial,

Let,

f(n) = 2n4 + 100n2 + 10n + 50 then,

g(n) = n4, So g(n) is Function which Take function as Input and returns Variable with Biggerst Power,

Same f(n) & g(n) for Below all explainations

Big O - Function (Provides Upper Bound)

Big O(n4) = 3n4, Because 3n4 > 2n4

3n4 is value of Big O(n4) Just like f(x) = 3x

n4 is playing a role of x here so,

Replacing n4 with x'so, Big O(x') = 2x', Now we both are happy General Concept is

So 0 = f(n) = O(x')

O(x') = cg(n) = 3n4

Putting Value,

0 = 2n4 + 100n2 + 10n + 50 = 3n4

3n4 is our Upper Bound

Theta(n) Provides Lower Bound

Theta(n4) = cg(n) = 2n4 Because 2n4 = Our Example f(n)

2n4 is Value of Theta(n4)

so, 0 = cg(n) = f(n)

0 = 2n4 = 2n4 + 100n2 + 10n + 50

2n4 is our Lower Bound

Omega n - Order Function

This is Calculated to find out that weather lower Bound is similar to Upper bound,

Case 1). Upper Bound is Similar to Lower Bound

if Upper Bound is Similar to Lower Bound, The Average Case is Similar

Example, 2n4 = f(x) = 2n4,
Then Omega(n) = 2n4

Case 2). if Upper Bound is not Similar to Lower Bound

in this case, Omega(n) is Not fixed but Omega(n) is the set of functions with the same order of growth as g(n).

Example 2n4 = f(x) = 3n4, This is Our Default Case,
Then, Omega(n) = c'n4, is a set of functions with 2 = c' = 3

Hope This Explained!!

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

Formatting floats without trailing zeros

You can achieve that in most pythonic way like that:

python3:

"{:0.0f}".format(num)

adb command not found in linux environment

I had the same issue on my fresh Ubuntu 64 bit installation, and the path was set up correctly.

Thus, which adb would resolve correctly, but trying to run it would fail with adb: command not found.

The very helpful guys at #android-dev pointed me to the solution, namely that the 32 bit libraries hadn't been installed. On my previous computers, this had probably been pulled in as a dependency for another package.

On Ubuntu (probably other Debians as well), running [sudo] apt-get install ia32-libs

java.security.AccessControlException: Access denied (java.io.FilePermission

Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy file (path is as in the reply of Petey B)

permission java.io.FilePermission "your folder path", "write"

In your case it would be

permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"

Here /- means any files or sub-folders inside this folder.

Warning: But by doing this, you are inviting some security risk.

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Link to download apache http server for 64bit windows.

Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers http://www.anindya.com/apache-http-server-2-4-2-x86-and-x64-windows-installers/

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

git clone through ssh

Git 101:

git is a decentralized version control system. You do not necessary need a server to get up and running with git. Still you might want to do that as it looks cool, right? (It's also useful if you want to work on a single project from multiple computers.)

So to get a "server" running you need to run git init --bare <your_project>.git as this will create an empty repository, which you can then import on your machines without having to muck around in config files in your .git dir.

After this you could clone the repo on your clients as it is supposed to work, but I found that some clients (namely git-gui) will fail to clone a repo that is completely empty. To work around this you need to run cd <your_project>.git && touch <some_random_file> && git add <some_random_file> && git commit && git push origin master. (Note that you might need to configure your username and email for that machine's git if you hadn't done so in the past. The actual commands to run will be in the error message you get so I'll just omit them.)

So at this point you can clone the repository to any machine simply by running git clone <user>@<server>:<relative_path><your_project>.git. (As others have pointed out you might need to prefix it with ssh:// if you use the absolute path.) This assumes that you can already log in from your client to the server. (You'll also get bonus points for setting up a config file and keys for ssh, if you intend to push a lot of stuff to the remote server.)

Some relevant links:
This pretty much tells you what you need to know.
And this is for those who know the basic workings of git but sometimes forget the exact syntax.

What's the difference between git reset --mixed, --soft, and --hard?

I’m not a git expert and just arrived on this forum to understand it! Thus maybe my explanation is not perfect, sorry for that. I found all the other answer helpful and I will just try to give another perspective. I will modify a bit the question since I guess that it was maybe the intent of the author: “I’m new to git. Before using git, I was renaming my files like this: main.c, main_1.c, main_2.c when i was performing majors changes in order to be able to go back in case of trouble. Thus, if I decided to come back to main_1.c, it was easy and I also keep main_2.c and main_3.c since I could also need them later. How can I easily do the same thing using git?” For my answer, I mainly use the “regret number three” of the great answer of Matt above because I also think that the initial question is about “what do I do if I have regret when using git?”. At the beginning, the situation is like that:

A-B-C-D (master)

  1. The first main point is to create a new branch: git branch mynewbranch. Then one get:

A-B-C-D (master and mynewbranch)

  1. Let’s suppose now that one want to come back to A (3 commits before). The second main point is to use the command git reset --hard even if one can read on the net that it is dangerous. Yes, it’s dangerous but only for uncommitted changes. Thus, the way to do is:

Git reset --hard thenumberofthecommitA

or

Git reset --hard master~3

Then one obtains: A (master) – B – C – D (mynewbranch)

Then, it’s possible to continue working and commit from A (master) but still can get an easy access to the other versions by checking out on the other branch: git checkout mynewbranch. Now, let’s imagine that one forgot to create a new branch before the command git reset --hard. Is the commit B, C, D are lost? No, but there are not stored in any branches. To find them again, one may use the command : git reflog that is consider as “a safety command”( “in case of trouble, keep calm and use git reflog”). This command will list all commits even those that not belong to any branches. Thus, it’s a convenient way to find the commit B, C or D.

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

  • pyenv - manages different python versions,
  • all others - create virtual environment (which has isolated python version and installed "requirements"),

pipenv want combine all, in addition to previous it installs "requirements" (into the active virtual environment or create its own if none is active)

So maybe you will be happy with pipenv only.

But I use: pyenv + pyenv-virtualenvwrapper, + pipenv (pipenv for installing requirements only).

In Debian:

  1. apt install libffi-dev

  2. install pyenv based on https://www.tecmint.com/pyenv-install-and-manage-multiple-python-versions-in-linux/, but..

  3. .. but instead of pyenv-virtualenv install pyenv-virtualenvwrapper (which can be standalone library or pyenv plugin, here the 2nd option):

    pyenv install 3.9.0

    git clone https://github.com/pyenv/pyenv-virtualenvwrapper.git $(pyenv root)/plugins/pyenv-virtualenvwrapper

    into ~/.bashrc add: export $VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"

    source ~/.bashrc

    pyenv virtualenvwrapper

Then create virtual environments for your projects (workingdir must exist):

pyenv local 3.9.0  # to prevent 'interpreter not found' in mkvirtualenv
python -m pip install --upgrade pip setuptools wheel
mkvirtualenv <venvname> -p python3.9 -a <workingdir>

and switch between projects:

workon <venvname>
python -m pip install --upgrade pip setuptools wheel pipenv

Inside a project I have the file requirements.txt, without fixing the versions inside (if some version limitation is not neccessary). You have 2 possible tools to install them into the current virtual environment: pip-tools or pipenv. Lets say you will use pipenv:

pipenv install -r requirements.txt

this will create Pipfile and Pipfile.lock files, fixed versions are in the 2nd one. If you want reinstall somewhere exactly same versions then (Pipfile.lock must be present):

pipenv install

Remember that Pipfile.lock is related to some Python version and need to be recreated if you use a different one.

As you see I write requirements.txt. This has some problems: You must remove a removed package from Pipfile too. So writing Pipfile directly is probably better.

So you can see I use pipenv very poorly. Maybe if you will use it well, it can replace everything?

EDIT 2021.01: I have changed my stack to: pyenv + pyenv-virtualenvwrapper + poetry. Ie. I use no apt or pip installation of virtualenv or virtualenvwrapper, and instead I install pyenv's plugin pyenv-virtualenvwrapper. This is easier way.

Poetry is great for me:

poetry add <package>   # install single package
poetry remove <package>
poetry install   # if you remove poetry.lock poetry will re-calculate versions

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

How to delete an element from an array in C#

' To remove items from string based on Dictionary key values. ' VB.net code

 Dim stringArr As String() = "file1,file2,file3,file4,file5,file6".Split(","c)
 Dim test As Dictionary(Of String, String) = New Dictionary(Of String, String)
 test.Add("file3", "description")
 test.Add("file5", "description")
 stringArr = stringArr.Except(test.Keys).ToArray()

How to Remove the last char of String in C#?

newString = yourString.Substring(0, yourString.length -1);

Deleting array elements in JavaScript - delete vs splice

delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined

Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.

> myArray[0]
  undefined
> myArray
  [empty, "b", "c", "d"]

myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

less than 10 add 0 to number

Here is Genaric function for add any number of leading zeros for making any size of numeric string.

function add_zero(your_number, length) {
    var num = '' + your_number;
    while (num.length < length) {
        num = '0' + num;
    }
    return num;
}

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

Set Option  Value
textsize    2147483647
language    us_english
dateformat  mdy
datefirst   7
lock_timeout    -1
quoted_identifier   SET
arithabort  SET
ansi_null_dflt_on   SET
ansi_warnings   SET
ansi_padding    SET
ansi_nulls  SET
concat_null_yields_null SET
isolation level read committed

Losing Session State

Your session is lost becoz....

I have found a scenario where session is lost - In a asp.net page, for a amount text box field has invalid characters, and followed by a session variable retrieval for other purpose.After posting the invalid number parsing through Convert.ToInt32 or double raises a first chance exception, but error does not show at that line, Instead of that, Session being null because of unhandled exception, shows error at session retrieval, thus deceiving the debugging...

HINT: Test your system to fail it- DESTRUCTIVE.. enter enough junk in unrelated scenarios for ex: after search results shown enter junk in search criteria and goto details of search result... , you would be able to reproduce this machine on your local code base too...:)

Hope it Helps, hydtechie

What is the bower (and npm) version syntax?

In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~ or other syntax details) at semver.org.

There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.

SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:

Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.

So, your specific question about ~ relates to that Major.Minor.Patch schema. (As does the related caret operator ^.) You can use ~ to narrow the range of versions you're willing to accept to either:

  • subsequent patch-level changes to the same minor version ("bug fixes not affecting the API"), or:
  • subsequent minor-level changes to the same major version ("backwards compatible API additions/changes")

For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:

"angular": "~1.2"
  or:
"angular": "~1.2.0"

This also gets you the same results as using the .x syntax:

"angular": "1.2.x"

But, you can use the tilde/~ syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:

"angular": "~1.2.4"

Moving left, towards the major version, if you use...

"angular": "~1"

... it's the same as...

"angular": "1.x"
  or:
"angular": "^1.0.0"

...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:

Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!

Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1, a caret range such as ^1.2.3 lets you say you'll take any changes >=1.2.3 && <2.0.0. You couldn't do that with a tilde range.

That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.

It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x syntax: they simply let you do more. That's why you'll see the tilde used often even where .x would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0 format, rather than the 2.4.x format it could use. By sticking to ~, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.

Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.


RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||. Like so:

"angular": "1.2 <= 1.2.9 || >2.0.0"

Vue 2 - Mutating props vue-warn

According to the VueJs 2.0, you should not mutate a prop inside the component. They are only mutated by their parents. Therefore, you should define variables in data with different names and keep them updated by watching actual props. In case the list prop is changed by a parent, you can parse it and assign it to mutableList. Here is a complete solution.

Vue.component('task', {
    template: ´<ul>
                  <li v-for="item in mutableList">
                      {{item.name}}
                  </li>
              </ul>´,
    props: ['list'],
    data: function () {
        return {
            mutableList = JSON.parse(this.list);
        }
    },
    watch:{
        list: function(){
            this.mutableList = JSON.parse(this.list);
        }
    }
});

It uses mutableList to render your template, thus you keep your list prop safe in the component.

Pass multiple values with onClick in HTML link

A few things here...

If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.

Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.

Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...

<a href=# onclick="ReAssign('valuationId', window.user)">Re-Assign</a>

There are a few extra things to note here, if you want more than a quick solution.

You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).

Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:

.runjs {
    cursor: pointer;
    text-decoration: underline;
    color: blue;
}

This lets you leave out the href attribute which you weren't using anyways.

Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...

var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
    links[i].onclick = function() { ReAssign('valuationId', window.user); };

While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.

File Upload without Form

Step 1: Create HTML Page where to place the HTML Code.

Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.

Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax Code url apply which one on your php file name.

JS

//$(document).on("change", "#avatar", function() {   // If you want to upload without a submit button 
$(document).on("click", "#upload", function() {
  var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
  var form_data = new FormData(); // Creating object of FormData class
  form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
  form_data.append("user_id", 123) // Adding extra parameters to form_data
  $.ajax({
    url: "/upload_avatar", // Upload Script
    dataType: 'script',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data, // Setting the data attribute of ajax with file_data
    type: 'post',
    success: function(data) {
      // Do something after Ajax completes 
    }
  });
});

HTML

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

Php

print_r($_FILES);
print_r($_POST);

Find methods calls in Eclipse project

Go to the method in X.java, and select Open Call Hierarchy from the context menu.

React fetch data in server before render

I've just stumbled upon this problem too, learning React, and solved it by showing spinner until the data is ready.

    render() {
    if (this.state.data === null) {
        return (
            <div className="MyView">
                <Spinner/>
            </div>
        );
    }
    else {
        return(
            <div className="MyView">
                <ReactJson src={this.state.data}/>
            </div>
        );
    }
}

How can I make IntelliJ IDEA update my dependencies from Maven?

in IntelliJ 2020 in the pom.xml view one should be able to apply pom changes by following key combination: CTRG + SHIFT + O.

And as correctly commented before - IntelliJ additionally shows a balloon widget to import changes.

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

The accepted answer to set git config core.filemode false, works, but with consequences. Setting core.filemode to false tells git to ignore any executable bit changes on the filesystem so it won't view this as a change. If you do need to stage an executable bit change for this repository anytime in the future, you would have to do it manually, or set core.filemode back to true.

A less consequential alternative, if all the modified files should have mode 100755, is to do something like

chmod 100755 $(git ls-files --modified)

which just does exactly the change in mode, no more, no less, without additional implications.

(in my case, it was due to a OneDrive sync with my filesystem on MacOS; by not changing core.filemode, I'm leaving the possibility open that the mode change might happen again in the future; in my case, I'd like to know if it happens again, and changing core.filemode will hide it from me, which I don't want)

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

How to read a large file line by line?

I would strongly recommend not using the default file loading as it is horrendously slow. You should look into the numpy functions and the IOpro functions (e.g. numpy.loadtxt()).

http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html

https://store.continuum.io/cshop/iopro/

Then you can break your pairwise operation into chunks:

import numpy as np
import math

lines_total = n    
similarity = np.zeros(n,n)
lines_per_chunk = m
n_chunks = math.ceil(float(n)/m)
for i in xrange(n_chunks):
    for j in xrange(n_chunks):
        chunk_i = (function of your choice to read lines i*lines_per_chunk to (i+1)*lines_per_chunk)
        chunk_j = (function of your choice to read lines j*lines_per_chunk to (j+1)*lines_per_chunk)
        similarity[i*lines_per_chunk:(i+1)*lines_per_chunk,
                   j*lines_per_chunk:(j+1)*lines_per_chunk] = fast_operation(chunk_i, chunk_j) 

It's almost always much faster to load data in chunks and then do matrix operations on it than to do it element by element!!

How to get first two characters of a string in oracle query?

Try select substr(orderno, 1,2) from shipment;

`IF` statement with 3 possible answers each based on 3 different ranges

You need to use the AND function for the multiple conditions:

=IF(AND(A2>=75, A2<=79),0.255,IF(AND(A2>=80, X2<=84),0.327,IF(A2>=85,0.559,0)))

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

problem with php mail 'From' header

The web host is not really playing foul. It's not strictly according to the rules - but compared with some some of the amazing inventions intended to prevent spam, its not a particularly bad one.

If you really do want to send mail from '@gmail.com' why not just use the gmail SMTP service? If you can't reconfigure the server where PHP is running, then there are lots of email wrapper tools out there which allow you to specify a custom SMTP relay phpmailer springs to mind.

C.

How do I check if an element is really visible with JavaScript?

Catch mouse-drag and viewport events (onmouseup, onresize, onscroll).

When a drag ends do a comparison of the dragged item boundary with all "elements of interest" (ie, elements with class "dont_hide" or an array of ids). Do the same with window.onscroll and window.onresize. Mark any elements hidden with a special attribute or classname or simply perform whatever action you want then and there.

The hidden tests are pretty easy. For "totally hidden" you want to know if ALL corners are either inside the dragged-item boundary or outside the viewport. For partially hidden you're looking for a single corner matching the same test.

Return the most recent record from ElasticSearch index

I used @timestamp instead of _timestamp

{
    'size' : 1,
    'query': {
        'match_all' : {}
            },
    "sort" : [{"@timestamp":{"order": "desc"}}]
}

Iterating over and deleting from Hashtable in Java

So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:

 table.delete(key);
 for (K key: table.keySet()) {
    // do whatever you need to do with the rest of the keys
 }

How to add "active" class to Html.ActionLink in ASP.NET MVC

I realized that this problem was a common problem for some of us, so I published my own solution using nuget package. Below you can see how it works. I hope that will be useful.

Note:This nuget package is my first package. So if you see a mistake, please give feedback. Thank you.

  1. Install Package or download source code and add your Project

    -Install-Package Betalgo.MvcMenuNavigator
    
  2. Add your pages to an enum

    public enum HeaderTop
    {
        Dashboard,
        Product
    }
    public enum HeaderSub
    {
        Index
    }
    
  3. Put Filter to top of your Controllor or Action

    [MenuNavigator(HeaderTop.Product, HeaderSub.Index)]
    public class ProductsController : Controller
    {
        public async Task<ActionResult> Index()
        {
            return View();
        }
    
        [MenuNavigator(HeaderTop.Dashboard, HeaderSub.Index)]
        public async Task<ActionResult> Dashboard()
        {
            return View();
        }
    }
    
  4. And use it In your header layout like this

    @{
    var headerTop = (HeaderTop?)MenuNavigatorPageDataNavigatorPageData.HeaderTop;
    var headerSub = (HeaderSub?)MenuNavigatorPageDataNavigatorPageData.HeaderSub;
    }
    <div class="nav-collapse collapse navbar-collapse navbar-responsive-collapse">
    <ul class="nav navbar-nav">
        <li class="@(headerTop==HeaderTop.Dashboard?"active selected open":"")">
            <a href="@Url.Action("Index","Home")">Dashboard</a>
        </li>
        <li class="@(headerTop==HeaderTop.Product?"active selected open":"")">
            <a href="@Url.Action("Index", "Products")">Products</a>
        </li>
    </ul>
    

More Info: https://github.com/betalgo/MvcMenuNavigator

How do I convert a Python 3 byte-string variable into a regular string?

Call decode() on a bytes instance to get the text which it encodes.

str = bytes.decode()

How to make 'submit' button disabled?

in Angular 2.x.x , 4, 5 ...

<form #loginForm="ngForm">
    <input type="text" required> 
    <button  type="submit"  [disabled]="loginForm.form.invalid">Submit</button>
</form>

Pandas DataFrame to List of Dictionaries

Use df.to_dict('records') -- gives the output without having to transpose externally.

In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

While you can't yet get Firefox to remove the dropdown arrow (see MatTheCat's post), you can hide your "stylized" background image from showing in Firefox.

-moz-background-position: -9999px -9999px!important;

This will position it out of frame, leaving you with the default select box arrow – while keeping the stylized version in Webkit.

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

You can create user with no password in phpmyadmin and it solves the problem! Lebbar Abdelhadi,

How to compare two floating point numbers in Bash?

Using bashj (https://sourceforge.net/projects/bashj/ ), a bash mutant with java support, you just write (and it IS easy to read):

#!/usr/bin/bashj

#!java
static int doubleCompare(double a,double b) {return((a>b) ? 1 : (a<b) ? -1 : 0);}

#!bashj
num1=3.17648e-22
num2=1.5
comp=j.doubleCompare($num1,$num2)
if [ $comp == 0 ] ; then echo "Equal" ; fi
if [ $comp == 1 ] ; then echo "$num1 > $num2" ; fi
if [ $comp == -1 ] ; then echo "$num2 > $num1" ; fi

Of course bashj bash/java hybridation offers much more...

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

The javascript library sugar.js (http://sugarjs.com/) has functions to format dates

Example:

Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')

How to get jSON response into variable from a jquery script

Your PHP array is defined as:

$arr = array ('resonse'=>'error','comment'=>'test comment here');

Notice the mispelling "resonse". Also, as RaYell has mentioned, you have to use data instead of json in your success function because its parameter is currently data.

Try editing your PHP file to change the spelling form resonse to response. It should work then.

How to compare only date in moment.js

Meanwhile you can use the isSameOrAfter method:

moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');

Docs: https://momentjs.com/docs/#/query/is-same-or-after/

System.Security.SecurityException when writing to Event Log

I hit similar issue - in my case Source contained <, > characters. 64 bit machines are using new even log - xml base I would say and these characters (set from string) create invalid xml which causes exception. Arguably this should be consider Microsoft issue - not handling the Source (name/string) correctly.

Undo scaffolding in Rails

So, Process you should follow to undo scaffolding in rails 4. Run Command as below:

  1. rails d scaffold FooBar
  2. rake db:rollback if you_had_run_rake db:migrate after creating above scaffold?

That's it!

Cheers!

Set Canvas size using javascript

Try this:

var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

How to detect string which contains only spaces?

Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.

if (!str.trim().length) {
  console.log('str is empty!');
}

You can read more about trim here.

EXEC sp_executesql with multiple parameters

Here is a simple example:

EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;

Your call will be something like this

EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID

Play/pause HTML 5 video using JQuery

This is how I managed to make it work:

jQuery( document ).ready(function($) {
    $('.myHTMLvideo').click(function() {
        this.paused ? this.play() : this.pause();
    });
});

All my HTML5 tags have the class 'myHTMLvideo'

Python sys.argv lists and indexes

let's say on the command-line you have:

C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John

to make it easier to read, let's just shorten this to:

C:\> hello.py John

argv represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1

in other words, sys.argv[0] == 'hello.py' and sys.argv[1] == 'John' ... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.

len(sys.argv) >= 2 just checks whether you entered at least two elements. in this case, we entered exactly 2.

now let's translate your code into English:

define main() function:
    if there are at least 2 elements on the cmd-line:
        set 'name' to the second element located at index 1, e.g., John
    otherwise there is only 1 element... the program name, e.g., hello.py:
        set 'name' to "World" (since we did not get any useful user input)
    display 'Hello' followed by whatever i assigned to 'name'

so what does this mean? it means that if you enter:

  • "hello.py", the code outputs "Hello World" because you didn't give a name
  • "hello.py John", the code outputs "Hello John" because you did
  • "hello.py John Paul", the code still outputs "Hello John" because it does not save nor use sys.argv[2], which was "Paul" -- can you see in this case that len(sys.argv) == 3 because there are 3 elements in the sys.argv list?

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

Show two digits after decimal point in c++

It is possible to print a 15 decimal number in C++ using the following:

#include <iomanip>
#include <iostream>

cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();

return 0;

Do a "git export" (like "svn export")?

If you want something that works with submodules this might be worth a go.

Note:

  • MASTER_DIR = a checkout with your submodules checked out also
  • DEST_DIR = where this export will end up
  • If you have rsync, I think you'd be able to do the same thing with even less ball ache.

Assumptions:

  • You need to run this from the parent directory of MASTER_DIR ( i.e from MASTER_DIR cd .. )
  • DEST_DIR is assumed to have been created. This is pretty easy to modify to include the creation of a DEST_DIR if you wanted to

cd MASTER_DIR && tar -zcvf ../DEST_DIR/export.tar.gz --exclude='.git*' . && cd ../DEST_DIR/ && tar xvfz export.tar.gz && rm export.tar.gz

How to add external library in IntelliJ IDEA?

A better way in long run is to integrate Gradle in your project environment. Its a build tool for Java, and now being used a lot in the android development space.

You will need to make a .gradle file and list your library dependencies. Then, all you would need to do is import the project in IntelliJ using Gradle.

Cheers

Removing the fragment identifier from AngularJS urls (# symbol)

If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:

  1. Set up your base href in your _Layout page: <head> <base href="/"> </head>

  2. Then, add following in your angular app config : $locationProvider.html5Mode(true)

  3. Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refreash will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all

url:

routes.MapRoute(
    name: "App",
    url: "{*url}",
    defaults: new {
        controller = "Home", action = "Index"
    }
);

TypeScript function overloading

Function overloading in typescript:

According to Wikipedia, (and many programming books) the definition of method/function overloading is the following:

In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

In typescript we cannot have different implementations of the same function that are called according to the number and type of arguments. This is because when TS is compiled to JS, the functions in JS have the following characteristics:

  • JavaScript function definitions do not specify data types for their parameters
  • JavaScript functions do not check the number of arguments when called

Therefore, in a strict sense, one could argue that TS function overloading doesn't exists. However, there are things you can do within your TS code that can perfectly mimick function overloading.

Here is an example:

function add(a: number, b: number, c: number): number;
function add(a: number, b: number): any;
function add(a: string, b: string): any;

function add(a: any, b: any, c?: any): any {
  if (c) {
    return a + c;
  }
  if (typeof a === 'string') {
    return `a is ${a}, b is ${b}`;
  } else {
    return a + b;
  }
}

The TS docs call this method overloading, and what we basically did is supplying multiple method signatures (descriptions of possible parameters and types) to the TS compiler. Now TS can figure out if we called our function correctly during compile time and give us an error if we called the function incorrectly.

Deserialize JSON to ArrayList<POJO> using Jackson

Another way is to use an array as a type, e.g.:

ObjectMapper objectMapper = new ObjectMapper();
MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:

List<MyPojo> pojoList = Arrays.asList(pojos);

IMHO this is much more readable.

And to make it be an actual list (that can be modified, see limitations of Arrays.asList()) then just do the following:

List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos));

Python Matplotlib Y-Axis ticks on Right Side of Plot

Use ax.yaxis.tick_right()

for example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

enter image description here

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

The reason for this apparent performance discrepancy between categorical & binary cross entropy is what user xtof54 has already reported in his answer below, i.e.:

the accuracy computed with the Keras method evaluate is just plain wrong when using binary_crossentropy with more than 2 labels

I would like to elaborate more on this, demonstrate the actual underlying issue, explain it, and offer a remedy.

This behavior is not a bug; the underlying reason is a rather subtle & undocumented issue at how Keras actually guesses which accuracy to use, depending on the loss function you have selected, when you include simply metrics=['accuracy'] in your model compilation. In other words, while your first compilation option

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

is valid, your second one:

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

will not produce what you expect, but the reason is not the use of binary cross entropy (which, at least in principle, is an absolutely valid loss function).

Why is that? If you check the metrics source code, Keras does not define a single accuracy metric, but several different ones, among them binary_accuracy and categorical_accuracy. What happens under the hood is that, since you have selected binary cross entropy as your loss function and have not specified a particular accuracy metric, Keras (wrongly...) infers that you are interested in the binary_accuracy, and this is what it returns - while in fact you are interested in the categorical_accuracy.

Let's verify that this is the case, using the MNIST CNN example in Keras, with the following modification:

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])  # WRONG way

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=2,  # only 2 epochs, for demonstration purposes
          verbose=1,
          validation_data=(x_test, y_test))

# Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0) 
score[1]
# 0.9975801164627075

# Actual accuracy calculated manually:
import numpy as np
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98780000000000001

score[1]==acc
# False    

To remedy this, i.e. to use indeed binary cross entropy as your loss function (as I said, nothing wrong with this, at least in principle) while still getting the categorical accuracy required by the problem at hand, you should ask explicitly for categorical_accuracy in the model compilation as follows:

from keras.metrics import categorical_accuracy
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[categorical_accuracy])

In the MNIST example, after training, scoring, and predicting the test set as I show above, the two metrics now are the same, as they should be:

# Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0) 
score[1]
# 0.98580000000000001

# Actual accuracy calculated manually:
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98580000000000001

score[1]==acc
# True    

System setup:

Python version 3.5.3
Tensorflow version 1.2.1
Keras version 2.0.4

UPDATE: After my post, I discovered that this issue had already been identified in this answer.

Arrays in unix shell?

in bash, you create array like this

arr=(one two three)

to call the elements

$ echo "${arr[0]}"
one
$ echo "${arr[2]}"
three

to ask for user input, you can use read

read -p "Enter your choice: " choice

How to strip HTML tags from a string in SQL Server?

Patrick Honorez code needs a slight change.

It returns incomplete results for html that contains &lt; or &gt;

This is because the code below the section

-- Remove anything between tags

will in fact replace the < > to nothing. The fix is to the apply the below two lines at the end:

set @HTMLText = replace(@htmlText, '&lt;' collate Latin1_General_CS_AS, '<'  collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '&gt;' collate Latin1_General_CS_AS, '>'  collate Latin1_General_CS_AS)

Writing a list to a file with Python

Another way of iterating and adding newline:

for item in items:
    filewriter.write(f"{item}" + "\n")

How to sort mongodb with pymongo

You can try this:

db.Account.find().sort("UserName")  
db.Account.find().sort("UserName",pymongo.ASCENDING)   
db.Account.find().sort("UserName",pymongo.DESCENDING)  

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Sections don't work in partial views and that's by design. You may use some custom helpers to achieve similar behavior, but honestly it's the view's responsibility to include the necessary scripts, not the partial's responsibility. I would recommend using the @scripts section of the main view to do that and not have the partials worry about scripts.

JavaScript: changing the value of onclick with or without jQuery

Note that following gnarf's idea you can also do:

var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;

That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).

Does Java have an exponential operator?

In case if anyone wants to create there own exponential function using recursion, below is for your reference.

public static double power(double value, double p) {
        if (p <= 0)
            return 1;

        return value * power(value, p - 1);
    }

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

convert nan value to zero

A code example for drake's answer to use nan_to_num:

>>> import numpy as np
>>> A = np.array([[1, 2, 3], [0, 3, np.NaN]])
>>> A = np.nan_to_num(A)
>>> A
array([[ 1.,  2.,  3.],
       [ 0.,  3.,  0.]])

"Rate This App"-link in Google Play store app on the phone

Best Way

From now you can use In App Rating feature by Google.

Here is Kotlin/Java integration official guide

The Google Play In-App Review API lets you prompt users to submit Play Store ratings and reviews without the inconvenience of leaving your app or game.

Generally, the in-app review flow (see figure 1) can be triggered at any time throughout the user journey of your app. During the flow, the user has the ability to rate your app using the 1 to 5 star system and to add an optional comment. Once submitted, the review is sent to the Play Store and eventually displayed.

sc

Detecting when the 'back' button is pressed on a navbar

You should check out the UINavigationBarDelegate Protocol. In this case you might want to use the navigationBar:shouldPopItem: method.

Angular 2 Hover event

For handling the event on overing, you can try something like this (it works for me):

In the Html template:

<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
  <img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>

In the angular component:

    onHovering(eventObject) {
    console.log("AlertsBtnComponent.onHovering:");
    var regExp = new RegExp(".svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));       
    }

   }
   onUnovering(eventObject) {
    console.log("AlertsBtnComponent.onUnovering:");
    var regExp = new RegExp("_h.svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
    }
}

Setting different color for each series in scatter plot on matplotlib

A MUCH faster solution for large dataset and limited number of colors is the use of Pandas and the groupby function:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time


# a generic set of data with associated colors
nsamples=1000
x=np.random.uniform(0,10,nsamples)
y=np.random.uniform(0,10,nsamples)
colors={0:'r',1:'g',2:'b',3:'k'}
c=[colors[i] for i in np.round(np.random.uniform(0,3,nsamples),0)]

plt.close('all')

# "Fast" Scatter plotting
starttime=time.time()
# 1) make a dataframe
df=pd.DataFrame()
df['x']=x
df['y']=y
df['c']=c
plt.figure()
# 2) group the dataframe by color and loop
for g,b in df.groupby(by='c'):
    plt.scatter(b['x'],b['y'],color=g)
print('Fast execution time:', time.time()-starttime)

# "Slow" Scatter plotting
starttime=time.time()
plt.figure()
# 2) group the dataframe by color and loop
for i in range(len(x)):
    plt.scatter(x[i],y[i],color=c[i])
print('Slow execution time:', time.time()-starttime)

plt.show()

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.

A new version of OSX or XCode was installed and Apple wants you to agree to their Terms and Conditions. So just launch Xcode and "Agree" to them.

How do I update a formula with Homebrew?

I think the correct way to do is

brew upgrade mongodb

It will upgrade the mongodb formula. If you want to upgrade all outdated formula, simply

brew upgrade

Angular - ng: command not found

If you have already installed @angular/cli

Then you only need to link it to npm using npm link @angular/cli

Otherwise first install angular by npm install @angular/cli and then link.

Proper way to empty a C-String

If you are trying to clear out a receive buffer for something that receives strings I have found the best way is to use memset as described above. The reason is that no matter how big the next received string is (limited to sizeof buffer of course), it will automatically be an asciiz string if written into a buffer that has been pre-zeroed.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

jQuery: Currency Format Number

Please find in the below code what I developed to support internationalization. It formats the given numeric value to language specific format. In the given example I have used ‘en’ while have tested for ‘es’, ‘fr’ and other countries where in the format varies. It not only stops user from keying characters but formats the value on tab out. Have created components for Number as well as for Decimal format. Apart from this have created parseNumber(value, locale) and parseDecimal(value, locale) functions which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value. I have used JQuery validator plugin in the below shared code.

HTML:

<tr>
                            <td>
                                <label class="control-label">
                                    Number Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="numberField" 
                                           name="numberField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="17"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           data-rule-numberExceedsMaxLimit="en"
                                           data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           onkeydown="return isNumber(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="numberFormatter(this,                                                           
                                                       'en', 
                                                       'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label class="control-label">
                                    Decimal Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="decimalField" 
                                           name="decimalField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="20"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           data-rule-decimalExceedsMaxLimit="en"
                                           data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           onkeydown="return isDecimal(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="decimalFormatter(this,
                                               'en', 
                                               'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>

JavaScript:

            /* 
     * @author: dinesh.lomte
     */
    /* Holds the maximum limit of digits to be entered in number field. */
    var numericMaxLimit = 13;
    /* Holds the maximum limit of digits to be entered in decimal field. */
    var decimalMaxLimit = 16;

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Boolean}
     */
    parseDecimal = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0.00;
        }
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            value = value.replace(/\./g, '');
        } else {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[0], 'g'), '');
        }
        if (getNumberFormat(locale)[1] === ',') {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[1], 'g'), '.');
        }
        return value;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    decimalFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();
        value = value.replace(/\s/g, '');
        value = parseDecimal(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    numberFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();    
        var format = getNumberFormat(locale);
        if (hasDecimal(value, format[1])) {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        value = value.replace(/\s/g, '');
        value = parseNumber(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} id
     * @param {type} flag
     * @param {type} message
     * @returns {undefined}
     */
    showErrorMessage = function(id, flag, message) {

        if (flag) {
            // only add if not added
            if ($('#'+id).parent().next('.app-error-message').length === 0) {
                var errorTag = '<div class=\'app-error-message\'>' + message + '</div>';
                $('#'+id).parent().after(errorTag);
            }
        } else {
            // remove it
            $('#'+id).parent().next(".app-error-message").remove(); 
        }
    };

    /**
     * 
     * @param {type} id             
     * @returns
     */
    setFocus = function(id) {

        id = id.trim();
        if (isNull(id)) {
            return;
        }
        setTimeout(function() {
            document.getElementById(id).focus();
        }, 10);
    };

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Array}
     */
    parseNumber = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0;
        }    
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            return value.replace(/\./g, '');
        }
        return value.replace(
                new RegExp(getNumberFormat(locale)[0], 'g'), '');
    };

    /**
     * 
     * @param {type} locale
     * @returns {Array}
     */
    getNumberFormat = function(locale) {

        var format = [];
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        var value = numberFormatObj.format('132617.07');
        format[0] = value.charAt(3);
        format[1] = value.charAt(7);
        return format;
    };

    /**
     * 
     * @param {type} value
     * @param {type} fractionFormat
     * @returns {Boolean}
     */
    hasDecimal = function(value, fractionFormat) {

        value = value.trim();
        if (isNull(value) || isNull(fractionFormat)) {
            return false;
        }
        if (value.indexOf(fractionFormat) >= 1) {
            return true;
        }
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isNumber = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {        
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && getNumberFormat(locale)[0] === getFormat(keyCode)) {        
            return true;
        }    
        return false;
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isDecimal = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && (getNumberFormat(locale)[0] === getFormat(keyCode)
                    || getNumberFormat(locale)[1] === getFormat(keyCode))) {
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {Boolean}
     */
    isNumberKey = function(keyCode) {

        if ((keyCode >= 48 && keyCode <= 57)
                || (keyCode >= 96 && keyCode <= 105)) {        
            return true;
        }
        var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];
        if (keys.indexOf(keyCode) !== -1) {        
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {JSON@call;parse.numberFormatter.value|String}
     */
    getFormat = function(keyCode) {

        var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}';
        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.numberFormatter) {
            if (jsonObject.numberFormatter.hasOwnProperty(key)
                    && keyCode === parseInt(jsonObject.numberFormatter[key].key)) {
                return jsonObject.numberFormatter[key].value;
            }
        }
        return '';
    };

    /**
     * 
     * @type String
     */
    var jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}';

    /**
     * 
     * @param {type} value
     * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}
     */
    getShiftCharSpecificNumber = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return jsonObject.shiftCharacterNumberMap[key].number;
            }
        }
        return '';
    };

    /**
     * 
     * @param {type} value
     * @returns {Boolean}
     */
    isShiftSpecificChar = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return true;
            }
        }
        return false;
    };

    /**
     * 
     * @param {type} element
     * @returns {undefined}
     */
    updateField = function(element) {

        var value = element.value;

        for (var index = 0; index < value.length; index++) {
            if (!isShiftSpecificChar(value.charAt(index))) {
                continue;
            }
            element.value = value.replace(
                    value.charAt(index),
                    getShiftCharSpecificNumber(value.charAt(index)));
        }
    };

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {

        value = parseInt(parseNumber(value, params));
        if (value.toString().length > numericMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {

        value = parseFloat(parseDecimal(value, params)).toFixed(2);    
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isNumberExceedMaxLimit = function(id, locale) {

        var value = parseInt(parseNumber(
                document.getElementById(id).value, locale));
        if (value.toString().length > numericMaxLimit) {
            setFocus(id);
            return true;
        }    
        return false;
    };

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isDecimalExceedsMaxLimit = function(id, locale) {

        var value = parseFloat(parseDecimal(
                document.getElementById(id).value, locale)).toFixed(2);
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            setFocus(id);
            return true;
        }
        return false;
    };

How do you add an ActionListener onto a JButton in Java

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

How to use a calculated column to calculate another column in the same view

In SQL Server

You can do this using With CTE

WITH common_table_expression (Transact-SQL)

CREATE TABLE tab(ColumnA DECIMAL(10,2), ColumnB DECIMAL(10,2), ColumnC DECIMAL(10,2))

INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2),(3, 15, 6),(7, 14, 3)

WITH tab_CTE (ColumnA, ColumnB, ColumnC,calccolumn1)  
AS  
(  
Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from tab
)  

SELECT
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC AS calccolumn2
FROM  tab_CTE

DBFiddle Demo

Can I use library that used android support with Androidx projects.

If your project is not AndroidX (mean Appcompat) and got this error, try to downgrade dependencies versions that triggers this error, in my case play-services-location ("implementation 'com.google.android.gms:play-services-location:17.0.0'") , I solved the problem by downgrading to com.google.android.gms:play-services-location:16.0.0'

How to use Python's pip to download and keep the zipped files for a package?

I would prefer (RHEL) - pip download package==version --no-deps --no-binary=:all:

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Python Finding Prime Factors

"""
The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

"""

from sympy import primefactors
print primefactors(600851475143)[-1]

Pass correct "this" context to setTimeout callback?

NOTE: This won't work in IE

var ob = {
    p: "ob.p"
}

var p = "window.p";

setTimeout(function(){
    console.log(this.p); // will print "window.p"
},1000); 

setTimeout(function(){
    console.log(this.p); // will print "ob.p"
}.bind(ob),1000);

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

Show/Hide the console window of a C# console application

If you don't have a problem integrating a small batch application, there is this program called Cmdow.exe that will allow you to hide console windows based on console title.

Console.Title = "MyConsole";
System.Diagnostics.Process HideConsole = new System.Diagnostics.Process();
HideConsole.StartInfo.UseShellExecute = false;
HideConsole.StartInfo.Arguments = "MyConsole /hid";
HideConsole.StartInfo.FileName = "cmdow.exe";
HideConsole.Start();

Add the exe to the solution, set the build action to "Content", set Copy to Output Directory to what suits you, and cmdow will hide the console window when it is ran.

To make the console visible again, you just change the Arguments

HideConsole.StartInfo.Arguments = "MyConsole /Vis";

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

What are Transient and Volatile Modifiers?

Volatile means other threads can edit that particular variable. So the compiler allows access to them.

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Transient means that when you serialize an object, it will return its default value on de-serialization

http://www.geekinterview.com/question_details/2

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Codified version of all other answers (at the time of writing):

import java.io.*;

/**
 * This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
 * <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
 * of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
 * Also includes comments and observations from others on the same question, and my own experience.
 * <p>
 * <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
 * <p>
 * <b>JVM memory management crash course</b>:
 * Java virtual machine process' heap size is bounded by the maximum memory allowed.
 * The startup and maximum size can be configured by JVM arguments.
 * JVMs don't allocate the maximum memory on startup as the program running may never require that.
 * This is to be a good player and not waste system resources unnecessarily.
 * Instead they allocate some memory and then grow when new allocations require it.
 * The garbage collector will be run at times to clean up unused objects to prevent this growing.
 * Many parameters of this management such as when to grow/shrink or which GC to use
 * can be tuned via advanced configuration parameters on JVM startup.
 *
 * @see <a href="http://stackoverflow.com/a/42567450/253468">
 *     What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
 * @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
 *     Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
 *     Full VM options reference for Windows</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
 *     Full VM options reference for Linux, Mac OS X and Solaris</a>
 * @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
 *     Java HotSpot VM Options quick reference</a>
 */
public class SystemMemory {

    // can be white-box mocked for testing
    private final Runtime runtime = Runtime.getRuntime();

    /**
     * <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
     * <p>
     * <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
     */
    public long getAllocatedTotal() {
        return runtime.totalMemory();
    }

    /**
     * <b>Current allocated free memory</b>: space immediately ready for new objects.
     * <p>
     * <i>Caution</i>: this is not the total free available memory,
     * the JVM may grow the heap for new allocations.
     */
    public long getAllocatedFree() {
        return runtime.freeMemory();
    }

    /**
     * <b>Used memory</b>:
     * Java heap currently used by instantiated objects. 
     * <p>
     * <i>Caution</i>: May include no longer referenced objects, soft references, etc.
     * that will be swept away by the next garbage collection.
     */
    public long getUsed() {
        return getAllocatedTotal() - getAllocatedFree();
    }

    /**
     * <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
     * <p>
     * <i>Caution</i>: This may change over time, do not cache it!
     * There are some JVMs / garbage collectors that can shrink the allocated process memory.
     * <p>
     * <i>Caution</i>: If this is true, the JVM will likely run GC more often.
     */
    public boolean isAtMaximumAllocation() {
        return getAllocatedTotal() == getTotal();
        // = return getUnallocated() == 0;
    }

    /**
     * <b>Unallocated memory</b>: amount of space the process' heap can grow.
     */
    public long getUnallocated() {
        return getTotal() - getAllocatedTotal();
    }

    /**
     * <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
     * <p>
     * <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
     */
    public long getTotal() {
        return runtime.maxMemory();
    }

    /**
     * <b>Total free memory</b>: memory available for new Objects,
     * even at the cost of growing the allocated memory of the process.
     */
    public long getFree() {
        return getTotal() - getUsed();
        // = return getAllocatedFree() + getUnallocated();
    }

    /**
     * <b>Unbounded memory</b>: there is no inherent limit on free memory.
     */
    public boolean isBounded() {
        return getTotal() != Long.MAX_VALUE;
    }

    /**
     * Dump of the current state for debugging or understanding the memory divisions.
     * <p>
     * <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
     */
    public String getCurrentStats() {
        StringWriter backing = new StringWriter();
        PrintWriter out = new PrintWriter(backing, false);
        out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
                getAllocatedTotal(),
                (float)getAllocatedTotal() / (float)getTotal() * 100,
                getTotal(),
                isBounded()? "bounded" : "unbounded",
                isAtMaximumAllocation()? "maxed out" : "can grow",
                getUnallocated()
        );
        out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
                getUsed(),
                (float)getUsed() / (float)getTotal() * 100,
                getTotal(),
                (float)getUsed() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
                getFree(),
                (float)getFree() / (float)getTotal() * 100,
                getTotal(),
                getAllocatedFree(),
                (float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.flush();
        return backing.toString();
    }

    public static void main(String... args) {
        SystemMemory memory = new SystemMemory();
        System.out.println(memory.getCurrentStats());
    }
}

Using FileUtils in eclipse

<!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.io -->
<dependency>
    <groupId>org.apache.directory.studio</groupId>
    <artifactId>org.apache.commons.io</artifactId>
    <version>2.4</version>
</dependency>

Add above dependency in pom.xml file

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

It may be added at that '&' can be used to add additional conditions e.g.

df = df[(df.EPS > 2.0) & (df.EPS <4.0)]

Notice that when evaluating the statements, pandas needs parenthesis.

Are HTTP headers case-sensitive?

Header names are not case sensitive.

From RFC 2616 - "Hypertext Transfer Protocol -- HTTP/1.1", Section 4.2, "Message Headers":

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

The updating RFC 7230 does not list any changes from RFC 2616 at this part.

PHP date yesterday

strtotime(), as in date("F j, Y", strtotime("yesterday"));

How can I delete all of my Git stashes at once?

There are two ways to delete a stash:

  1. If you no longer need a particular stash, you can delete it with: $ git stash drop <stash_id>.
  2. You can delete all of your stashes from the repo with: $ git stash clear.

Use both of them with caution, it maybe is difficult to revert the once deleted stashes.

Here is the reference article.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,

Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.

Add Relations Tab - SQL Server Compact Tool Box

Comments in Markdown

I use standard HTML tags, like

<!---
your comment goes here
and here
-->

Note the triple dash. The advantage is that it works with pandoc when generating TeX or HTML output. More information is available on the pandoc-discuss group.

Python integer incrementing with ++

Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.

Fortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can find the answer here: Is there a minlength validation attribute in HTML5?

Therefore this should do the job:

<input pattern=".{6,6}">

Difference between del, remove, and pop on lists

pop

Takes index (when given, else take last), removes value at that index, and returns value

remove

Takes value, removes first occurrence, and returns nothing

delete

Takes index, removes value at that index, and returns nothing

MySQL Cannot Add Foreign Key Constraint

To find the specific error run this:

SHOW ENGINE INNODB STATUS;

And look in the LATEST FOREIGN KEY ERROR section.

The data type for the child column must match the parent column exactly. For example, since medicalhistory.MedicalHistoryID is an INT, Patient.MedicalHistory also needs to be an INT, not a SMALLINT.

Also, you should run the query set foreign_key_checks=0 before running the DDL so you can create the tables in an arbitrary order rather than needing to create all parent tables before the relevant child tables.

How to access random item in list?

ArrayList ar = new ArrayList();
        ar.Add(1);
        ar.Add(5);
        ar.Add(25);
        ar.Add(37);
        ar.Add(6);
        ar.Add(11);
        ar.Add(35);
        Random r = new Random();
        int index = r.Next(0,ar.Count-1);
        MessageBox.Show(ar[index].ToString());

SQL Server Script to create a new user

This past week I installed Microsoft SQL Server 2014 Developer Edition on my dev box, and immediately ran into a problem I had never seen before.

I’ve installed various versions of SQL Server countless times, and it is usually a painless procedure. Install the server, run the Management Console, it’s that simple. However, after completing this installation, when I tried to log in to the server using SSMS, I got an error like the one below:

SQL Server login error 18456 “Login failed for user… (Microsoft SQL Server, Error: 18456)” I’m used to seeing this error if I typed the wrong password when logging in – but that’s only if I’m using mixed mode (Windows and SQL Authentication). In this case, the server was set up with Windows Authentication only, and the user account was my own. I’m still not sure why it didn’t add my user to the SYSADMIN role during setup; perhaps I missed a step and forgot to add it. At any rate, not all hope was lost.

The way to fix this, if you cannot log on with any other account to SQL Server, is to add your network login through a command line interface. For this to work, you need to be an Administrator on Windows for the PC that you’re logged onto.

Stop the MSSQL service. Open a Command Prompt using Run As Administrator. Change to the folder that holds the SQL Server EXE file; the default for SQL Server 2014 is “C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Binn”. Run the following command: “sqlservr.exe –m”. This will start SQL Server in single-user mode. While leaving this Command Prompt open, open another one, repeating steps 2 and 3. In the second Command Prompt window, run “SQLCMD –S Server_Name\Instance_Name” In this window, run the following lines, pressing Enter after each one: 1

CREATE LOGIN [domainName\loginName] FROM WINDOWS 2 GO 3 SP_ADDSRVROLEMEMBER 'LOGIN_NAME','SYSADMIN' 4 GO Use CTRL+C to end both processes in the Command Prompt windows; you will be prompted to press Y to end the SQL Server process.

Restart the MSSQL service. That’s it! You should now be able to log in using your network login.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I think that you can bind the load event of the iframe, the event fires when the iframe content is fully loaded.

At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.

Code:

var iframeError;

function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout(error, 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));

});

Demo: http://jsfiddle.net/IrvinDominin/QXc6P/

Second problem

It is because you miss the parens in the inline function call; try change this:

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

into this:

<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>

Demo: http://jsfiddle.net/IrvinDominin/ALBXR/4/

ModalPopupExtender OK Button click event not firing?

I was just searching for a solution for this :)

it appears that you can't have OkControlID assign to a control if you want to that control fires an event, just removing this property I got everything working again.

my code (working):

<asp:Panel ID="pnlResetPanelsView" CssClass="modalPopup" runat="server" Style="display:none;">
    <h2>
        Warning</h2>
    <p>
        Do you really want to reset the panels to the default view?</p>
    <div style="text-align: center;">
        <asp:Button ID="btnResetPanelsViewOK" Width="60" runat="server" Text="Yes" 
            CssClass="buttonSuperOfficeLayout" OnClick="btnResetPanelsViewOK_Click" />&nbsp;
        <asp:Button ID="btnResetPanelsViewCancel" Width="60" runat="server" Text="No" CssClass="buttonSuperOfficeLayout" />
    </div>
</asp:Panel>
<ajax:ModalPopupExtender ID="mpeResetPanelsView" runat="server" TargetControlID="btnResetView"
    PopupControlID="pnlResetPanelsView" BackgroundCssClass="modalBackground" DropShadow="true"
    CancelControlID="btnResetPanelsViewCancel" />

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

The answer to your question is that you need to have permissions. Type the following code in your manifest.xml file:

<uses-sdk  android:minSdkVersion="8"   android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_OWNER_DATA"></uses-permission>
<uses-permission android:name="android.permission.READ_OWNER_DATA"></uses-permission>`

It worked for me...

Get current time as formatted string in Go?

For readability, best to use the RFC constants in the time package (me thinks)

import "fmt" 
import "time"

func main() {
    fmt.Println(time.Now().Format(time.RFC850))
}

How do I set the default Java installation/runtime (Windows)?

I have several JDK (1.4, 1.5, 1.6) installed in C:\Java with their JREs. Then I let Sun update the public JRE in C:\Program Files\Java.
Lately there is an improvement, installing in jre6. Previously, there was a different folder per new version (1.5.0_4, 1.5.0_5, etc.), which was taking lot of space

Making a DateTime field in a database automatic?

Just right click on that column and select properties and write getdate()in Default value or binding.like image:

enter image description here

If you want do it in CodeFirst in EF you should add this attributes befor of your column definition:

[Databasegenerated(Databaseoption.computed)]

this attributes can found in System.ComponentModel.Dataannotion.Schema.

In my opinion first one is better:))

jQuery select2 get value of select tag?

This solution allows you to forget select element. Helpful when you do not have an id on select elements.

$("#first").select2()
.on("select2:select", function (e) {
    var selected_element = $(e.currentTarget);
    var select_val = selected_element.val();
});

How to exit from the application and show the home screen?

Here's what i did:

SomeActivity.java

 @Override
    public void onBackPressed() {
            Intent newIntent = new Intent(this,QuitAppActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(newIntent);
            finish();
    }

QuitAppActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      finish();
}

Basically what you did is cleared all activities from the stack and launch QuitAppActivity, that will finish the task.

Smooth scroll without the use of jQuery

<script>
var set = 0;

function animatescroll(x, y) {
    if (set == 0) {
        var val72 = 0;
        var val73 = 0;
        var setin = 0;
        set = 1;

        var interval = setInterval(function() {
            if (setin == 0) {
                val72++;
                val73 += x / 1000;
                if (val72 == 1000) {
                    val73 = 0;
                    interval = clearInterval(interval);
                }
                document.getElementById(y).scrollTop = val73;
            }
        }, 1);
    }
}
</script>

x = scrollTop
y = id of the div that is used to scroll

Note: For making the body to scroll give the body an ID.

Checking if a list is empty with LINQ

private bool NullTest<T>(T[] list, string attribute)

    {
        bool status = false;
        if (list != null)
        {
            int flag = 0;
            var property = GetProperty(list.FirstOrDefault(), attribute);
            foreach (T obj in list)
            {
                if (property.GetValue(obj, null) == null)
                    flag++;
            }
            status = flag == 0 ? true : false;
        }
        return status;
    }


public PropertyInfo GetProperty<T>(T obj, string str)

    {
        Expression<Func<T, string, PropertyInfo>> GetProperty = (TypeObj, Column) => TypeObj.GetType().GetProperty(TypeObj
            .GetType().GetProperties().ToList()
            .Find(property => property.Name
            .ToLower() == Column
            .ToLower()).Name.ToString());
        return GetProperty.Compile()(obj, str);
    }

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

It turned out there were 2 versions of SQL Server installed on the machine.
Removing the old one solved the issues on my side.

More details:
During the startup the services of both services were trying to run.
And the one which was loaded first was working properly and was blocking the second to start.
P.S. Stopping the services of the first server and manually starting the second wasn't working as well.

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

ssh: The authenticity of host 'hostname' can't be established

Ideally, you should create a self-managed certificate authority. Start with generating a key pair: ssh-keygen -f cert_signer

Then sign each server's public host key: ssh-keygen -s cert_signer -I cert_signer -h -n www.example.com -V +52w /etc/ssh/ssh_host_rsa_key.pub

This generates a signed public host key: /etc/ssh/ssh_host_rsa_key-cert.pub

In /etc/ssh/sshd_config, point the HostCertificate to this file: HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub

Restart the sshd service: service sshd restart

Then on the SSH client, add the following to ~/.ssh/known_hosts: @cert-authority *.example.com ssh-rsa AAAAB3Nz...cYwy+1Y2u/

The above contains:

  • @cert-authority
  • The domain *.example.com
  • The full contents of the public key cert_signer.pub

The cert_signer public key will trust any server whose public host key is signed by the cert_signer private key.

Although this requires a one-time configuration on the client side, you can trust multiple servers, including those that haven't been provisioned yet (as long as you sign each server, that is).

For more details, see this wiki page.

Eliminate extra separators below UITableView

Swift 4.0 Extension

Just a little extension for the storyboard:

enter image description here

extension UITableView {
    @IBInspectable
    var hideSeparatorForEmptyCells: Bool {
        set {
            tableFooterView = newValue ? UIView() : nil
        }
        get {
            return tableFooterView == nil
        }
    }
}

Change input text border color without changing its height

Try this

<input type="text"/>

It will display same in all cross browser like mozilla , chrome and internet explorer.

<style>
    input{
       border:2px solid #FF0000;
    }
</style>

Dont add style inline because its not good practise, use class to add style for your input box.

HttpUtility does not exist in the current context

It worked for by following process:

Add Reference:

system.net
system.web

also, include the namespace

using system.net
using system.web

Decreasing height of bootstrap 3.0 navbar

Working solution:

Bootstrap 3.0 by default has a 15px padding on top and bottom, so we just need to override it!

For example:

.navbar-nav > li > a {padding-top:10px !important; padding-bottom:10px !important;}
.navbar {min-height:40px !important}

How to get back to the latest commit after checking out a previous commit?

If you have a branch different than master, one easy way is to check out that branch, then check out master. Voila, you are back at the tip of master. There's probably smarter ways...

How to extract string following a pattern with grep, regex or perl

Oops, the sed command has to precede the tidy command of course:

echo "$htmlstr" | 
sed '/type="global"/d' |
tidy -q -c -wrap 0 -numeric -asxml -utf8 --merge-divs yes --merge-spans yes 2>/dev/null |
xmlstarlet sel -N x="http://www.w3.org/1999/xhtml" -T -t -m "//x:table" -v '@name' -n

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Javascript | Set all values of an array

The ES6 approach is very clean. So first you initialize an array of x length, and then call the fill method on it.

let arr = new Array(3).fill(9)

this will create an array with 3 elements like:

[9, 9, 9]

Typescript: difference between String and string

Here is an example that shows the differences, which will help with the explanation.

var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;

String is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2 in the example above creates a new string without the use of the new keyword and without explicitly using the String object.

string is the TypeScript string type, which you can use to type variables, parameters and return values.

Additional notes...

Currently (Feb 2013) Both s1 and s2 are valid JavaScript. s3 is valid TypeScript.

Use of String. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:

var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();

If you really had a penchant for the string, you could use it in TypeScript in one of two ways...

var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type

Get loop counter/index using for…of syntax in JavaScript

For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.

Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).

loop over an Array:

var a = [];
for (var i=0; i<a.length; i++) {
    i // is the index
    a[i] // is the item
}

loop over an Object:

var o = {};
for (var prop in o) {
    prop // is the property name
    o[prop] // is the property value - the item
}

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

HttpServletRequest - Get query string parameters, no form data

Java 8

return Collections.list(httpServletRequest.getParameterNames())
                  .stream()
                  .collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));

How to do a SUM() inside a case statement in SQL server

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.

Example

This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

     SELECT 
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

batch file to check 64bit or 32bit OS

I use either of the following:

:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (GOTO 64BIT) ELSE (GOTO 32BIT)

:64BIT
echo 64-bit...
GOTO END

:32BIT
echo 32-bit...
GOTO END

:END

or I set the bit variable, which I later use in my script to run the correct setup.

:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (set bit=x64) ELSE (set bit=x86)

or...

:CheckOS
IF "%PROCESSOR_ARCHITECTURE%"=="x86" (set bit=x86) else (set bit=x64)

Hope this helps.

How can I combine multiple rows into a comma-delimited list in Oracle?

SELECT REPLACE(REPLACE
((SELECT     TOP (100) PERCENT country_name + ', ' AS CountryName
FROM         country_name
ORDER BY country_name FOR XML PATH('')), 
'&<CountryName>', ''), '&<CountryName>', '') AS CountryNames

Logical Operators, || or OR?

I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.

EDIT: As others have pointed out there is indeed a difference between the two.

substring index range

Like you I didn't find it came naturally. I normally still have to remind myself that

  • the length of the returned string is

    lastIndex - firstIndex

  • that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception

so

"University".substring(6, 10)

returns the 4-character string "sity" even though there is no character at position 10.

showing that a date is greater than current date

Assuming you have a field for DateTime, you could have your query look like this:

SELECT *
FROM TABLE
WHERE DateTime > (GetDate() + 90)

How to enable Bootstrap tooltip on disabled button?

Based on Bootstrap 4

Disabled elements Elements with the disabled attribute aren’t interactive, meaning users cannot focus, hover, or click them to trigger a tooltip (or popover). As a workaround, you’ll want to trigger the tooltip from a wrapper or , ideally made keyboard-focusable using tabindex="0", and override the pointer-events on the disabled element.

<span class="d-inline-block" tabindex="0" data-toggle="tooltip" title="Disabled tooltip">
  <button class="btn btn-primary" style="pointer-events: none;" type="button" disabled>Disabled button</button>
</span>

All the details here: Bootstrap 4 doc

Reliable and fast FFT in Java

Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms

How do I draw a shadow under a UIView?

To those who failed in getting this to work (As myself!) after trying all the answers here, just make sure Clip Subviews is not enabled at the Attributes inspector...

CSS background image to fit width, height should auto-scale in proportion

I had the same issue, unable to resize the image when adjusting browser dimensions.

Bad Code:

html {  
  background-color: white;  
  background-image: url("example.png");  
  background-repeat: no-repeat;  
  background-attachment: scroll;  
  background-position: 0% 0%;
}


Good Code:

html {  
  background-color: white;  
  background-image: url("example.png");  
  background-repeat: no-repeat;  
  background-attachment: scroll;  
  background-position: 0% 0%;
  background-size: contain;
}

The key here is the addition of this element -> background-size: contain;

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Carriage return in C?

From 5.2.2/2 (character display semantics) :

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n (new line) Moves the active position to the initial position of the next line.

\r (carriage return) Moves the active position to the initial position of the current line.

Here, your code produces :

  • <new_line>ab
  • \b : back one character
  • write si : overrides the b with s (producing asi on the second line)
  • \r : back at the beginning of the current line
  • write ha : overrides the first two characters (producing hai on the second line)

In the end, the output is :

\nhai

How do I share variables between different .c files?

Those other variables would have to be declared public (use extern, public is for C++), and you would have to include that .c file. However, I recommend creating appropriate .h files to define all of your variables.

For example, for hello.c, you would have a hello.h, and hello.h would store your variable definitions. Then another .c file, such as world.c would have this piece of code at the top:

#include "hello.h"

That will allow world.c to use variables that are defined in hello.h

It's slightly more complicated than that though. You may use < > to include library files found on your OS's path. As a beginner I would stick all of your files in the same folder and use the " " syntax.

How do I add a simple onClick event handler to a canvas element?

Probably very late to the answer but I just read this while preparing for my 70-480 exam, and found this to work -

var elem = document.getElementById('myCanvas');
elem.onclick = function() { alert("hello world"); }

Notice the event as onclick instead of onClick.

JS Bin example.

How do I display a wordpress page content?

@Sydney Try putting wp_reset_query() before you call the loop. This will display the content of your page.

<?php
    wp_reset_query(); // necessary to reset query
    while ( have_posts() ) : the_post();
        the_content();
    endwhile; // End of the loop.
?>

EDIT: Try this if you have some other loops that you previously ran. Place wp_reset_query(); where you find it most suitable, but before you call this loop.

Export a graph to .eps file with R

The postscript() device allows creation of EPS, but only if you change some of the default values. Read ?postscript for the details.

Here is an example:

postscript("foo.eps", horizontal = FALSE, onefile = FALSE, paper = "special")
plot(1:10)
dev.off()

Linux Process States

When a process needs to fetch data from a disk, it effectively stops running on the CPU to let other processes run because the operation might take a long time to complete – at least 5ms seek time for a disk is common, and 5ms is 10 million CPU cycles, an eternity from the point of view of the program!

From the programmer point of view (also said "in userspace"), this is called a blocking system call. If you call write(2) (which is a thin libc wrapper around the system call of the same name), your process does not exactly stop at that boundary; it continues, in the kernel, running the system call code. Most of the time it goes all the way up to a specific disk controller driver (filename ? filesystem/VFS ? block device ? device driver), where a command to fetch a block on disk is submitted to the proper hardware, which is a very fast operation most of the time.

THEN the process is put in sleep state (in kernel space, blocking is called sleeping – nothing is ever 'blocked' from the kernel point of view). It will be awakened once the hardware has finally fetched the proper data, then the process will be marked as runnable and will be scheduled. Eventually, the scheduler will run the process.

Finally, in userspace, the blocking system call returns with proper status and data, and the program flow goes on.

It is possible to invoke most I/O system calls in non-blocking mode (see O_NONBLOCK in open(2) and fcntl(2)). In this case, the system calls return immediately and only report submitting the disk operation. The programmer will have to explicitly check at a later time whether the operation completed, successfully or not, and fetch its result (e.g., with select(2)). This is called asynchronous or event-based programming.

Most answers here mentioning the D state (which is called TASK_UNINTERRUPTIBLE in the Linux state names) are incorrect. The D state is a special sleep mode which is only triggered in a kernel space code path, when that code path can't be interrupted (because it would be too complex to program), with the expectation that it would block only for a very short time. I believe that most "D states" are actually invisible; they are very short lived and can't be observed by sampling tools such as 'top'.

You can encounter unkillable processes in the D state in a few situations. NFS is famous for that, and I've encountered it many times. I think there's a semantic clash between some VFS code paths, which assume to always reach local disks and fast error detection (on SATA, an error timeout would be around a few 100 ms), and NFS, which actually fetches data from the network which is more resilient and has slow recovery (a TCP timeout of 300 seconds is common). Read this article for the cool solution introduced in Linux 2.6.25 with the TASK_KILLABLE state. Before this era there was a hack where you could actually send signals to NFS process clients by sending a SIGKILL to the kernel thread rpciod, but forget about that ugly trick.…

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

remote: repository not found fatal: not found

Your username shouldn't be an email address, but your GitHub user account: pete.
And your password should be your GitHub account password.

You actually can set your username directly in the remote url, in order for Git to request only your password:

cd C:\Users\petey_000\rails_projects\first_app
git remote set-url origin https://[email protected]/pete/first_app

And you need to create the fist_app repo on GitHub first: make sure to create it completely empty, or, if you create it with an initial commit (including a README.md, a license file and a .gitignore file), then do a git pull first, before making your git push.

Naming returned columns in Pandas aggregate function?

I agree with the OP that it seems more natural and consistent to name and define the output columns in the same place (e.g. as is done with tidyverse's summarize in R), but a work-around in pandas for now is to create the new columns with desired names via assign before doing the aggregation:

data.assign(
    f=data['column1'],
    mean=data['column2'],
    std=data['column2']
).groupby('Country').agg(dict(f=sum, mean=np.mean, std=np.std)).reset_index()

(Using reset_index turns 'Country', 'f', 'mean', and 'std' all into regular columns with a separate integer index.)

Changing the child element's CSS when the parent is hovered

Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.

*:not(:hover)>.parent-hover-show{
    display:none;
}

But this way, all you need is to apply parent-hover-show to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.

How to convert unsigned long to string

The standard approach is to use sprintf(buffer, "%lu", value); to write a string rep of value to buffer. However, overflow is a potential problem, as sprintf will happily (and unknowingly) write over the end of your buffer.

This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.

This site discusses this and related problems at some length.

Some libraries offer snprintf as an alternative which lets you specify a maximum buffer size.

Check if value already exists within list of dictionaries?

Perhaps a function along these lines is what you're after:

 def add_unique_to_dict_list(dict_list, key, value):
  for d in dict_list:
     if key in d:
        return d[key]

  dict_list.append({ key: value })
  return value

Combining two lists and removing duplicates, without removing duplicates in original list

This might help

def union(a,b):
    for e in b:
        if e not in a:
            a.append(e)

The union function merges the second list into first, with out duplicating an element of a, if it's already in a. Similar to set union operator. This function does not change b. If a=[1,2,3] b=[2,3,4]. After union(a,b) makes a=[1,2,3,4] and b=[2,3,4]

Excel VBA select range at last row and column

Is this what you are trying? I have commented the code so that you will not have any problem understanding it.

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim rng As Range

    '~~> Set this to the relevant worksheet
    Set ws = [Sheet1]

    With ws
        '~~> Get the last row and last column
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Set the range
        Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))

        With rng
            Debug.Print .Address
            '
            '~~> What ever you want to do with the address
            '
        End With
    End With
End Sub

BTW I am assuming that LastRow is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find to find the Last Row and the Last Column. You might want to see THIS

How can I make a CSS table fit the screen width?

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Quick Answer:

The simplest way to get row counts per group is by calling .size(), which returns a Series:

df.groupby(['col1','col2']).size()


Usually you want this result as a DataFrame (instead of a Series) so you can do:

df.groupby(['col1', 'col2']).size().reset_index(name='counts')


If you want to find out how to calculate the row counts and other statistics for each group continue reading below.


Detailed example:

Consider the following example dataframe:

In [2]: df
Out[2]: 
  col1 col2  col3  col4  col5  col6
0    A    B  0.20 -0.61 -0.49  1.49
1    A    B -1.53 -1.01 -0.39  1.82
2    A    B -0.44  0.27  0.72  0.11
3    A    B  0.28 -1.32  0.38  0.18
4    C    D  0.12  0.59  0.81  0.66
5    C    D -0.13 -1.65 -1.64  0.50
6    C    D -1.42 -0.11 -0.18 -0.44
7    E    F -0.00  1.42 -0.26  1.17
8    E    F  0.91 -0.47  1.35 -0.34
9    G    H  1.48 -0.63 -1.14  0.17

First let's use .size() to get the row counts:

In [3]: df.groupby(['col1', 'col2']).size()
Out[3]: 
col1  col2
A     B       4
C     D       3
E     F       2
G     H       1
dtype: int64

Then let's use .size().reset_index(name='counts') to get the row counts:

In [4]: df.groupby(['col1', 'col2']).size().reset_index(name='counts')
Out[4]: 
  col1 col2  counts
0    A    B       4
1    C    D       3
2    E    F       2
3    G    H       1


Including results for more statistics

When you want to calculate statistics on grouped data, it usually looks like this:

In [5]: (df
   ...: .groupby(['col1', 'col2'])
   ...: .agg({
   ...:     'col3': ['mean', 'count'], 
   ...:     'col4': ['median', 'min', 'count']
   ...: }))
Out[5]: 
            col4                  col3      
          median   min count      mean count
col1 col2                                   
A    B    -0.810 -1.32     4 -0.372500     4
C    D    -0.110 -1.65     3 -0.476667     3
E    F     0.475 -0.47     2  0.455000     2
G    H    -0.630 -0.63     1  1.480000     1

The result above is a little annoying to deal with because of the nested column labels, and also because row counts are on a per column basis.

To gain more control over the output I usually split the statistics into individual aggregations that I then combine using join. It looks like this:

In [6]: gb = df.groupby(['col1', 'col2'])
   ...: counts = gb.size().to_frame(name='counts')
   ...: (counts
   ...:  .join(gb.agg({'col3': 'mean'}).rename(columns={'col3': 'col3_mean'}))
   ...:  .join(gb.agg({'col4': 'median'}).rename(columns={'col4': 'col4_median'}))
   ...:  .join(gb.agg({'col4': 'min'}).rename(columns={'col4': 'col4_min'}))
   ...:  .reset_index()
   ...: )
   ...: 
Out[6]: 
  col1 col2  counts  col3_mean  col4_median  col4_min
0    A    B       4  -0.372500       -0.810     -1.32
1    C    D       3  -0.476667       -0.110     -1.65
2    E    F       2   0.455000        0.475     -0.47
3    G    H       1   1.480000       -0.630     -0.63



Footnotes

The code used to generate the test data is shown below:

In [1]: import numpy as np
   ...: import pandas as pd 
   ...: 
   ...: keys = np.array([
   ...:         ['A', 'B'],
   ...:         ['A', 'B'],
   ...:         ['A', 'B'],
   ...:         ['A', 'B'],
   ...:         ['C', 'D'],
   ...:         ['C', 'D'],
   ...:         ['C', 'D'],
   ...:         ['E', 'F'],
   ...:         ['E', 'F'],
   ...:         ['G', 'H'] 
   ...:         ])
   ...: 
   ...: df = pd.DataFrame(
   ...:     np.hstack([keys,np.random.randn(10,4).round(2)]), 
   ...:     columns = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6']
   ...: )
   ...: 
   ...: df[['col3', 'col4', 'col5', 'col6']] = \
   ...:     df[['col3', 'col4', 'col5', 'col6']].astype(float)
   ...: 


Disclaimer:

If some of the columns that you are aggregating have null values, then you really want to be looking at the group row counts as an independent aggregation for each column. Otherwise you may be misled as to how many records are actually being used to calculate things like the mean because pandas will drop NaN entries in the mean calculation without telling you about it.

What do these three dots in React do?

Three dots ... represents Spread Operators or Rest Parameters,

It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls or elements for array are expected.

  • Merge two arrays

_x000D_
_x000D_
var arr1 = [1,2,3];_x000D_
var arr2 = [4,5,6];_x000D_
_x000D_
arr1 = [...arr1, ...arr2];_x000D_
console.log(arr1);  //[1, 2, 3, 4, 5, 6]
_x000D_
_x000D_
_x000D_

  • Copying array:

_x000D_
_x000D_
var arr = [1, 2, 3];_x000D_
var arr2 = [...arr];_x000D_
_x000D_
console.log(arr); //[1, 2, 3]
_x000D_
_x000D_
_x000D_

Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).

  • Add values of one array to other at specific index e.g 3:

_x000D_
_x000D_
var arr1 = [4,5]_x000D_
var arr2 = [1,2,3,...arr1,6]_x000D_
console.log(arr2); // [1, 2, 3, 4, 5, 6]
_x000D_
_x000D_
_x000D_

  • When calling a constructor with new:

_x000D_
_x000D_
var dateFields = [1970, 0, 1];  // 1 Jan 1970_x000D_
var d = new Date(...dateFields);_x000D_
_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_

  • Spread in object literals:

_x000D_
_x000D_
var obj1 = { foo: 'bar', x: 42 };_x000D_
var obj2 = { foo: 'baz', y: 13 };_x000D_
_x000D_
var clonedObj = { ...obj1 };_x000D_
console.log(clonedObj); //{foo: "bar", x: 42}_x000D_
_x000D_
var mergedObj = { ...obj1, ...obj2 };_x000D_
console.log(mergedObj); //{foo: "baz", x: 42, y: 13}
_x000D_
_x000D_
_x000D_

Note that foo property of obj1 has been overwritten by obj2 foo property

  • As a rest parameter syntax which allows us to represent an indefinite number of arguments as an array:

_x000D_
_x000D_
function sum(...theArgs) {_x000D_
  return theArgs.reduce((previous, current) => {_x000D_
    return previous + current;_x000D_
  });_x000D_
}_x000D_
_x000D_
console.log(sum(1, 2, 3)); //6_x000D_
console.log(sum(1, 2, 3, 4)); //10
_x000D_
_x000D_
_x000D_

Note:Spread syntax (other than in the case of spread properties) can be applied only to iterable objects: So following will throw error

_x000D_
_x000D_
var obj = {'key1': 'value1'};_x000D_
var array = [...obj]; // TypeError: obj is not iterable
_x000D_
_x000D_
_x000D_

Reference1

Reference2

How to delete a stash created with git stash create?

To delete a normal stash created with git stash , you want git stash drop or git stash drop stash@{n}. See below for more details.


You don't need to delete a stash created with git stash create. From the docs:

Create a stash entry (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.

Since nothing references the stash commit, it will get garbage collected eventually.


A stash created with git stash or git stash save is saved to refs/stash, and can be deleted with git stash drop. As with all Git objects, the actual stash contents aren't deleted from your computer until a gc prunes those objects after they expire (default is 2 weeks later).

Older stashes are saved in the refs/stash reflog (try cat .git/logs/refs/stash), and can be deleted with git stash drop stash@{n}, where n is the number shown by git stash list.

Convert string to integer type in Go?

For example,

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
)

func main() {
    flag.Parse()
    s := flag.Arg(0)
    // string to int
    i, err := strconv.Atoi(s)
    if err != nil {
        // handle error
        fmt.Println(err)
        os.Exit(2)
    }
    fmt.Println(s, i)
}

Check if a number is a perfect square

Use Newton's method to quickly zero in on the nearest integer square root, then square it and see if it's your number. See isqrt.

Python = 3.8 has math.isqrt. If using an older version of Python, look for the "def isqrt(n)" implementation here.

import math

def is_square(i: int) -> bool:
    return i == math.isqrt(i) ** 2

How would you count occurrences of a string (actually a char) within a string?

Thought I would throw my extension method into the ring (see comments for more info). I have not done any formal bench marking, but I think it has to be very fast for most scenarios.

EDIT: OK - so this SO question got me to wondering how the performance of our current implementation would stack up against some of the solutions presented here. I decided to do a little bench marking and found that our solution was very much in line with the performance of the solution provided by Richard Watson up until you are doing aggressive searching with large strings (100 Kb +), large substrings (32 Kb +) and many embedded repetitions (10K +). At that point our solution was around 2X to 4X slower. Given this and the fact that we really like the solution presented by Richard Watson, we have refactored our solution accordingly. I just wanted to make this available for anyone that might benefit from it.

Our original solution:

    /// <summary>
    /// Counts the number of occurrences of the specified substring within
    /// the current string.
    /// </summary>
    /// <param name="s">The current string.</param>
    /// <param name="substring">The substring we are searching for.</param>
    /// <param name="aggressiveSearch">Indicates whether or not the algorithm 
    /// should be aggressive in its search behavior (see Remarks). Default 
    /// behavior is non-aggressive.</param>
    /// <remarks>This algorithm has two search modes - aggressive and 
    /// non-aggressive. When in aggressive search mode (aggressiveSearch = 
    /// true), the algorithm will try to match at every possible starting 
    /// character index within the string. When false, all subsequent 
    /// character indexes within a substring match will not be evaluated. 
    /// For example, if the string was 'abbbc' and we were searching for 
    /// the substring 'bb', then aggressive search would find 2 matches 
    /// with starting indexes of 1 and 2. Non aggressive search would find 
    /// just 1 match with starting index at 1. After the match was made, 
    /// the non aggressive search would attempt to make it's next match 
    /// starting at index 3 instead of 2.</remarks>
    /// <returns>The count of occurrences of the substring within the string.</returns>
    public static int CountOccurrences(this string s, string substring, 
        bool aggressiveSearch = false)
    {
        // if s or substring is null or empty, substring cannot be found in s
        if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(substring))
            return 0;

        // if the length of substring is greater than the length of s,
        // substring cannot be found in s
        if (substring.Length > s.Length)
            return 0;

        var sChars = s.ToCharArray();
        var substringChars = substring.ToCharArray();
        var count = 0;
        var sCharsIndex = 0;

        // substring cannot start in s beyond following index
        var lastStartIndex = sChars.Length - substringChars.Length;

        while (sCharsIndex <= lastStartIndex)
        {
            if (sChars[sCharsIndex] == substringChars[0])
            {
                // potential match checking
                var match = true;
                var offset = 1;
                while (offset < substringChars.Length)
                {
                    if (sChars[sCharsIndex + offset] != substringChars[offset])
                    {
                        match = false;
                        break;
                    }
                    offset++;
                }
                if (match)
                {
                    count++;
                    // if aggressive, just advance to next char in s, otherwise, 
                    // skip past the match just found in s
                    sCharsIndex += aggressiveSearch ? 1 : substringChars.Length;
                }
                else
                {
                    // no match found, just move to next char in s
                    sCharsIndex++;
                }
            }
            else
            {
                // no match at current index, move along
                sCharsIndex++;
            }
        }

        return count;
    }

And here is our revised solution:

    /// <summary>
    /// Counts the number of occurrences of the specified substring within
    /// the current string.
    /// </summary>
    /// <param name="s">The current string.</param>
    /// <param name="substring">The substring we are searching for.</param>
    /// <param name="aggressiveSearch">Indicates whether or not the algorithm 
    /// should be aggressive in its search behavior (see Remarks). Default 
    /// behavior is non-aggressive.</param>
    /// <remarks>This algorithm has two search modes - aggressive and 
    /// non-aggressive. When in aggressive search mode (aggressiveSearch = 
    /// true), the algorithm will try to match at every possible starting 
    /// character index within the string. When false, all subsequent 
    /// character indexes within a substring match will not be evaluated. 
    /// For example, if the string was 'abbbc' and we were searching for 
    /// the substring 'bb', then aggressive search would find 2 matches 
    /// with starting indexes of 1 and 2. Non aggressive search would find 
    /// just 1 match with starting index at 1. After the match was made, 
    /// the non aggressive search would attempt to make it's next match 
    /// starting at index 3 instead of 2.</remarks>
    /// <returns>The count of occurrences of the substring within the string.</returns>
    public static int CountOccurrences(this string s, string substring, 
        bool aggressiveSearch = false)
    {
        // if s or substring is null or empty, substring cannot be found in s
        if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(substring))
            return 0;

        // if the length of substring is greater than the length of s,
        // substring cannot be found in s
        if (substring.Length > s.Length)
            return 0;

        int count = 0, n = 0;
        while ((n = s.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
        {
            if (aggressiveSearch)
                n++;
            else
                n += substring.Length;
            count++;
        }

        return count;
    }

What is Parse/parsing?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.

String tenString = "10"

//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;

//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

To make @Raghavendra's answer more specific:

Once you've downloaded 2 zip files,

copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.

You'll still get the same warning, however, the installation will run completely without generating any errors.

What's the difference between .NET Core, .NET Framework, and Xamarin?

.NET 5 will be a unified version of all .NET variants coming in November 2020, so there will be no need to choose between variants anymore. enter image description here

Stop form refreshing page on submit

Personally I like to validate the form on submit and if there are errors, just return false.

$('form').submit(function() {

    var error;

   if ( !$('input').val() ) {
        error = true
    }

    if (error) {
         alert('there are errors')
         return false
    }

});

http://jsfiddle.net/dfyXY/

Boto3 to download all files from a S3 Bucket

import os
import boto3

#initiate s3 resource
s3 = boto3.resource('s3')

# select bucket
my_bucket = s3.Bucket('my_bucket_name')

# download file into current directory
for s3_object in my_bucket.objects.all():
    # Need to split s3_object.key into path and file name, else it will give error file not found.
    path, filename = os.path.split(s3_object.key)
    my_bucket.download_file(s3_object.key, filename)

Read CSV with Scanner()

I have seen many production problems caused by code not handling quotes ("), newline characters within quotes, and quotes within the quotes; e.g.: "he said ""this""" should be parsed into: he said "this"

Like it was mentioned earlier, many CSV parsing examples out there just read a line, and then break up the line by the separator character. This is rather incomplete and problematic.

For me and probably those who prefer build verses buy (or use somebody else's code and deal with their dependencies), I got down to classic text parsing programming and that worked for me:

/**
 * Parse CSV data into an array of String arrays. It handles double quoted values.
 * @param is input stream
 * @param separator
 * @param trimValues
 * @param skipEmptyLines
 * @return an array of String arrays
 * @throws IOException
 */
public static String[][] parseCsvData(InputStream is, char separator, boolean trimValues, boolean skipEmptyLines)
    throws IOException
{
    ArrayList<String[]> data = new ArrayList<String[]>();
    ArrayList<String> row = new ArrayList<String>();
    StringBuffer value = new StringBuffer();
    int ch = -1;
    int prevCh = -1;
    boolean inQuotedValue = false;
    boolean quoteAtStart = false;
    boolean rowIsEmpty = true;
    boolean isEOF = false;

    while (true)
    {
        prevCh = ch;
        ch = (isEOF) ? -1 : is.read();

        // Handle carriage return line feed
        if (prevCh == '\r' && ch == '\n')
        {
            continue;
        }
        if (inQuotedValue)
        {
            if (ch == -1)
            {
                inQuotedValue = false;
                isEOF = true;
            }
            else
            {
                value.append((char)ch);

                if (ch == '"')
                {
                    inQuotedValue = false;
                }
            }
        }
        else if (ch == separator || ch == '\r' || ch == '\n' || ch == -1)
        {
            // Add the value to the row
            String s = value.toString();

            if (quoteAtStart && s.endsWith("\""))
            {
                s = s.substring(1, s.length() - 1);
            }
            if (trimValues)
            {
                s = s.trim();
            }
            rowIsEmpty = (s.length() > 0) ? false : rowIsEmpty;
            row.add(s);
            value.setLength(0);

            if (ch == '\r' || ch == '\n' || ch == -1)
            {
                // Add the row to the result
                if (!skipEmptyLines || !rowIsEmpty)
                {
                    data.add(row.toArray(new String[0]));
                }
                row.clear();
                rowIsEmpty = true;

                if (ch == -1)
                {
                    break;
                }
            }
        }
        else if (prevCh == '"')
        {
            inQuotedValue = true;
        }
        else
        {
            if (ch == '"')
            {
                inQuotedValue = true;
                quoteAtStart = (value.length() == 0) ? true : false;
            }
            value.append((char)ch);
        }
    }
    return data.toArray(new String[0][]);
}

Unit Test:

String[][] data = parseCsvData(new ByteArrayInputStream("foo,\"\",,\"bar\",\"\"\"music\"\"\",\"carriage\r\nreturn\",\"new\nline\"\r\nnext,line".getBytes()), ',', true, true);
for (int rowIdx = 0; rowIdx < data.length; rowIdx++)
{
    System.out.println(Arrays.asList(data[rowIdx]));
}

generates the output:

[foo, , , bar, "music", carriage
return, new
line]
[next, line]

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

Objective-C and Swift URL encoding

It's called URL encoding. More here.

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
           (CFStringRef)self,
           NULL,
           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
           CFStringConvertNSStringEncodingToEncoding(encoding));
}

Unable to use Intellij with a generated sources folder

The fix

Go to Project Structure - Modules - Source Folders and find the target/generated-sources/antlr4/com/mycompany - click Edit properties and set Package prefix to com.mycompany.

This is exactly the reason why we can set Package prefix on source dirs.


Different but related problem here

Android YouTube app Play Video Intent

You can use the Youtube Android player API to play the video if Youtube app is installed, otherwise just prompt the user to choose from the available web browsers.

if(YouTubeIntents.canResolvePlayVideoIntent(mContext)){
                    mContext.startActivity(YouTubeIntents.createPlayVideoIntent(mContext, mVideoId));
}else {
    Intent webIntent = new Intent(Intent.ACTION_VIEW, 
           Uri.parse("http://www.youtube.com/watch?v=" + mVideoId));

    mContext.startActivity(webIntent);
}

How can I delete a newline if it is the last character in a file?

gawk

   awk '{q=p;p=$0}NR>1{print q}END{ORS = ""; print p}' file

How to read file binary in C#?

Generally, I don't really see a possible way to do this. I've exhausted all of the options that the earlier comments gave you, and they don't seem to work. You could try this:

        `private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "This PC\\Documents";
        openFileDialog1.Filter = "All Files (*.*)|*.*";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Title = "Open a file with code";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string exeCode = string.Empty;
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName))) //Sets a new integer to the BinaryReader
            {
                br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                exeCode = Encoding.UTF8.GetString(br.ReadBytes(1000000000)); //Reads as many bytes as it can from the beginning of the .exe file
            }
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName)))
                br.Close(); //Closes the BinaryReader. Without it, opening the file with any other command will result the error "This file is being used by another process".

            richTextBox1.Text = exeCode;
        }
    }`
  • That's the code for the "Open..." button, but here's the code for the "Save..." button:

    ` private void button2_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog();

        save.Filter = "All Files (*.*)|*.*";
        save.Title = "Save Your Changes";
        save.InitialDirectory = "This PC\\Documents";
        save.FilterIndex = 1;
    
        if (save.ShowDialog() == DialogResult.OK)
        {
    
            using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(save.FileName))) //Sets a new integer to the BinaryReader
            {
                bw.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                bw.Write(richTextBox1.Text);
            }
        }
    }`
    
    • That's the save button. This works fine, but only shows the '!This cannot be run in DOS-Mode!' - Otherwise, if you can fix this, I don't know what to do.

    • My Site

Sending POST data in Android

Method to post data as HTTP request,

public static InputStream callPostService(String Url,
        List<NameValuePair> data) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Url);
    try {
        httppost.setEntity(new UrlEncodedFormEntity(data));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Create pandas Dataframe by appending one row at a time

pandas.DataFrame.append

DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) ? 'DataFrame'

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df.append(df2)

With ignore_index set to True:

df.append(df2, ignore_index=True)

regex to remove all text before a character

The regular expression:

^[^_]*_(.*)$

Then get the part between parenthesis. In perl:

my var = "3.04_somename.jpg";
$var =~ m/^[^_]*_(.*)$/;
my fileName = $1;

In Java:

String var = "3.04_somename.jpg";
String fileName = "";
Pattern pattern = Pattern.compile("^[^_]*_(.*)$");
Matcher matcher = pattern.matcher(var);
if (matcher.matches()) {
    fileName = matcher.group(1);
}

...

Truncate Decimal number not Round Off

A function to truncate an arbitrary number of decimals:

public decimal Truncate(decimal number, int digits)
{
  decimal stepper = (decimal)(Math.Pow(10.0, (double)digits));
  int temp = (int)(stepper * number);
  return (decimal)temp / stepper;
}

Extending the User model with custom fields in Django

Simple and effective approach is models.py

from django.contrib.auth.models import User
class CustomUser(User):
     profile_pic = models.ImageField(upload_to='...')
     other_field = models.CharField()

background-size in shorthand background property (CSS3)

You can do as

 body{
        background:url('equote.png'),url('equote.png');
        background-size:400px 100px,50px 50px;
    }