Programs & Examples On #Commodore

Commonly used name for Commodore Business Machines (CBM), home computer and electronics manufacturer which also housed Commodore International Limited. The Commodore brand was known for the Commodore 64, 128 and Amiga series computers.

How to Compare a long value is equal to Long value

It works as expected,

Try checking IdeOneDemo

 public static void main(String[] args) {
        long a = 1111;
        Long b = 1113l;

        if (a == b) {
            System.out.println("Equals");
        } else {
            System.out.println("not equals");
        }
    }

prints

not equals for me

Use compareTo() to compare Long, == wil not work in all case as far as the value is cached

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

Add below code in to file d:\xampp\apache\conf\extra\httpd-xampp.conf:

<IfModule alias_module>
...
    Alias / "d:/xampp/my/folder/"
    <Directory "d:/xampp/my/folder">
        AllowOverride AuthConfig Limit
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>

Above config can access from http://127.0.0.1/

Note: someone suggest that replace from Require local to Require all granted but not work for me

<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    # Require local
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Unit testing with mockito for constructors

Here is the code to mock this functionality using PowerMockito API.

Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);

You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
    // your testing code
}

Take screenshots in the iOS simulator

Screenshot with device frame

Step - 1 Open quick time player

Step - 2 Tap new screen recording

enter image description here

Step - 3 Select Capture selected window enter image description here

Step - 4 Cursor point on the simulator. It will automatically select the whole simulator like enter image description here

Step - 5 Screenshot will open using preview. save it.

Here is some sample screenshot

enter image description here enter image description here

Custom "confirm" dialog in JavaScript?

Faced with the same problem, I was able to solve it using only vanilla JS, but in an ugly way. To be more accurate, in a non-procedural way. I removed all my function parameters and return values and replaced them with global variables, and now the functions only serve as containers for lines of code - they're no longer logical units.

In my case, I also had the added complication of needing many confirmations (as a parser works through a text). My solution was to put everything up to the first confirmation in a JS function that ends by painting my custom popup on the screen, and then terminating.

Then the buttons in my popup call another function that uses the answer and then continues working (parsing) as usual up to the next confirmation, when it again paints the screen and then terminates. This second function is called as often as needed.

Both functions also recognize when the work is done - they do a little cleanup and then finish for good. The result is that I have complete control of the popups; the price I paid is in elegance.

How can I remove non-ASCII characters but leave periods and spaces using Python?

You can filter all characters from the string that are not printable using string.printable, like this:

>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'

string.printable on my machine contains:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c

EDIT: On Python 3, filter will return an iterable. The correct way to obtain a string back would be:

''.join(filter(lambda x: x in printable, s))

How do you format a Date/Time in TypeScript?

This worked for me

    /**
     * Convert Date type to "YYYY/MM/DD" string 
     * - AKA ISO format?
     * - It's logical and sortable :)
     * - 20200227
     * @param Date eg. new Date()
     * https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd 
     * https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?page=2&tab=active#tab-top
     */
    static DateToYYYYMMDD(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
        return DS
    }

You can certainly add HH:MM something like this...

    static DateToYYYYMMDD_HHMM(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
            + ' ' + ('0' + Date.getHours()).slice(-2)
            + ':' + ('0' + Date.getMinutes()).slice(-2)
        return DS
    }

BATCH file asks for file or folder

echo f | xcopy /s/y J:\"My Name"\"FILES IN TRANSIT"\JOHN20101126\"Missing file"\Shapes.atc C:\"Documents and Settings"\"His name"\"Application Data"\Autodesk\"AutoCAD 2010"\"R18.0"\enu\Support\Shapes.atc

Sonar properties files

You can define a Multi-module project structure, then you can set the configuration for sonar in one properties file in the root folder of your project, (Way #1)

PostgreSQL column 'foo' does not exist

I fixed it by changing the quotation mark (") with apostrophe (') inside Values. For instance:

insert into trucks ("id","datetime") VALUES (862,"10-09-2002 09:15:59");

Becomes this:

insert into trucks ("id","datetime") VALUES (862,'10-09-2002 09:15:59');

Assuming datetime column is VarChar.

Aligning rotated xticklabels with their respective xticks

Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:

import numpy as np
n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]


fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
    label.set_y(label.get_position()[1] - (i % 2) * 0.075)

enter image description here

For more background and alternatives, see this post on my blog

Remove characters except digits from string using Python?

In Python 2.*, by far the fastest approach is the .translate method:

>>> x='aaa12333bb445bb54b5b52'
>>> import string
>>> all=string.maketrans('','')
>>> nodigs=all.translate(all, string.digits)
>>> x.translate(all, nodigs)
'1233344554552'
>>> 

string.maketrans makes a translation table (a string of length 256) which in this case is the same as ''.join(chr(x) for x in range(256)) (just faster to make;-). .translate applies the translation table (which here is irrelevant since all essentially means identity) AND deletes characters present in the second argument -- the key part.

.translate works very differently on Unicode strings (and strings in Python 3 -- I do wish questions specified which major-release of Python is of interest!) -- not quite this simple, not quite this fast, though still quite usable.

Back to 2.*, the performance difference is impressive...:

$ python -mtimeit -s'import string; all=string.maketrans("", ""); nodig=all.translate(all, string.digits); x="aaa12333bb445bb54b5b52"' 'x.translate(all, nodig)'
1000000 loops, best of 3: 1.04 usec per loop
$ python -mtimeit -s'import re;  x="aaa12333bb445bb54b5b52"' 're.sub(r"\D", "", x)'
100000 loops, best of 3: 7.9 usec per loop

Speeding things up by 7-8 times is hardly peanuts, so the translate method is well worth knowing and using. The other popular non-RE approach...:

$ python -mtimeit -s'x="aaa12333bb445bb54b5b52"' '"".join(i for i in x if i.isdigit())'
100000 loops, best of 3: 11.5 usec per loop

is 50% slower than RE, so the .translate approach beats it by over an order of magnitude.

In Python 3, or for Unicode, you need to pass .translate a mapping (with ordinals, not characters directly, as keys) that returns None for what you want to delete. Here's a convenient way to express this for deletion of "everything but" a few characters:

import string

class Del:
  def __init__(self, keep=string.digits):
    self.comp = dict((ord(c),c) for c in keep)
  def __getitem__(self, k):
    return self.comp.get(k)

DD = Del()

x='aaa12333bb445bb54b5b52'
x.translate(DD)

also emits '1233344554552'. However, putting this in xx.py we have...:

$ python3.1 -mtimeit -s'import re;  x="aaa12333bb445bb54b5b52"' 're.sub(r"\D", "", x)'
100000 loops, best of 3: 8.43 usec per loop
$ python3.1 -mtimeit -s'import xx; x="aaa12333bb445bb54b5b52"' 'x.translate(xx.DD)'
10000 loops, best of 3: 24.3 usec per loop

...which shows the performance advantage disappears, for this kind of "deletion" tasks, and becomes a performance decrease.

Launching an application (.EXE) from C#?

Here's a snippet of helpful code:

using System.Diagnostics;

// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments; 
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;


// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
     proc.WaitForExit();

     // Retrieve the app's exit code
     exitCode = proc.ExitCode;
}

There is much more you can do with these objects, you should read the documentation: ProcessStartInfo, Process.

Can I change the Android startActivity() transition animation?

You can simply create a context and do something like below:-

private Context context = this;

And your animation:-

((Activity) context).overridePendingTransition(R.anim.abc_slide_in_bottom,R.anim.abc_slide_out_bottom);

You can use any animation you want.

How to part DATE and TIME from DATETIME in MySQL

Try:

SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`

How do I create a comma-separated list using a SQL query?

To be agnostic, drop back and punt.

Select a.name as a_name, r.name as r_name
  from ApplicationsResource ar, Applications a, Resources r
 where a.id = ar.app_id
   and r.id = ar.resource_id
 order by r.name, a.name;

Now user your server programming language to concatenate a_names while r_name is the same as the last time.

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

  1. delete the bin folder
  2. change the order of librarys
  3. clean and rebuild

worked for me.

C# Iterating through an enum? (Indexing a System.Array)

How about a dictionary list?

Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
    list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}

and of course you can change the dictionary value type to whatever your enum values are.

Replacing NULL and empty string within Select statement

Sounds like you want a view instead of altering actual table data.

Coalesce(NullIf(rtrim(Address.Country),''),'United States')

This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.

Session TimeOut in web.xml

<session-config>
    <session-timeout>-1</session-timeout>
</session-config>

You can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete.

How do I include a JavaScript file in another JavaScript file?

The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.

But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers.

For compatibility with older browsers, build tools like Webpack and Rollup and/or transpilation tools like Babel can be used.

ES6 Modules

ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the --experimental-modules flag, and since at least Node.js v13.8.0 without the flag. To enable "ESM" (vs. Node.js's previous CommonJS-style module system ["CJS"]) you either use "type": "module" in package.json or give the files the extension .mjs. (Similarly, modules written with Node.js's previous CJS module can be named .cjs if your default is ESM.)

Using package.json:

{
    "type": "module"
}

Then module.js:

export function hello() {
  return "Hello";
}

Then main.js:

import { hello } from './module.js';
let val = hello();  // val is "Hello";

Using .mjs, you'd have module.mjs:

export function hello() {
  return "Hello";
}

Then main.mjs:

import { hello } from './module.mjs';
let val = hello();  // val is "Hello";

ECMAScript modules in browsers

Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse. There is no need to use Node.js' .mjs extension; browsers completely ignore file extensions on modules/scripts.

<script type="module">
  import { hello } from './hello.mjs'; // Or it could be simply `hello.js`
  hello('world');
</script>
// hello.mjs -- or it could be simply `hello.js`
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

Read more at https://jakearchibald.com/2017/es-modules-in-browsers/

Dynamic imports in browsers

Dynamic imports let the script load other scripts as needed:

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

Read more at https://developers.google.com/web/updates/2017/11/dynamic-import

Node.js require

The older CJS module style, still widely used in Node.js, is the module.exports/require system.

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.

AJAX Loading

You could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks and security issues.

Fetch Loading

Like Dynamic Imports you can load one or many scripts with a fetch call using promises to control order of execution for script dependencies using the Fetch Inject library:

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

jQuery Loading

The jQuery library provides loading functionality in one line:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

Dynamic Script Loading

You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.

The script can even reside on a different server. Furthermore, the browser evaluates the code. The <script> tag can be injected into either the web page <head>, or inserted just before the closing </body> tag.

Here is an example of how this could work:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its src to the provided URL

    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}

This function will add a new <script> tag to the end of the head section of the page, where the src attribute is set to the URL which is given to the function as the first parameter.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

Detecting when the script has been executed

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)

It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.head;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function:

var myPrettyCode = function() {
   // Here, do whatever you want
};

Then you run all that:

loadScript("my_lovely_script.js", myPrettyCode);

Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line script.async = false;. There's a great article on Javascript loading in general which discusses this.

Source Code Merge/Preprocessing

As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.

Correct way to push into state array

This Code work for me :

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

It is most likely a mismatch between the model class name and the table name as mentioned by 'adrift'. Make these the same or use the example below for when you want to keep the model class name different from the table name (that I did for OAuthMembership). Note that the model class name is OAuthMembership whereas the table name is webpages_OAuthMembership.

Either provide a table attribute to the Model:

[Table("webpages_OAuthMembership")]
public class OAuthMembership

OR provide the mapping by overriding DBContext OnModelCreating:

class webpages_OAuthMembershipEntities : DbContext
{
    protected override void OnModelCreating( DbModelBuilder modelBuilder )
    {
        var config = modelBuilder.Entity<OAuthMembership>();
        config.ToTable( "webpages_OAuthMembership" );            
    }
    public DbSet<OAuthMembership> OAuthMemberships { get; set; }        
}

Newline in JLabel

You can use the MultilineLabel component in the Jide Open Source Components.

http://www.jidesoft.com/products/oss.htm

Download a specific tag with Git

For checking out only a given tag for deployment, I use e.g.:

git clone -b 'v2.0' --single-branch --depth 1 https://github.com/git/git.git

This seems to be the fastest way to check out code from a remote repository if one has only interest in the most recent code instead of in a complete repository. In this way, it resembles the 'svn co' command.

Note: Per the Git manual, passing the --depth flag implies --single-branch by default.

--depth

Create a shallow clone with a history truncated to the specified number of commits. Implies --single-branch unless --no-single-branch is given to fetch the histories near the tips of all branches. If you want to clone submodules shallowly, also pass --shallow-submodules.

How to get name of dataframe column in pyspark?

Python

As @numeral correctly said, column._jc.toString() works fine in case of unaliased columns.

In case of aliased columns (i.e. column.alias("whatever") ) the alias can be extracted, even without the usage of regular expressions: str(column).split(" AS ")[1].split("`")[1] .

I don't know Scala syntax, but I'm sure It can be done the same.

Adding a Method to an Existing Object Instance

Since this question asked for non-Python versions, here's JavaScript:

a.methodname = function () { console.log("Yay, a new method!") }

How to select the comparison of two columns as one column in Oracle

I stopped using DECODE several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN.

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

select a, b, decode(a, b, 'true', 'false') as same
  from t;

     A       B  SAME
------  ------  -----
     1       1  true
     1       0  false
     1          false
  null    null  true  

C# - Print dictionary

My goto is

Console.WriteLine( Serialize(dictionary.ToList() ) );

Make sure you include the package using static System.Text.Json.JsonSerializer;

How do I install a Python package with a .whl file?

There's a slight difference between accessing the .whl file in python2 and python3.In python3 you need to install wheel first and then you can access .whl files.

Python3

pip install wheel

And then by using wheel

wheel unpack some-package.whl

Python2

pip install some-package.whl

Which is faster: multiple single INSERTs or one multiple-row INSERT?

In general the less number of calls to the database the better (meaning faster, more efficient), so try to code the inserts in such a way that it minimizes database accesses. Remember, unless your using a connection pool, each databse access has to create a connection, execute the sql, and then tear down the connection. Quite a bit of overhead!

Is there an effective tool to convert C# code to Java code?

This is off the cuff, but isn't that what Grasshopper was for?

Declaring and using MySQL varchar variables

Looks like you forgot the @ in variable declaration. Also I remember having problems with SET in MySql a long time ago.

Try

DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);

update mypermits 
   set person = @FOO 
 where person = @oldFOO;

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

Git copy changes from one branch to another

Instead of merge, as others suggested, you can rebase one branch onto another:

git checkout BranchB
git rebase BranchA

This takes BranchB and rebases it onto BranchA, which effectively looks like BranchB was branched from BranchA, not master.

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

one time i found this script, this copy folder and files and keep the same structure of the source in the destination, you can make some tries with this.

# Find the source files
$sourceDir="X:\sourceFolder"

# Set the target file
$targetDir="Y:\Destfolder\"
Get-ChildItem $sourceDir -Include *.* -Recurse |  foreach {

    # Remove the original  root folder
    $split = $_.Fullname  -split '\\'
    $DestFile =  $split[1..($split.Length - 1)] -join '\' 

    # Build the new  destination file path
    $DestFile = $targetDir+$DestFile

    # Move-Item won't  create the folder structure so we have to 
    # create a blank file  and then overwrite it
    $null = New-Item -Path  $DestFile -Type File -Force
    Move-Item -Path  $_.FullName -Destination $DestFile -Force
}

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

Add the Git\bin directory to the Path environment variable. The directory is %ProgramFiles%\Git\bin by default. By this way you can access Git Bash with simply typing bash in every terminal including the integrated terminal of Visual Studio Code.

How to set the path and environment variables in Windows

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

swap may not be the red herring previously suggested. How big is the python process in question just before the ENOMEM?

Under kernel 2.6, /proc/sys/vm/swappiness controls how aggressively the kernel will turn to swap, and overcommit* files how much and how precisely the kernel may apportion memory with a wink and a nod. Like your facebook relationship status, it's complicated.

...but swap is actually available on demand (according to the web host)...

but not according to the output of your free(1) command, which shows no swap space recognized by your server instance. Now, your web host may certainly know much more than I about this topic, but virtual RHEL/CentOS systems I've used have reported swap available to the guest OS.

Adapting Red Hat KB Article 15252:

A Red Hat Enterprise Linux 5 system will run just fine with no swap space at all as long as the sum of anonymous memory and system V shared memory is less than about 3/4 the amount of RAM. .... Systems with 4GB of ram or less [are recommended to have] a minimum of 2GB of swap space.

Compare your /proc/sys/vm settings to a plain CentOS 5.3 installation. Add a swap file. Ratchet down swappiness and see if you live any longer.

How to set bootstrap navbar active class with Angular JS?

Here's another solution for anyone who might be interested. The advantage of this is it has fewer dependencies. Heck, it works without a web server too. So it's completely client-side.

HTML:

<nav class="navbar navbar-inverse" ng-controller="topNavBarCtrl"">
<div class="container-fluid">
    <div class="navbar-header">
        <a class="navbar-brand" href="#"><span class="glyphicon glyphicon-home" aria-hidden="true"></span></a>
    </div>
    <ul class="nav navbar-nav">
        <li ng-click="selectTab()" ng-class="getTabClass()"><a href="#">Home</a></li>
        <li ng-repeat="tab in tabs" ng-click="selectTab(tab)" ng-class="getTabClass(tab)"><a href="#">{{ tab }}</a></li>
    </ul>
</div>

Explanation:

Here we are generating the links dynamically from an angularjs model using the directive ng-repeat. Magic happens with the methods selectTab() and getTabClass() defined in the controller for this navbar presented below.

Controller:

angular.module("app.NavigationControllersModule", [])

// Constant named 'activeTab' holding the value 'active'. We will use this to set the class name of the <li> element that is selected.
.constant("activeTab", "active")

.controller("topNavBarCtrl", function($scope, activeTab){
    // Model used for the ng-repeat directive in the template.
    $scope.tabs = ["Page 1", "Page 2", "Page 3"];

    var selectedTab = null;

    // Sets the selectedTab.
    $scope.selectTab = function(newTab){
       selectedTab = newTab;
    };

    // Sets class of the selectedTab to 'active'.
    $scope.getTabClass = function(tab){
       return selectedTab == tab ? activeTab : "";
    };
});

Explanation:

selectTab() method is called using ng-click directive. So when the link is clicked, the variable selectedTab is set to the name of this link. In the HTML you can see that this method is called without any argument for Home tab so that it will be highlighted when the page loads.

The getTabClass() method is called via ng-class directive in the HTML. This method checks if the tab it is in is the same as the value of the selectedTab variable. If true, it returns "active" else returns "" which is applied as the class name by ng-class directive. Then whatever css you have applied to class active will be applied to the selected tab.

What does map(&:name) mean in Ruby?

Another cool shorthand, unknown to many, is

array.each(&method(:foo))

which is a shorthand for

array.each { |element| foo(element) }

By calling method(:foo) we took a Method object from self that represents its foo method, and used the & to signify that it has a to_proc method that converts it into a Proc.

This is very useful when you want to do things point-free style. An example is to check if there is any string in an array that is equal to the string "foo". There is the conventional way:

["bar", "baz", "foo"].any? { |str| str == "foo" }

And there is the point-free way:

["bar", "baz", "foo"].any?(&"foo".method(:==))

The preferred way should be the most readable one.

How to increase font size in a plot in R?

By trial and error, I've determined the following is required to set font size:

  1. cex doesn't work in hist(). Use cex.axis for the numbers on the axes, cex.lab for the labels.
  2. cex doesn't work in axis() either. Use cex.axis for the numbers on the axes.
  3. In place of setting labels using hist(), you can set them using mtext(). You can set the font size using cex, but using a value of 1 actually sets the font to 1.5 times the default!!! You need to use cex=2/3 to get the default font size. At the very least, this is the case under R 3.0.2 for Mac OS X, using PDF output.
  4. You can change the default font size for PDF output using pointsize in pdf().

I suppose it would be far too logical to expect R to (a) actually do what its documentation says it should do, (b) behave in an expected fashion.

Firebase FCM notifications click_action payload

there is dual method for fcm fcm messaging notification and app notification in first your app reciever only message notification with body ,title and you can add color ,vibration not working,sound default. in 2nd you can full control what happen when you recieve message example onMessageReciever(RemoteMessage rMessage){ notification.setContentTitle(rMessage.getData().get("yourKey")); } you will recieve data with(yourKey) but that not from fcm message that from fcm cloud functions reguard

Android RecyclerView addition & removal of items

you must to remove this item from arrayList of data

myDataset.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
notifyItemRangeChanged(holder.getAdapterPosition(), getItemCount());

When using a Settings.settings file in .NET, where is the config actually stored?

It depends on whether the setting you have chosen is at "User" scope or "Application" scope.

User scope

User scope settings are stored in

C:\Documents and Settings\ username \Local Settings\Application Data\ ApplicationName

You can read/write them at runtime.

For Vista and Windows 7, folder is

C:\Users\ username \AppData\Local\ ApplicationName

or

C:\Users\ username \AppData\Roaming\ ApplicationName

Application scope

Application scope settings are saved in AppName.exe.config and they are readonly at runtime.

handling dbnull data in vb.net

   VB.Net
   ========
    Dim da As New SqlDataAdapter
    Dim dt As New DataTable
    Call conecDB()        'Connection to Database
    da.SelectCommand = New SqlCommand("select max(RefNo) from BaseData", connDB)

    da.Fill(dt)

    If dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) = "" Then
        MsgBox("datbase is null")

    ElseIf dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) <> "" Then
        MsgBox("datbase have value")

    End If

Cannot execute script: Insufficient memory to continue the execution of the program

You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.

I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.

(This is the same answer I provided here)

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

PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()

"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"

convert string into array of integers

Better one line solution:

var answerInt = [];
var answerString = "1 2 3 4";
answerString.split(' ').forEach(function (item) {
   answerInt.push(parseInt(item))
});

Converting pixels to dp

private fun toDP(context: Context,value: Int): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
        value.toFloat(),context.resources.displayMetrics).toInt()
}

Force "git push" to overwrite remote files

You want to force push

What you basically want to do is to force push your local branch, in order to overwrite the remote one.

If you want a more detailed explanation of each of the following commands, then see my details section below. You basically have 4 different options for force pushing with Git:

git push <remote> <branch> -f
git push origin master -f # Example

git push <remote> -f
git push origin -f # Example

git push -f

git push <remote> <branch> --force-with-lease

If you want a more detailed explanation of each command, then see my long answers section below.

Warning: force pushing will overwrite the remote branch with the state of the branch that you're pushing. Make sure that this is what you really want to do before you use it, otherwise you may overwrite commits that you actually want to keep.

Force pushing details

Specifying the remote and branch

You can completely specify specific branches and a remote. The -f flag is the short version of --force

git push <remote> <branch> --force
git push <remote> <branch> -f

Omitting the branch

When the branch to push branch is omitted, Git will figure it out based on your config settings. In Git versions after 2.0, a new repo will have default settings to push the currently checked-out branch:

git push <remote> --force

while prior to 2.0, new repos will have default settings to push multiple local branches. The settings in question are the remote.<remote>.push and push.default settings (see below).

Omitting the remote and the branch

When both the remote and the branch are omitted, the behavior of just git push --force is determined by your push.default Git config settings:

git push --force
  • As of Git 2.0, the default setting, simple, will basically just push your current branch to its upstream remote counter-part. The remote is determined by the branch's branch.<remote>.remote setting, and defaults to the origin repo otherwise.

  • Before Git version 2.0, the default setting, matching, basically just pushes all of your local branches to branches with the same name on the remote (which defaults to origin).

You can read more push.default settings by reading git help config or an online version of the git-config(1) Manual Page.

Force pushing more safely with --force-with-lease

Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:

git push <remote> <branch> --force-with-lease

You can learn more details about how to use --force-with-lease by reading any of the following:

How do I hide certain files from the sidebar in Visual Studio Code?

The __pycache__ folder and *.pyc files are totally unnecessary to the developer. To hide these files from the explorer view, we need to edit the settings.json for VSCode. Add the folder and the files as shown below:

"files.exclude": {
  ...
  ...
  "**/*.pyc": {"when": "$(basename).py"}, 
  "**/__pycache__": true,
  ...
  ...
}

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

How do I use typedef and typedef enum in C?

typedef enum state {DEAD,ALIVE} State;
|     | |                     | |   |^ terminating semicolon, required! 
|     | |   type specifier    | |   |
|     | |                     | ^^^^^  declarator (simple name)
|     | |                     |    
|     | ^^^^^^^^^^^^^^^^^^^^^^^  
|     |
^^^^^^^-- storage class specifier (in this case typedef)

The typedef keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern or static is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.

After the above declaration, the State identifier becomes an alias for the type enum state {DEAD,ALIVE}. The declaration also provides that type itself. However that isn't typedef doing it. Any declaration in which enum state {DEAD,ALIVE} appears as a type specifier introduces that type into the scope:

enum state {DEAD, ALIVE} stateVariable;

If enum state has previously been introduced the typedef has to be written like this:

typedef enum state State;

otherwise the enum is being redefined, which is an error.

Like other declarations (except function parameter declarations), the typedef declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:

typedef unsigned long ulong, *ulongptr;
|     | |           | |  1 | |   2   |
|     | |           | |    | ^^^^^^^^^--- "pointer to" declarator
|     | |           | ^^^^^^------------- simple declarator
|     | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier

This typedef introduces two type names ulong and ulongptr, based on the unsigned long type given in the specifier-qualifier list. ulong is just a straight alias for that type. ulongptr is declared as a pointer to unsigned long, thanks to the * syntax, which in this role is a kind of type construction operator which deliberately mimics the unary * for pointer dereferencing used in expressions. In other words ulongptr is an alias for the "pointer to unsigned long" type.

Alias means that ulongptr is not a distinct type from unsigned long *. This is valid code, requiring no diagnostic:

unsigned long *p = 0;
ulongptr q = p;

The variables q and p have exactly the same type.

The aliasing of typedef isn't textual. For instance if user_id_t is a typedef name for the type int, we may not simply do this:

unsigned user_id_t uid;  // error! programmer hoped for "unsigned int uid". 

This is an invalid type specifier list, combining unsigned with a typedef name. The above can be done using the C preprocessor:

#define user_id_t int
unsigned user_id_t uid;

whereby user_id_t is macro-expanded to the token int prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.

Among the disadvantages that it doesn't work well for derived types:

 #define silly_macro int *

 silly_macro not, what, you, think;

This declaration doesn't declare what, you and think as being of type "pointer to int" because the macro-expansion is:

 int * not, what, you, think;

The type specifier is int, and the declarators are *not, what, you and think. So not has the expected pointer type, but the remaining identifiers do not.

And that's probably 99% of everything about typedef and type aliasing in C.

Importing CSV with line breaks in Excel 2007

On MacOS try using Numbers

If you have access to Mac OS I have found that the Apple spreadsheet Numbers does a good job of unpicking a complex multi-line CSV file that Excel could not handle. Just open the .csv with Numbers and then export to Excel.

Hot to get all form elements values using jQuery?

Try this for getting form input text value to JavaScript object...

var fieldPair = {};
$("#form :input").each(function() {
    if($(this).attr("name").length > 0) {
        fieldPair[$(this).attr("name")] = $(this).val();
    }
});

console.log(fieldPair);

How to get values from IGrouping

More clarified version of above answers:

IEnumerable<IGrouping<int, ClassA>> groups = list.GroupBy(x => x.PropertyIntOfClassA);

foreach (var groupingByClassA in groups)
{
    int propertyIntOfClassA = groupingByClassA.Key;

    //iterating through values
    foreach (var classA in groupingByClassA)
    {
        int key = classA.PropertyIntOfClassA;
    }
}

How to create an Array, ArrayList, Stack and Queue in Java?

I am guessing you're confused with the parameterization of the types:

// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>(); 


// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();

What is the difference between print and puts?

A big difference is if you are displaying arrays. Especially ones with NIL. For example:

print [nil, 1, 2]

gives

[nil, 1, 2]

but

puts [nil, 1, 2]

gives

1
2

Note, no appearing nil item (just a blank line) and each item on a different line.

Xampp Access Forbidden php

Did you change any thing on the virtual-host before it stop working ?

Add this line to xampp/apache/conf/extra/httpd-vhosts.conf

<VirtualHost localhost:80>
    DocumentRoot "C:/xampp/htdocs"
    ServerAdmin localhost
    <Directory "C:/xampp/htdocs">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Calculating the area under a curve given a set of coordinates, without knowing the function

The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.

Here's a simple example. In both trapz and simps, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units.

from __future__ import print_function

import numpy as np
from scipy.integrate import simps
from numpy import trapz


# The y values.  A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])

# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)

# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)

Output:

area = 452.5
area = 460.0

WCF named pipe minimal example

Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:

Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:

<configuration>
    <system.serviceModel>
        <services>
            <service name="com.aschneider.examples.wcf.services.EchoService">
                <host>
                    <baseAddresses>
                        <add baseAddress="net.pipe://localhost/EchoService"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors></serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:

<configuration>
    <system.serviceModel>
        <bindings>
            <netNamedPipeBinding>
                <binding name="NetNamedPipeBinding_IEchoService"/>
            </netNamedPipeBinding>
        </bindings>
        <client>
            <endpoint address              = "net.pipe://localhost/EchoService"
                      binding              = "netNamedPipeBinding"
                      bindingConfiguration = "NetNamedPipeBinding_IEchoService"
                      contract             = "EchoServiceReference.IEchoService"
                      name                 = "NetNamedPipeBinding_IEchoService"/>
        </client>
    </system.serviceModel>
</configuration>

The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).

Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

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

I write these 2 functions to make my life easier:

function scrollToTop(elem, parent, speed) {
    var scrollOffset = parent.scrollTop() + elem.offset().top;
    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

function scrollToCenter(elem, parent, speed) {
    var elOffset = elem.offset().top;
    var elHeight = elem.height();
    var parentViewTop = parent.offset().top;
    var parentHeight = parent.innerHeight();
    var offset;

    if (elHeight >= parentHeight) {
        offset = elOffset;
    } else {
        margin = (parentHeight - elHeight)/2;
        offset = elOffset - margin;
    }

    var scrollOffset = parent.scrollTop() + offset - parentViewTop;

    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

And use them:

scrollToTop($innerListItem, $parentDiv, 200);
// or
scrollToCenter($innerListItem, $parentDiv, 200);

How can I control the speed that bootstrap carousel slides in items?

You can use this

<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel" data-interval="4000">

Just add data-interval="1000" where next picture will be after 1 sec.

How do I remove background-image in css?

Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.

http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds

I have not found a solution yet...

How to select specific columns in laravel eloquent

You can use get() as well as all()

ModelName::where('a', 1)->get(['column1','column2']);

Maven Modules + Building a Single Specific Module

You say you "really just want B", but this is false. You want B, but you also want an updated A if there have been any changes to it ("active development").

So, sometimes you want to work with A, B, and C. For this case you have aggregator project P. For the case where you want to work with A and B (but do not want C), you should create aggregator project Q.

Edit 2016: The above information was perhaps relevant in 2009. As of 2016, I highly recommend ignoring this in most cases, and simply using the -am or -pl command-line flags as described in the accepted answer. If you're using a version of maven from before v2.1, change that first :)

What is deserialize and serialize in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.

Say, you have an object:

{foo: [1, 4, 7, 10], bar: "baz"}

serializing into JSON will convert it into a string:

'{"foo":[1,4,7,10],"bar":"baz"}'

which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}.

Access nested dictionary items via a list of keys?

How about check and then set dict element without processing all indexes twice?

Solution:

def nested_yield(nested, keys_list):
    """
    Get current nested data by send(None) method. Allows change it to Value by calling send(Value) next time
    :param nested: list or dict of lists or dicts
    :param keys_list: list of indexes/keys
    """
    if not len(keys_list):  # assign to 1st level list
        if isinstance(nested, list):
            while True:
                nested[:] = yield nested
        else:
            raise IndexError('Only lists can take element without key')


    last_key = keys_list.pop()
    for key in keys_list:
        nested = nested[key]

    while True:
        try:
            nested[last_key] = yield nested[last_key]
        except IndexError as e:
            print('no index {} in {}'.format(last_key, nested))
            yield None

Example workflow:

ny = nested_yield(nested_dict, nested_address)
data_element = ny.send(None)
if data_element:
    # process element
    ...
else:
    # extend/update nested data
    ny.send(new_data_element)
    ...
ny.close()

Test

>>> cfg= {'Options': [[1,[0]],[2,[4,[8,16]]],[3,[9]]]}
    ny = nested_yield(cfg, ['Options',1,1,1])
    ny.send(None)
[8, 16]
>>> ny.send('Hello!')
'Hello!'
>>> cfg
{'Options': [[1, [0]], [2, [4, 'Hello!']], [3, [9]]]}
>>> ny.close()

Why am I getting "Thread was being aborted" in ASP.NET?

This error can be caused by trying to end a response more than once. As other answers already mentioned, there are various methods that will end a response (like Response.End, or Response.Redirect). If you call more than one in a row, you'll get this error.

I came across this error when I tried to use Response.End after using Response.TransmitFile which seems to end the response too.

How can you profile a Python script?

The terminal-only (and simplest) solution, in case all those fancy UI's fail to install or to run:
ignore cProfile completely and replace it with pyinstrument, that will collect and display the tree of calls right after execution.

Install:

$ pip install pyinstrument

Profile and display result:

$ python -m pyinstrument ./prog.py

Works with python2 and 3.

[EDIT] The documentation of the API, for profiling only a part of the code, can be found here.

Regex pattern for numeric values

"[1-9][0-9]*|0"

I'd just use "[0-9]+" to represent positive whole numbers.

Error: class X is public should be declared in a file named X.java

when you named your file WeatherArray.java,maybe you have another file on hard disk ,so you can rename WeatherArray.java as ReWeatherArray.java, then rename ReWeatherArray.java as WeatherArray.java. it will be ok.

How to use the unsigned Integer in Java 8 and Java 9?

Well, even in Java 8, long and int are still signed, only some methods treat them as if they were unsigned. If you want to write unsigned long literal like that, you can do

static long values = Long.parseUnsignedLong("18446744073709551615");

public static void main(String[] args) {
    System.out.println(values); // -1
    System.out.println(Long.toUnsignedString(values)); // 18446744073709551615
}

pypi UserWarning: Unknown distribution option: 'install_requires'

sudo apt-get install python-dev  # for python2.x installs
sudo apt-get install python3-dev  # for python3.x installs

It will install any missing headers. It solved my issue

Differences between C++ string == and compare()?

Internally, string::operator==() is using string::compare(). Please refer to: CPlusPlus - string::operator==()

I wrote a small application to compare the performance, and apparently if you compile and run your code on debug environment the string::compare() is slightly faster than string::operator==(). However if you compile and run your code in Release environment, both are pretty much the same.

FYI, I ran 1,000,000 iteration in order to come up with such conclusion.

In order to prove why in debug environment the string::compare is faster, I went to the assembly and here is the code:

DEBUG BUILD

string::operator==()

        if (str1 == str2)
00D42A34  lea         eax,[str2]  
00D42A37  push        eax  
00D42A38  lea         ecx,[str1]  
00D42A3B  push        ecx  
00D42A3C  call        std::operator==<char,std::char_traits<char>,std::allocator<char> > (0D23EECh)  
00D42A41  add         esp,8  
00D42A44  movzx       edx,al  
00D42A47  test        edx,edx  
00D42A49  je          Algorithm::PerformanceTest::stringComparison_usingEqualOperator1+0C4h (0D42A54h)  

string::compare()

            if (str1.compare(str2) == 0)
00D424D4  lea         eax,[str2]  
00D424D7  push        eax  
00D424D8  lea         ecx,[str1]  
00D424DB  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0D23582h)  
00D424E0  test        eax,eax  
00D424E2  jne         Algorithm::PerformanceTest::stringComparison_usingCompare1+0BDh (0D424EDh)

You can see that in string::operator==(), it has to perform extra operations (add esp, 8 and movzx edx,al)

RELEASE BUILD

string::operator==()

        if (str1 == str2)
008533F0  cmp         dword ptr [ebp-14h],10h  
008533F4  lea         eax,[str2]  
008533F7  push        dword ptr [ebp-18h]  
008533FA  cmovae      eax,dword ptr [str2]  
008533FE  push        eax  
008533FF  push        dword ptr [ebp-30h]  
00853402  push        ecx  
00853403  lea         ecx,[str1]  
00853406  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)  

string::compare()

            if (str1.compare(str2) == 0)
    00853830  cmp         dword ptr [ebp-14h],10h  
    00853834  lea         eax,[str2]  
    00853837  push        dword ptr [ebp-18h]  
    0085383A  cmovae      eax,dword ptr [str2]  
    0085383E  push        eax  
    0085383F  push        dword ptr [ebp-30h]  
    00853842  push        ecx  
00853843  lea         ecx,[str1]  
00853846  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)

Both assembly code are very similar as the compiler perform optimization.

Finally, in my opinion, the performance gain is negligible, hence I would really leave it to the developer to decide on which one is the preferred one as both achieve the same outcome (especially when it is release build).

Example of waitpid() in use?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(2);
        exit(EXIT_SUCCESS);
    }

//Comment from here to...
    //Parent waits process pid (child)
    waitpid(pid, &status, 0);
    //Option is 0 since I check it later

    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
//To Here and see the difference
    printf("Parent: %d\n", getpid());

    return 0;
}

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

How to set different colors in HTML in one statement?

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  color:transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<h2><span class="rainbow">Rainbows are colorful and scalable and lovely</span></h2>
_x000D_
_x000D_
_x000D_

Docker-Compose can't connect to Docker Daemon

I got this error when there were files in the Dockerfile directory that were not accessible by the current user. docker could thus not upload the full context to the daemon and brought the "Couldn't connect to Docker daemon at http+docker://localunixsocket" message.

Adding a favicon to a static HTML page

I know its older post but still posting for someone like me. This worked for me

<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />

put your favicon icon on root directory..

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

How to refresh a page with jQuery by passing a parameter to URL

var singleText = "single";
var s = window.location.search;

if (s.indexOf(singleText) == -1) {
    window.location.href += (s.substring(0,1) == "?") ? "&" : "?" + singleText;
}

Reverse Y-Axis in PyPlot

DisplacedAussie's answer is correct, but usually a shorter method is just to reverse the single axis in question:

plt.scatter(x_arr, y_arr)
ax = plt.gca()
ax.set_ylim(ax.get_ylim()[::-1])

where the gca() function returns the current Axes instance and the [::-1] reverses the list.

How do I execute a file in Cygwin?

When you start in Cygwin you are in the "/home/Administrator" zone, so put your a.exe file there.

Then at the prompt run:

cd a.exe

It will be read in by Cygwin and you will be asked to install it.

Best way to parse command-line parameters?

freecli

package freecli
package examples
package command

import java.io.File

import freecli.core.all._
import freecli.config.all._
import freecli.command.all._

object Git extends App {

  case class CommitConfig(all: Boolean, message: String)
  val commitCommand =
    cmd("commit") {
      takesG[CommitConfig] {
        O.help --"help" ::
        flag --"all" -'a' -~ des("Add changes from all known files") ::
        O.string -'m' -~ req -~ des("Commit message")
      } ::
      runs[CommitConfig] { config =>
        if (config.all) {
          println(s"Commited all ${config.message}!")
        } else {
          println(s"Commited ${config.message}!")
        }
      }
    }

  val rmCommand =
    cmd("rm") {
      takesG[File] {
        O.help --"help" ::
        file -~ des("File to remove from git")
      } ::
      runs[File] { f =>
        println(s"Removed file ${f.getAbsolutePath} from git")
      }
    }

  val remoteCommand =
   cmd("remote") {
     takes(O.help --"help") ::
     cmd("add") {
       takesT {
         O.help --"help" ::
         string -~ des("Remote name") ::
         string -~ des("Remote url")
       } ::
       runs[(String, String)] {
         case (s, u) => println(s"Remote $s $u added")
       }
     } ::
     cmd("rm") {
       takesG[String] {
         O.help --"help" ::
         string -~ des("Remote name")
       } ::
       runs[String] { s =>
         println(s"Remote $s removed")
       }
     }
   }

  val git =
    cmd("git", des("Version control system")) {
      takes(help --"help" :: version --"version" -~ value("v1.0")) ::
      commitCommand ::
      rmCommand ::
      remoteCommand
    }

  val res = runCommandOrFail(git)(args).run
}

This will generate the following usage:

Usage

SQL Greater than, Equal to AND Less Than

Somthing like this should workL

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()

How to sort multidimensional array by column?

Yes. The sorted built-in accepts a key argument:

sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]

note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).

or alternatively,

from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]

Read more on the python wiki.

twitter bootstrap navbar fixed top overlapping site

Further to Nick Bisby's answer, if you get this problem using HAML in rails and you have applied Roberto Barros' fix here:

I replaced the require in the "bootstrap_and_overrides.css" to:

=require twitter-bootstrap-static/bootstrap.css.erb

(See https://github.com/seyhunak/twitter-bootstrap-rails/issues/91)

... you need to put the body CSS before the require statement as follows:

@import "twitter/bootstrap/bootstrap";
body { padding-top: 40px; }
@import "twitter/bootstrap/responsive";
=require twitter-bootstrap-static/bootstrap.css.erb

If the require statement is before the body CSS, it will not take effect.

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

compare two list and return not matching items using linq

You could do something like:

HashSet<int> sentIDs = new HashSet<int>(SentList.Select(s => s.MsgID));

var results = MsgList.Where(m => !sentIDs.Contains(m.MsgID));

This will return all messages in MsgList which don't have a matching ID in SentList.

Input text dialog Android

I found it cleaner and more reusable to extend AlertDialog.Builder to create a custom dialog class. This is for a dialog that asks the user to input a phone number. A preset phone number can also be supplied by calling setNumber() before calling show().

InputSenderDialog.java

public class InputSenderDialog extends AlertDialog.Builder {

    public interface InputSenderDialogListener{
        public abstract void onOK(String number);
        public abstract void onCancel(String number);
    }

    private EditText mNumberEdit;

    public InputSenderDialog(Activity activity, final InputSenderDialogListener listener) {
        super( new ContextThemeWrapper(activity, R.style.AppTheme) );

        @SuppressLint("InflateParams") // It's OK to use NULL in an AlertDialog it seems...
        View dialogLayout = LayoutInflater.from(activity).inflate(R.layout.dialog_input_sender_number, null);
        setView(dialogLayout);

        mNumberEdit = dialogLayout.findViewById(R.id.numberEdit);

        setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onOK(String.valueOf(mNumberEdit.getText()));

            }
        });

        setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onCancel(String.valueOf(mNumberEdit.getText()));
            }
        });
    }

    public InputSenderDialog setNumber(String number){
        mNumberEdit.setText( number );
        return this;
    }

    @Override
    public AlertDialog show() {
        AlertDialog dialog = super.show();
        Window window = dialog.getWindow();
        if( window != null )
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        return dialog;
    }
}

dialog_input_sender_number.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="10dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:paddingBottom="20dp"
        android:text="Input phone number"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <TextView
        android:id="@+id/numberLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/title"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Phone number" />

    <EditText
        android:id="@+id/numberEdit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/numberLabel"
        app:layout_constraintLeft_toLeftOf="parent"
        android:inputType="phone" >
        <requestFocus />
    </EditText>

</android.support.constraint.ConstraintLayout>

Usage:

new InputSenderDialog(getActivity(), new InputSenderDialog.InputSenderDialogListener() {
    @Override
    public void onOK(final String number) {
        Log.d(TAG, "The user tapped OK, number is "+number);
    }

    @Override
    public void onCancel(String number) {
        Log.d(TAG, "The user tapped Cancel, number is "+number);
    }
}).setNumber(someNumberVariable).show();

How to round a Double to the nearest Int in swift?

A very easy solution worked for me:

  if (62 % 50 != 0) {
      var number = 62 / 50 + 1 // adding 1 is doing the actual "round up"
  }

number contains value 2

How to copy from CSV file to PostgreSQL table with headers in CSV file?

You can use d6tstack which creates the table for you and is faster than pd.to_sql() because it uses native DB import commands. It supports Postgres as well as MYSQL and MS SQL.

import pandas as pd
df = pd.read_csv('table.csv')
uri_psql = 'postgresql+psycopg2://usr:pwd@localhost/db'
d6tstack.utils.pd_to_psql(df, uri_psql, 'table')

It is also useful for importing multiple CSVs, solving data schema changes and/or preprocess with pandas (eg for dates) before writing to db, see further down in examples notebook

d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'), 
    apply_after_read=apply_fun).to_psql_combine(uri_psql, 'table')

Find and Replace string in all files recursive using grep and sed

The GNU guys REALLY messed up when they introduced recursive file searching to grep. grep is for finding REs in files and printing the matching line (g/re/p remember?) NOT for finding files. There's a perfectly good tool with a very obvious name for FINDing files. Whatever happened to the UNIX mantra of do one thing and do it well?

Anyway, here's how you'd do what you want using the traditional UNIX approach (untested):

find /path/to/folder -type f -print |
while IFS= read -r file
do
   awk -v old="$oldstring" -v new="$newstring" '
      BEGIN{ rlength = length(old) }
      rstart = index($0,old) { $0 = substr($0,rstart-1) new substr($0,rstart+rlength) }
      { print }
   ' "$file" > tmp &&
   mv tmp "$file"
done

Not that by using awk/index() instead of sed and grep you avoid the need to escape all of the RE metacharacters that might appear in either your old or your new string plus figure out a character to use as your sed delimiter that can't appear in your old or new strings, and that you don't need to run grep since the replacement will only occur for files that do contain the string you want. Having said all of that, if you don't want the file timestamp to change if you don't modify the file, then just do a diff on tmp and the original file before doing the mv or throw in an fgrep -q before the awk.

Caveat: The above won't work for file names that contain newlines. If you have those then let us know and we can show you how to handle them.

How to skip "are you sure Y/N" when deleting files in batch files

Use del /F /Q to force deletion of read-only files (/F) and directories and not ask to confirm (/Q) when deleting via wildcard.

Change one value based on another value in pandas

The original question addresses a specific narrow use case. For those who need more generic answers here are some examples:

Creating a new column using data from other columns

Given the dataframe below:

import pandas as pd
import numpy as np

df = pd.DataFrame([['dog', 'hound', 5],
                   ['cat', 'ragdoll', 1]],
                  columns=['animal', 'type', 'age'])

In[1]:
Out[1]:
  animal     type  age
----------------------
0    dog    hound    5
1    cat  ragdoll    1

Below we are adding a new description column as a concatenation of other columns by using the + operation which is overridden for series. Fancy string formatting, f-strings etc won't work here since the + applies to scalars and not 'primitive' values:

df['description'] = 'A ' + df.age.astype(str) + ' years old ' \
                    + df.type + ' ' + df.animal

In [2]: df
Out[2]:
  animal     type  age                description
-------------------------------------------------
0    dog    hound    5    A 5 years old hound dog
1    cat  ragdoll    1  A 1 years old ragdoll cat

We get 1 years for the cat (instead of 1 year) which we will be fixing below using conditionals.

Modifying an existing column with conditionals

Here we are replacing the original animal column with values from other columns, and using np.where to set a conditional substring based on the value of age:

# append 's' to 'age' if it's greater than 1
df.animal = df.animal + ", " + df.type + ", " + \
    df.age.astype(str) + " year" + np.where(df.age > 1, 's', '')

In [3]: df
Out[3]:
                 animal     type  age
-------------------------------------
0   dog, hound, 5 years    hound    5
1  cat, ragdoll, 1 year  ragdoll    1

Modifying multiple columns with conditionals

A more flexible approach is to call .apply() on an entire dataframe rather than on a single column:

def transform_row(r):
    r.animal = 'wild ' + r.type
    r.type = r.animal + ' creature'
    r.age = "{} year{}".format(r.age, r.age > 1 and 's' or '')
    return r

df.apply(transform_row, axis=1)

In[4]:
Out[4]:
         animal            type      age
----------------------------------------
0    wild hound    dog creature  5 years
1  wild ragdoll    cat creature   1 year

In the code above the transform_row(r) function takes a Series object representing a given row (indicated by axis=1, the default value of axis=0 will provide a Series object for each column). This simplifies processing since we can access the actual 'primitive' values in the row using the column names and have visibility of other cells in the given row/column.

How do I add Git version control (Bitbucket) to an existing source code folder?

Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:

  1. Suppose you have your project folder on PC;
  2. Create a new repository on bitbucket: enter image description here

  3. Press on I have an existing project: enter image description here

  4. Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)

  5. Type command git init

  6. Type command git add --all

  7. Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO)

  8. Type command git commit -m "my first commit"

  9. Type command git push -u origin master

Note: if you get error unable to detect email or name, just type following commands after 5th step:

 git config --global user.email "yourEmail"  #your email at Bitbucket
 git config --global user.name "yourName"  #your name at Bitbucket

how to get javaScript event source element?

You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

jquery can't get data attribute value

jQuery's data() method will give you access to data-* attributes, BUT, it clobbers the case of the attribute name. You can either use this:

$('#myButton').data("x10") // note the lower case

Or, you can use the attr() method, which preserves your case:

$('#myButton').attr("data-X10")

Try both methods here: http://jsfiddle.net/q5rbL/

Be aware that these approaches are not completely equivalent. If you will change the data-* attribute of an element, you should use attr(). data() will read the value once initially, then continue to return a cached copy, whereas attr() will re-read the attribute each time.

Note that jQuery will also convert hyphens in the attribute name to camel case (source -- i.e. data-some-data == $(ele).data('someData')). Both of these conversions are in conformance with the HTML specification, which dictates that custom data attributes should contain no uppercase letters, and that hyphens will be camel-cased in the dataset property (source). jQuery's data method is merely mimicking/conforming to this standard behavior.

Documentation

How to find all occurrences of a substring?

this is an old thread but i got interested and wanted to share my solution.

def find_all(a_string, sub):
    result = []
    k = 0
    while k < len(a_string):
        k = a_string.find(sub, k)
        if k == -1:
            return result
        else:
            result.append(k)
            k += 1 #change to k += len(sub) to not search overlapping results
    return result

It should return a list of positions where the substring was found. Please comment if you see an error or room for improvment.

TypeError: Router.use() requires middleware function but got a Object

If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes);

with

app.use(app.router);
routes.initialize(app);

Please click here to get more details about app.router

Note:

app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For me this setting was working.
In my windows 8.1 the path for php7 is

C:\user\test\tools\php7\php.exe

settings.json

 {  
 "php.executablePath":"/user/test/tools/php7/php.exe",
 "php.validate.executablePath": "/user/test/tools/php7/php.exe"
 }

see also https://github.com/microsoft/vscode/issues/533

How can I use SUM() OVER()

Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID.

To obtain running totals with SUM() OVER (), you need to add an ORDER BY sub-clause after PARTITION BY …, like this:

SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)

But remember, not all database systems support ORDER BY in the OVER clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)

How to convert Integer to int?

Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.

How do I do pagination in ASP.NET MVC?

Controller

 [HttpGet]
    public async Task<ActionResult> Index(int page =1)
    {
        if (page < 0 || page ==0 )
        {
            page = 1;
        }
        int pageSize = 5;
        int totalPage = 0;
        int totalRecord = 0;
        BusinessLayer bll = new BusinessLayer();
        MatchModel matchmodel = new MatchModel();
        matchmodel.GetMatchList = bll.GetMatchCore(page, pageSize, out totalRecord, out totalPage);
        ViewBag.dbCount = totalPage;
        return View(matchmodel);
    }

BusinessLogic

  public List<Match> GetMatchCore(int page, int pageSize, out int totalRecord, out int totalPage)
    {
        SignalRDataContext db = new SignalRDataContext();
        var query = new List<Match>();
        totalRecord = db.Matches.Count();
        totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
        query = db.Matches.OrderBy(a => a.QuestionID).Skip(((page - 1) * pageSize)).Take(pageSize).ToList();
        return query;
    }

View for displaying total page count

 if (ViewBag.dbCount != null)
    {
        for (int i = 1; i <= ViewBag.dbCount; i++)
        {
            <ul class="pagination">
                <li>@Html.ActionLink(@i.ToString(), "Index", "Grid", new { page = @i },null)</li> 
            </ul>
        }
    }

C function that counts lines in file

Here is complete implementation in C/C++

#include <stdio.h>

void lineCount(int argc,char **argv){

        if(argc < 2){
             fprintf(stderr,"File required");
             return;
        }
        FILE *fp = fopen(argv[1],"r");



        if(!fp){
            fprintf(stderr,"Error in opening file");
            return ;      
        }

        int count = 1; //if a file open ,be it empty, it has atleast a newline char
        char temp;

        while(fscanf(fp,"%c",&temp) != -1){
                if(temp == 10) count++;
        }

        fprintf(stdout,"File has %d lines\n",count);
   }

int main(int argc,char **argv){

        lineCount(argc,argv);
        return 0;
}
https://github.com/KotoJallow/Line-Count/blob/master/lineCount.c

How to know if two arrays have the same values

I have another way based on the accepted answer.

function compareArrays(array1, array2) {

    if (
        !Array.isArray(array1)
        || !Array.isArray(array2)
        || array1.length !== array2.length
    ) return false;

    var first = array1.sort().map(value => (String(value))).join();
    var second = array2.sort().map(value => (String(value))).join();

    return first == second ? true : false;
}

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

how to insert value into DataGridView Cell?

You can use this function if you want to add the data into database, with a button. I hope it will help.

// dgvBill is name of DataGridView

string StrQuery;
try
{
    using (SqlConnection conn = new SqlConnection(ConnectingString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
            comm.Connection = conn;
            conn.Open();
            for (int i = 0; i < dgvBill.Rows.Count; i++) 
            {
                StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price,  total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
                comm.CommandText = StrQuery;
                comm.ExecuteNonQuery();         
             }
         }
     }
 }
 catch (Exception err)
 {
     MessageBox.Show(err.Message  , "Error !");
 }

When is it appropriate to use C# partial classes?

The main use for partial classes is with generated code. If you look at the WPF (Windows Presentation Foundation) network, you define your UI with markup (XML). That markup is compiled into partial classes. You fill in code with partial classes of your own.

How to insert array of data into mysql using php

I would avoid to do a query for each entry.

if(is_array($EMailArr)){

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";

    $valuesArr = array();
    foreach($EMailArr as $row){

        $R_ID = (int) $row['R_ID'];
        $email = mysql_real_escape_string( $row['email'] );
        $name = mysql_real_escape_string( $row['name'] );

        $valuesArr[] = "('$R_ID', '$email', '$name')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}

Variables within app.config/web.config

I would suggest you DslConfig. With DslConfig you can use hierarchical config files from Global Config, Config per server host to config per application on each server host (see the AppSpike).
If this is to complicated for you you can just use the global config Variables.var
Just configure in Varibales.var

baseDir = "C:\MyBase"
Var["MyBaseDir"] = baseDir
Var["Dir1"] = baseDir + "\Dir1"
Var["Dir2"] = baseDir + "\Dir2"

And get the config values with

Configuration config = new DslConfig.BooDslConfiguration()
config.GetVariable<string>("MyBaseDir")
config.GetVariable<string>("Dir1")
config.GetVariable<string>("Dir2")

Convert json data to a html table

Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.

Example:

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${age}"}
        ]}
    ]}
]};

var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];

$('#target_div').html(json2html.transform(data,transform));

How does functools partial do what it does?

In my opinion, it's a way to implement currying in python.

from functools import partial
def add(a,b):
    return a + b

def add2number(x,y,z):
    return x + y + z

if __name__ == "__main__":
    add2 = partial(add,2)
    print("result of add2 ",add2(1))
    add3 = partial(partial(add2number,1),2)
    print("result of add3",add3(1))

The result is 3 and 4.

How does one Display a Hyperlink in React Native App?

Another helpful note to add to the above responses is to add some flexbox styling. This will keep the text on one line and will make sure the text doesn't overlap the screen.

 <View style={{ display: "flex", flexDirection: "row", flex: 1, flexWrap: 'wrap', margin: 10 }}>
  <Text>Add your </Text>
  <TouchableOpacity>
    <Text style={{ color: 'blue' }} onpress={() => Linking.openURL('https://www.google.com')} >
         link
    </Text>
   </TouchableOpacity>
   <Text>here.
   </Text>
 </View>

Python - add PYTHONPATH during command line module run

This is for windows:

For example, I have a folder named "mygrapher" on my desktop. Inside, there's folders called "calculation" and "graphing" that contain Python files that my main file "grapherMain.py" needs. Also, "grapherMain.py" is stored in "graphing". To run everything without moving files, I can make a batch script. Let's call this batch file "rungraph.bat".

@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal

This script is located in "mygrapher". To run things, I would get into my command prompt, then do:

>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)

Difference between classification and clustering in data mining?

+Classification: you are given some new data, you have to set new label for them.

For example, a company wants to classify their prospect customers. When a new customer comes, they have to determine if this is a customer who is going to buy their products or not.

+Clustering: you're given a set of history transactions which recorded who bought what.

By using clustering techniques, you can tell the segmentation of your customers.

Where is body in a nodejs http.get response?

Needle module is also good, here is an example which uses needle module

var needle = require('needle');

needle.get('http://www.google.com', function(error, response) {
  if (!error && response.statusCode == 200)
    console.log(response.body);
});

How can I scroll a div to be visible in ReactJS?

Another example which uses function in ref rather than string

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items:[], index: 0 };
    this._nodes = new Map();

    this.handleAdd = this.handleAdd.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
   }

  handleAdd() {
    let startNumber = 0;
    if (this.state.items.length) {
      startNumber = this.state.items[this.state.items.length - 1];
    }

    let newItems = this.state.items.splice(0);
    for (let i = startNumber; i < startNumber + 100; i++) {
      newItems.push(i);
    }

    this.setState({ items: newItems });
  }

  handleRemove() {
    this.setState({ items: this.state.items.slice(1) });
  }

  handleShow(i) {
    this.setState({index: i});
    const node = this._nodes.get(i);
    console.log(this._nodes);
    if (node) {
      ReactDOM.findDOMNode(node).scrollIntoView({block: 'end', behavior: 'smooth'});
    }
  }

  render() {
    return(
      <div>
        <ul>{this.state.items.map((item, i) => (<Item key={i} ref={(element) => this._nodes.set(i, element)}>{item}</Item>))}</ul>
        <button onClick={this.handleShow.bind(this, 0)}>0</button>
        <button onClick={this.handleShow.bind(this, 50)}>50</button>
        <button onClick={this.handleShow.bind(this, 99)}>99</button>
        <button onClick={this.handleAdd}>Add</button>
        <button onClick={this.handleRemove}>Remove</button>
        {this.state.index}
      </div>
    );
  }
}

class Item extends React.Component
{
  render() {
    return (<li ref={ element => this.listItem = element }>
      {this.props.children}
    </li>);
  }
}

Demo: https://codepen.io/anon/pen/XpqJVe

Oracle TNS names not showing when adding new connection to SQL Developer

None of the above changes made any difference in my case. I could run TNS_PING in the command window but SQL Developer couldn't figure out where tnsnames.ora was.

The issue in my case (Windows 7 - 64 bit - Enterprise ) was that the Oracle installer pointed the Start menu shortcut to the wrong version of SQL Developer. There appear to be three SQL Developer instances that accompany the installer. One is in %ORACLE_HOME%\client_1\sqldeveloper\ and two are in %ORACLE_HOME%\client_1\sqldeveloper\bin\ .

The installer installed a start menu shortcut that pointed at a version in the bin directory that simply did not function. It would ask for a password every time I started SQL Developer, not remember choices I had made and displayed a blank list when I chose TNS as the connection mechanism. It also does not have the TNS Directory field in the Database advanced settings referenced in other posts.

I tossed the old Start shortcut and installed a shortcut to %ORACLE_HOME%\client_1\sqldeveloper\sqldeveloper.exe . That change fixed the problem in my case.

Compile/run assembler in Linux?

The assembler(GNU) is as(1)

How to limit file upload type file size in PHP?

If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:

`upload_max_filesize = 2M` `post_max_size = 2M`

that will set the maximum upload limit to 2 MB

How to search images from private 1.0 registry in docker?

So I know this is a rapidly changing field but (as of 2015-09-08) I found the following in the Docker Registry HTTP API V2:

Listing Repositories (link)

GET /v2/_catalog

Listing Image Tags (link)

GET /v2/<name>/tags/list

Based on that the following worked for me on a local registry (registry:2 IMAGE ID 1e847b14150e365a95d76a9cc6b71cd67ca89905e3a0400fa44381ecf00890e1 created on 2015-08-25T07:55:17.072):

$ curl -X GET http://localhost:5000/v2/_catalog
{"repositories":["ubuntu"]}
$ curl -X GET http://localhost:5000/v2/ubuntu/tags/list
{"name":"ubuntu","tags":["latest"]}

jquery clear input default value

Unless you're really worried about older browsers, you could just use the new html5 placeholder attribute like so:

<input type="text" name="email" placeholder="Email address" class="input" />

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

How do you properly use namespaces in C++?

To avoid saying everything Mark Ingram already said a little tip for using namespaces:

Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.

I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.

Sometimes namespaces are used in bigger C++ projects to hide implementation details.

Additional note to the using directive: Some people prefer using "using" just for single elements:

using std::cout;  
using std::endl;

Should I put #! (shebang) in Python scripts, and what form should it take?

It's really just a matter of taste. Adding the shebang means people can invoke the script directly if they want (assuming it's marked as executable); omitting it just means python has to be invoked manually.

The end result of running the program isn't affected either way; it's just options of the means.

CSS: Auto resize div to fit container width

CSS auto-fit container between float:left & float:right divs solved my problem, thanks for your comments.

#left
{
    width:200px;
    float:left;
    background-color:antiquewhite;
    margin-left:10px;
}
#content
{
    overflow:hidden;
    margin-left:10px;
    background-color:AppWorkspace;
}

Regex (grep) for multi-line search needed

Your fundamental problem is that grep works one line at a time - so it cannot find a SELECT statement spread across lines.

Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.

I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.

In outline, for a single file:

$/ = "\n\n";    # Paragraphs

while (<>)
{
     if ($_ =~ m/SELECT.*customerName.*FROM/mi)
     {
         printf file name
         go to next file
     }
}

That needs to be wrapped into a sub that is then invoked by the methods of File::Find.

How do I extract the contents of an rpm?

Sometimes you can encounter an issue with intermediate RPM archive:

cpio: Malformed number
cpio: Malformed number
cpio: Malformed number
. . .
cpio: premature end of archive

That means it could be packed, these days it is LZMA2 compression as usual, by xz:

rpm2cpio <file>.rpm | xz -d | cpio -idmv

otherwise you could try:

rpm2cpio <file>.rpm | lzma -d | cpio -idmv

Import a module from a relative path

The quick-and-dirty way for Linux users

If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module.

ln -s (path)/module_name.py

or

ln -s (path)/package_name

Note: A "module" is any file with a .py extension and a "package" is any folder that contains the file __init__.py (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained "definitions and statements" as requested via the import command.

See: http://docs.python.org/2/tutorial/modules.html

How to extract epoch from LocalDate and LocalDateTime?

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.

LocalDate

LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();

LocalDateTime

LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();

Twitter bootstrap hide element on small devices

Bootstrap 4

The display (hidden/visible) classes are changed in Bootstrap 4. To hide on the xs viewport use:

d-none d-sm-block

Also see: Missing visible-** and hidden-** in Bootstrap v4


Bootstrap 3 (original answer)

Use the hidden-xs utility class..

<nav class="col-sm-3 hidden-xs">
        <ul class="list-unstyled">
        <li>Text 10</li>
        <li>Text 11</li>
        <li>Text 12</li>
        </ul>
</nav>

http://bootply.com/90722

Spring's overriding bean

Question was more about XML but as annotation are more popular nowadays and it works similarly I'll show by example. Let's create class Foo:

public class Foo {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

and two Configuration files (you can't create one):

@Configuration
public class Configuration1 {
    @Bean
    public Foo foo() {
        Foo foo = new Foo();
        foo.setName("configuration1");
        return foo;
    }
}

and

@Configuration
public class Configuration2 {
    @Bean
    public Foo foo() {
        Foo foo = new Foo();
        foo.setName("configuration2");
        return foo;
    }
}

and let's see what happens when calling foo.getName():

@SpringBootApplication
public class OverridingBeanDefinitionsApplication {

    public static void main(String[] args) {
        SpringApplication.run(OverridingBeanDefinitionsApplication.class, args);

        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(
                        Configuration1.class, Configuration2.class);

        Foo foo = applicationContext.getBean(Foo.class);
        System.out.println(foo.getName());
    }
}

in this example result is: configuration2. The Spring Container gets all configuration metadata sources and merges bean definitions in those sources. In this example there are two @Beans. Order in which they are fed into ApplicationContext decide. You can flip new AnnotationConfigApplicationContext(Configuration2.class, Configuration1.class); and result will be configuration1.

How to check the exit status using an if statement

For the record, if the script is run with set -e (or #!/bin/bash -e) and you therefore cannot check $? directly (since the script would terminate on any return code other than zero), but want to handle a specific code, @gboffis comment is great:

/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
   ...

How to add items to a spinner in Android?

Add a spinner to the XML layout, and then add this code to the Java file:

Spinner spinner;
spinner = (Spinner) findViewById(R.id.spinner1) ;
java.util.ArrayList<String> strings = new java.util.ArrayList<>();
strings.add("Mobile") ;
strings.add("Home");
strings.add("Work");
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(AddMember.this, R.layout.support_simple_spinner_dropdown_item, strings);
spinner.setAdapter(spinnerAdapter);

JSON Post with Customized HTTPHeader Field

I tried as you mentioned, but only first parameter is going through and rest all are appearing in the server as undefined. I am passing JSONWebToken as part of header.

.ajax({
    url: 'api/outletadd',
    type: 'post',
    data: { outletname:outletname , addressA:addressA , addressB:addressB, city:city , postcode:postcode , state:state , country:country , menuid:menuid },
    headers: {
        authorization: storedJWT
    },
    dataType: 'json',
    success: function (data){
        alert("Outlet Created");
    },
    error: function (data){
        alert("Outlet Creation Failed, please try again.");        
    }

    });

Access Https Rest Service using Spring RestTemplate

You need to configure a raw HttpClient with SSL support, something like this:

@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() 
throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient
      = HttpClients.custom()
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory 
      = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    ResponseEntity<String> response 
      = new RestTemplate(requestFactory).exchange(
      urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

font: Baeldung

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

Edit: Unfortunately, as of PHP 8.0, the answer is not "No, not anymore". This RFC was not accepted as I hoped, proposing to change T_PAAMAYIM_NEKUDOTAYIM to T_DOUBLE_COLON; but it was declined.

Note: I keep this answer for historical purposes. Actually, because of the creation of the RFC and the votes ratio at some point, I created this answer. Also, I keep this for hoping it to be accepted in the near future.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

You cannot play a video inside a view. It has to be played fullscreen.

Getting the current date in visual Basic 2008

Dim regDate As Date = Date.Now.date

This should fix your problem, though it's 2 years old!

How does Spring autowire by name when more than one matching bean is found?

You can use the @Qualifier annotation

From here

Fine-tuning annotation-based autowiring with qualifiers

Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:

class Main {
    private Country country;
    @Autowired
    @Qualifier("country")
    public void setCountry(Country country) {
        this.country = country;
    }
}

This will use the UK add an id to USA bean and use that if you want the USA.

How can I get new selection in "select" in Angular 2?

use selectionChange in angular 6 and above. example (selectionChange)= onChange($event.value)

git status shows modifications, git checkout -- <file> doesn't remove them

Try doing a

git checkout -f

That should clear all the changes in the current working local repo

How do I count cells that are between two numbers in Excel?

Example-

For cells containing the values between 21-31, the formula is:

=COUNTIF(M$7:M$83,">21")-COUNTIF(M$7:M$83,">31")

How to set value of input text using jQuery

In pure js it will be simpler

EmployeeId.value = 'fgg';

_x000D_
_x000D_
EmployeeId.value = 'fgg';
_x000D_
<div class="editor-label">_x000D_
  <label for="EmployeeId">Employee Number</label>_x000D_
</div>_x000D_
_x000D_
<div class="editor-field textBoxEmployeeNumber">_x000D_
  <input class="text-box single-line" data-val="true" data-val-number="The field EmployeeId must be a number." data-val-required="The EmployeeId field is required." id="EmployeeId" name="EmployeeId" type="text" value="" />_x000D_
  _x000D_
  <span class="field-validation-valid" data-valmsg-for="EmployeeId" data-valmsg-replace="true"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SHA512 vs. Blowfish and Bcrypt

It should suffice to say whether bcrypt or SHA-512 (in the context of an appropriate algorithm like PBKDF2) is good enough. And the answer is yes, either algorithm is secure enough that a breach will occur through an implementation flaw, not cryptanalysis.

If you insist on knowing which is "better", SHA-512 has had in-depth reviews by NIST and others. It's good, but flaws have been recognized that, while not exploitable now, have led to the the SHA-3 competition for new hash algorithms. Also, keep in mind that the study of hash algorithms is "newer" than that of ciphers, and cryptographers are still learning about them.

Even though bcrypt as a whole hasn't had as much scrutiny as Blowfish itself, I believe that being based on a cipher with a well-understood structure gives it some inherent security that hash-based authentication lacks. Also, it is easier to use common GPUs as a tool for attacking SHA-2–based hashes; because of its memory requirements, optimizing bcrypt requires more specialized hardware like FPGA with some on-board RAM.


Note: bcrypt is an algorithm that uses Blowfish internally. It is not an encryption algorithm itself. It is used to irreversibly obscure passwords, just as hash functions are used to do a "one-way hash".

Cryptographic hash algorithms are designed to be impossible to reverse. In other words, given only the output of a hash function, it should take "forever" to find a message that will produce the same hash output. In fact, it should be computationally infeasible to find any two messages that produce the same hash value. Unlike a cipher, hash functions aren't parameterized with a key; the same input will always produce the same output.

If someone provides a password that hashes to the value stored in the password table, they are authenticated. In particular, because of the irreversibility of the hash function, it's assumed that the user isn't an attacker that got hold of the hash and reversed it to find a working password.

Now consider bcrypt. It uses Blowfish to encrypt a magic string, using a key "derived" from the password. Later, when a user enters a password, the key is derived again, and if the ciphertext produced by encrypting with that key matches the stored ciphertext, the user is authenticated. The ciphertext is stored in the "password" table, but the derived key is never stored.

In order to break the cryptography here, an attacker would have to recover the key from the ciphertext. This is called a "known-plaintext" attack, since the attack knows the magic string that has been encrypted, but not the key used. Blowfish has been studied extensively, and no attacks are yet known that would allow an attacker to find the key with a single known plaintext.

So, just like irreversible algorithms based cryptographic digests, bcrypt produces an irreversible output, from a password, salt, and cost factor. Its strength lies in Blowfish's resistance to known plaintext attacks, which is analogous to a "first pre-image attack" on a digest algorithm. Since it can be used in place of a hash algorithm to protect passwords, bcrypt is confusingly referred to as a "hash" algorithm itself.

Assuming that rainbow tables have been thwarted by proper use of salt, any truly irreversible function reduces the attacker to trial-and-error. And the rate that the attacker can make trials is determined by the speed of that irreversible "hash" algorithm. If a single iteration of a hash function is used, an attacker can make millions of trials per second using equipment that costs on the order of $1000, testing all passwords up to 8 characters long in a few months.

If however, the digest output is "fed back" thousands of times, it will take hundreds of years to test the same set of passwords on that hardware. Bcrypt achieves the same "key strengthening" effect by iterating inside its key derivation routine, and a proper hash-based method like PBKDF2 does the same thing; in this respect, the two methods are similar.

So, my recommendation of bcrypt stems from the assumptions 1) that a Blowfish has had a similar level of scrutiny as the SHA-2 family of hash functions, and 2) that cryptanalytic methods for ciphers are better developed than those for hash functions.

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

you seem to have not created an main method, which should probably look something like this (i am not sure)

  class RunThis
{
    public static void main(String[] args)
    {

    Calculate answer = new Calculate();
    answer.getNumber1();
    answer.getNumber2();
    answer.setNumber(answer.getNumber1() , answer.getNumber2());
    answer.getOper();
    answer.setOper(answer.getOper());
    answer.getAnswer();
    }
}

the point is you should have created a main method under some class and after compiling you should run the .class file containing main method. In this case the main method is under RunThis i.e RunThis.class.

I am new to java this may or may not be the right answer, correct me if i am wrong

Can we have multiple "WITH AS" in single sql - Oracle SQL

Yes you can...

WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
     SET2 AS (SELECT * FROM SET1)        -- SET1 accessed
SELECT * FROM SET2;                      -- SET2 projected

10/29/2013 10:43:26 AM

Follow the order in which it should be initialized in Common Table Expressions

What does the Excel range.Rows property really do?

Since the .Rows result is marked as consisting of rows, you can "For Each" it to deal with each row individually, like this:

Function Attendance(rng As Range) As Long
Attendance = 0
For Each rRow In rng.Rows
    If WorksheetFunction.Sum(rRow) > 0 Then
        Attendance = Attendance + 1
    End If
Next
End Function

I use this to check attendance in any of a few categories (different columns) for a list of people (different rows).

(And of course you could use .Columns to do a "For Each" over the columns in the range.)

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

Android - get children inside a View?

Here is a suggestion: you can get the ID (specified e.g. by android:id="@+id/..My Str..) which was generated by R by using its given name (e.g. My Str). A code snippet using getIdentifier() method would then be:

public int getIdAssignedByR(Context pContext, String pIdString)
{
    // Get the Context's Resources and Package Name
    Resources resources = pContext.getResources();
    String packageName  = pContext.getPackageName();

    // Determine the result and return it
    int result = resources.getIdentifier(pIdString, "id", packageName);
    return result;
}

From within an Activity, an example usage coupled with findViewById would be:

// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);

Failed to serialize the response in Web API with Json

Solution that worked for me:

  1. Use [DataContract] for class and [DataMember] attributes for each property to serialize. This is enough to get Json result (for ex. from fiddler).

  2. To get xml serialization write in Global.asax this code:

    var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true;

  3. Read this article, it helped me to understand serialization: https://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

Using R to download zipped data file, extract, and import data

rio() would be very suitable for this - it uses the file extension of a file name to determine what kind of file it is, so it will work with a large variety of file types. I've also used unzip() to list the file names within the zip file, so its not necessary to specify the file name(s) manually.

library(rio)

# create a temporary directory
td <- tempdir()

# create a temporary file
tf <- tempfile(tmpdir=td, fileext=".zip")

# download file from internet into temporary location
download.file("http://download.companieshouse.gov.uk/BasicCompanyData-part1.zip", tf)

# list zip archive
file_names <- unzip(tf, list=TRUE)

# extract files from zip file
unzip(tf, exdir=td, overwrite=TRUE)

# use when zip file has only one file
data <- import(file.path(td, file_names$Name[1]))

# use when zip file has multiple files
data_multiple <- lapply(file_names$Name, function(x) import(file.path(td, x)))

# delete the files and directories
unlink(td)

How do you use NSAttributedString?

When building attributed strings, I prefer to use the mutable subclass, just to keep things cleaner.

That being said, here's how you create a tri-color attributed string:

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

typed in a browser. caveat implementor

Obviously you're not going to hard-code in the ranges like this. Perhaps instead you could do something like:

NSDictionary * wordToColorMapping = ....;  //an NSDictionary of NSString => UIColor pairs
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@""];
for (NSString * word in wordToColorMapping) {
  UIColor * color = [wordToColorMapping objectForKey:word];
  NSDictionary * attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
  NSAttributedString * subString = [[NSAttributedString alloc] initWithString:word attributes:attributes];
  [string appendAttributedString:subString];
  [subString release];
}

//display string

Twitter Bootstrap 3: how to use media queries?

These are the values from Bootstrap3:

/* Extra Small */
@media(max-width:767px){}

/* Small */
@media(min-width:768px) and (max-width:991px){}

/* Medium */
@media(min-width:992px) and (max-width:1199px){}

/* Large */
@media(min-width:1200px){}

How to distinguish between left and right mouse click with jQuery

There are a lot of very good answers, but I just want to touch on one major difference between IE9 and IE < 9 when using event.button.

According to the old Microsoft specification for event.button the codes differ from the ones used by W3C. W3C considers only 3 cases:

  1. Left mouse button is clicked - event.button === 1
  2. Right mouse button is clicked - event.button === 3
  3. Middle mouse button is clicked - event.button === 2

In older Internet Explorers however Microsoft are flipping a bit for the pressed button and there are 8 cases:

  1. No button is clicked - event.button === 0 or 000
  2. Left button is clicked - event.button === 1 or 001
  3. Right button is clicked - event.button === 2 or 010
  4. Left and right buttons are clicked - event.button === 3 or 011
  5. Middle button is clicked - event.button === 4 or 100
  6. Middle and left buttons are clicked - event.button === 5 or 101
  7. Middle and right buttons are clicked - event.button === 6 or 110
  8. All 3 buttons are clicked - event.button === 7 or 111

Despite the fact that this is theoretically how it should work, no Internet Explorer has ever supported the cases of two or three buttons simultaneously pressed. I am mentioning it because the W3C standard cannot even theoretically support this.

How to get Toolbar from fragment?

toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);

What's NSLocalizedString equivalent in Swift?

When you to translate, say from English, where a phrase is the same, to another language where it is different (because of the gender, verb conjugations or declension) the simplest NSString form in Swift that works in all cases is the three arguments one. For example, the English phrase "previous was", is translated differently to Russian for the case of "weight" ("?????????? ???") and for "waist" ("?????????? ????").

In this case you need two different translation for one Source (in terms of XLIFF tool recommended in WWDC 2018). You cannot achieve it with two argument NSLocalizedString, where "previous was" will be the same both for the "key" and the English translation (i.e. for the value). The only way is to use the three argument form

NSLocalizedString("previousWasFeminine", value: "previous was", comment: "previousWasFeminine")

NSLocalizedString("previousWasMasculine", value: "previous was", comment: "previousWasMasculine")

where keys ("previousWasFeminine" and "previousWasMasculine") are different.

I know that the general advice is to translate the phrase as the whole, however, sometimes it too time consuming and inconvenient.

Mathematical functions in Swift

To be perfectly precise, Darwin is enough. No need to import the whole Cocoa framework.

import Darwin

Of course, if you need elements from Cocoa or Foundation or other higher level frameworks, you can import them instead

Delete keychain items when an app is uninstalled

Just add an app setting bundle and implement a toggle to reset the keychain on app restart or something based on the value selected through settings (available through userDefaults)

How to get the selected value from drop down list in jsp?

    <%-- if you want to select value from drop-downlist here is jsp code. --%>
    <body>
    <form name="f1" method="get" action="#">
       <select name="clr">
           <option>Red</option>
           <option>Blue</option>   
           <option>Green</option>
           <option>Pink</option>
       </select>
     <input type="submit" name="submit" value="Select Color"/>
    </form>
    <%-- To display selected value from dropdown list. --%>
     <% 
                String s=request.getParameter("clr");
                if (s !=null)
                {
                    out.println("Selected Color is : "+s);
                }
      %>
</body>

Rollback to last git commit

git reset --hard will force the working directory back to the last commit and delete new/changed files.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

Step 1 : First time connect phone with Cable

Step 2 : Go to Organizer & Devices

Step 3 : Tick Connect as Network

Now simple trick which works everytime.

Step 4 : Turn on hotspot on iphone

Step 5 : Connect your mac with that hotspot.

Step 6 : Now run the code.

This will always work.

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you want it in crlf (Windows Eol), go to File -> Preferences -> Settings. Type "end of line" in the User tab and make sure Files: Eol is set to \r\n and if you're using the Prettier extension, make sure Prettier: End of Line is set to crlf. enter image description here Finally, on your eslintrc file, add this rule: 'linebreak-style': ['error', 'windows'] enter image description here

PLS-00103: Encountered the symbol when expecting one of the following:

The problem is that the else and if are two operators here. Since you open a new 'if' you need a corresponding 'end if'.

Thus:

declare
mark number :=50;
begin
  mark :=& mark;
  if (mark between 85 and 100) then
    dbms_output.put_line('mark is A ');
  else 
    if (mark between 50 and 65) then
      dbms_output.put_line('mark is D ');
    else 
      if (mark between 66 and 75) then
        dbms_output.put_line('mark is C ');
      else 
        if (mark between 76 and 84) then
          dbms_output.put_line('mark is B');
        else 
          dbms_output.put_line('mark is F');
        end if;
      end if;
    end if;
  end if;
end;
/

Alternatively you can use elsif:

declare
mark number :=50;
begin
  mark :=& mark;
  if (mark between 85 and 100)
    then
    dbms_output.put_line('mark is A ');
  elsif (mark between 50 and 65) then
    dbms_output.put_line('mark is D ');
  elsif (mark between 66 and 75) then
    dbms_output.put_line('mark is C ');
  elsif (mark between 76 and 84) then
    dbms_output.put_line('mark is B');
  else 
    dbms_output.put_line('mark is F');
  end if;
end;
/

Android - running a method periodically using postDelayed() call

You can simplify the code like this.

In Java:

new Handler().postDelayed (() -> {
    //your code here
}, 1000);

In Kotlin:

Handler().postDelayed({
   //your code here
}, 1000)

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

changing source on html5 video tag

I hated all these answers because they were too short or relied on other frameworks.

Here is "one" vanilla JS way of doing this, working in Chrome, please test in other browsers:

http://jsfiddle.net/mattdlockyer/5eCEu/2/

HTML:

<video id="video" width="320" height="240"></video>

JS:

var video = document.getElementById('video');
var source = document.createElement('source');

source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Kill%20Bill%20Vol.3.mp4');

video.appendChild(source);
video.play();

setTimeout(function() {  
    video.pause();

    source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Despicable%20Me%202.mp4'); 

    video.load();
    video.play();
}, 3000);

How to convert String to Date value in SAS?

As stated above, the simple answer is:

date = input(monyy,date9.);

with the addition of:

put date=yymmdd.;

The reason why this works, and what you did doesn't, is because of a common misunderstanding in SAS. DATE9. is an INFORMAT. In an INPUT statement, it provides the SAS interpreter with a set of translation commands it can send to the compiler to turn your text into the right numbers, which will then look like a date once the right FORMAT is applied. FORMATs are just visible representations of numbers (or characters). So by using YYMMDD., you confused the INPUT function by handing it a FORMAT instead of an INFORMAT, and probably got a helpful error that said:

Invalid argument to INPUT function at line... etc...

Which told you absolutely nothing about what to do next.

In summary, to represent your character date as a YYMMDD. In SAS you need to:

  1. change the INFORMAT - date = input(monyy,date9.);
  2. apply the FORMAT - put date=YYMMDD10.;

java.util.regex - importance of Pattern.compile()?

Pattern.compile() allow to reuse a regex multiple times (it is threadsafe). The performance benefit can be quite significant.

I did a quick benchmark:

    @Test
    public void recompile() {
        var before = Instant.now();
        for (int i = 0; i < 1_000_000; i++) {
            Pattern.compile("ab").matcher("abcde").matches();
        }
        System.out.println("recompile " + Duration.between(before, Instant.now()));
    }

    @Test
    public void compileOnce() {
        var pattern = Pattern.compile("ab");
        var before = Instant.now();
        for (int i = 0; i < 1_000_000; i++) {
            pattern.matcher("abcde").matches();
        }
        System.out.println("compile once " + Duration.between(before, Instant.now()));
    }

compileOnce was between 3x and 4x faster. I guess it highly depends on the regex itself but for a regex that is often used, I go for a static Pattern pattern = Pattern.compile(...)

How to fix a header on scroll

I know Coop has already answered this question, but here is a version which also tracks where in the document the div is, rather than relying on a static value:

http://jsfiddle.net/gxRC9/16/

Javascript

var offset = $( ".sticky-header" ).offset();
var sticky = document.getElementById("sticky-header")

$(window).scroll(function() {

    if ( $('body').scrollTop() > offset.top){
        $('.sticky-header').addClass('fixed');
    } else {
         $('.sticky-header').removeClass('fixed');
    } 

});

CSS

.fixed{
     position: fixed;
    top: 0px;
}

Use RSA private key to generate public key?

here in this code first we are creating RSA key which is private but it has pair of its public key as well so to get your actual public key we simply do this

openssl rsa -in mykey.pem -pubout > mykey.pub

hope you get it for more info check this

jQuery select box validation

To put a require rule on a select list you just need an option with an empty value

<option value="">Year</option>

then just applying required on its own is enough

<script>
    $(function () {
        $("form").validate();
    });
</script>

with form

<form>
<select name="year" id="year" class="required">
    <option value="">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<input type="submit" />
</form>

fiddle is here

How to clear out session on log out

I use following to clear session and clear aspnet_sessionID:

HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

Create or update mapping in elasticsearch

Please note that there is a mistake in the url provided in this answer:

For a PUT mapping request: the url should be as follows:

http://localhost:9200/name_of_index/_mappings/document_type

and NOT

http://localhost:9200/name_of_index/document_type/_mappings

How to detect online/offline event cross-browser?

The window.navigator.onLine attribute and its associated events are currently unreliable on certain web browsers (especially Firefox desktop) as @Junto said, so I wrote a little function (using jQuery) that periodically checks the network connectivity status and raise the appropriate offline and online events:

// Global variable somewhere in your app to replicate the 
// window.navigator.onLine variable (this last is not modifiable). It prevents
// the offline and online events to be triggered if the network
// connectivity is not changed
var IS_ONLINE = true;

function checkNetwork() {
  $.ajax({
    // Empty file in the root of your public vhost
    url: '/networkcheck.txt',
    // We don't need to fetch the content (I think this can lower
    // the server's resources needed to send the HTTP response a bit)
    type: 'HEAD',
    cache: false, // Needed for HEAD HTTP requests
    timeout: 2000, // 2 seconds
    success: function() {
      if (!IS_ONLINE) { // If we were offline
        IS_ONLINE = true; // We are now online
        $(window).trigger('online'); // Raise the online event
      }
    },
    error: function(jqXHR) {
      if (jqXHR.status == 0 && IS_ONLINE) {
        // We were online and there is no more network connection
        IS_ONLINE = false; // We are now offline
        $(window).trigger('offline'); // Raise the offline event
      } else if (jqXHR.status != 0 && !IS_ONLINE) {
        // All other errors (404, 500, etc) means that the server responded,
        // which means that there are network connectivity
        IS_ONLINE = true; // We are now online
        $(window).trigger('online'); // Raise the online event
      }
    }
  });
}

You can use it like this:

// Hack to use the checkNetwork() function only on Firefox 
// (http://stackoverflow.com/questions/5698810/detect-firefox-browser-with-jquery/9238538#9238538)
// (But it may be too restrictive regarding other browser
// who does not properly support online / offline events)
if (!(window.mozInnerScreenX == null)) {
    window.setInterval(checkNetwork, 30000); // Check the network every 30 seconds
}

To listen to the offline and online events (with the help of jQuery):

$(window).bind('online offline', function(e) {
  if (!IS_ONLINE || !window.navigator.onLine) {
    alert('We have a situation here');
  } else {
    alert('Battlestation connected');
  }
});

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Late at party, but a very simple solution is to use the jpsstat.sh script. It provides a simple live current memory, max memory and cpu use details.

  • Goto GitHub project and download the jpsstat.sh file
  • Right click on jpsstat.sh and goto permissions tab and make it executable
  • Now Run the script using following command ./jpsstat.sh

Here is the sample output of script -

=====  ======  =======  =======  =====
 PID    Name   CurHeap  MaxHeap  %_CPU
=====  ======  =======  =======  =====
2777   Test3      1.26     1.26    5.8
2582   Test1      2.52     2.52    8.3
2562   Test2      2.52     2.52    6.4

Error with multiple definitions of function

You have #include "fun.cpp" in mainfile.cpp so compiling with:

g++ -o hw1 mainfile.cpp

will work, however if you compile by linking these together like

g++ -g -std=c++11 -Wall -pedantic   -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic   -c -o mainfile.o mainfile.cpp

As they mention above, adding #include "fun.hpp" will need to be done or it won't work. However, your case with the funct() function is slightly different than my problem.

I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.

What's the main difference between int.Parse() and Convert.ToInt32

Int32.parse(string)--->

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:

string s1 = "1234"; 
string s2 = "1234.65"; 
string s3 = null; 
string s4 = "123456789123456789123456789123456789123456789"; 

result = Int32.Parse(s1);    //1234
result = Int32.Parse(s2);    //FormatException
result = Int32.Parse(s3);    //ArgumentNullException 
result = Int32.Parse(s4);    //OverflowException

Convert.ToInt32(string) --> Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

For example:

 result = Convert.ToInt32(s1);    // 1234 
 result = Convert.ToInt32(s2);    // FormatException
 result = Convert.ToInt32(s3);    // 0
 result = Convert.ToInt32(s4);    // OverflowException 

SOAP PHP fault parsing WSDL: failed to load external entity?

Put this code above any Soap call:

libxml_disable_entity_loader(false);

shell init issue when click tab, what's wrong with getcwd?

Yes, cd; and cd - would work. The reason It can see is that, directory is being deleted from any other terminal or any other program and recreate it. So i-node entry is modified so program can not access old i-node entry.

How to mount the android img file under linux?

Another option would be to use the File Explorer in DDMS (Eclipse SDK), you can see the whole file system there and download/upload files to the desired place. That way you don't have to mount and deal with images. Just remember to set your device as USB debuggable (from Developer Tools)

How to import a module given the full path?

Import package modules at runtime (Python recipe)

http://code.activestate.com/recipes/223972/

###################
##                #
## classloader.py #
##                #
###################

import sys, types

def _get_mod(modulePath):
    try:
        aMod = sys.modules[modulePath]
        if not isinstance(aMod, types.ModuleType):
            raise KeyError
    except KeyError:
        # The last [''] is very important!
        aMod = __import__(modulePath, globals(), locals(), [''])
        sys.modules[modulePath] = aMod
    return aMod

def _get_func(fullFuncName):
    """Retrieve a function object from a full dotted-package name."""

    # Parse out the path, module, and function
    lastDot = fullFuncName.rfind(u".")
    funcName = fullFuncName[lastDot + 1:]
    modPath = fullFuncName[:lastDot]

    aMod = _get_mod(modPath)
    aFunc = getattr(aMod, funcName)

    # Assert that the function is a *callable* attribute.
    assert callable(aFunc), u"%s is not callable." % fullFuncName

    # Return a reference to the function itself,
    # not the results of the function.
    return aFunc

def _get_class(fullClassName, parentClass=None):
    """Load a module and retrieve a class (NOT an instance).

    If the parentClass is supplied, className must be of parentClass
    or a subclass of parentClass (or None is returned).
    """
    aClass = _get_func(fullClassName)

    # Assert that the class is a subclass of parentClass.
    if parentClass is not None:
        if not issubclass(aClass, parentClass):
            raise TypeError(u"%s is not a subclass of %s" %
                            (fullClassName, parentClass))

    # Return a reference to the class itself, not an instantiated object.
    return aClass


######################
##       Usage      ##
######################

class StorageManager: pass
class StorageManagerMySQL(StorageManager): pass

def storage_object(aFullClassName, allOptions={}):
    aStoreClass = _get_class(aFullClassName, StorageManager)
    return aStoreClass(allOptions)

How to declare and add items to an array in Python?

In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:

Java:

int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};

However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}

To actually define an array (which is actually called list in python) you can do:

Python:

mylist = [1,2,3]

or other examples like:

mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]

SQL Query to fetch data from the last 30 days?

SELECT COUNT(job_id) FROM jobs WHERE posted_date < NOW()-30;

Now() returns the current Date and Time.

How do I get a substring of a string in Python?

Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:

some_string[::-1]

Or selecting alternate characters would be:

"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"

The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end.

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

INSERT INTO eSSLSmartOfficeSource2.[dbo].DeviceLogs  (DeviceId,UserId,LogDate,UpdateFlag) 
SELECT DL1.DeviceId ,DL1.UserId COLLATE DATABASE_DEFAULT,DL1.LogDate 
,0 FROM eSSLSmartOffice.[dbo].DeviceLogs DL1 
WHERE  NOT EXISTS 
(SELECT DL2.DeviceId ,DL2.UserId COLLATE DATABASE_DEFAULT
,DL2.LogDate ,DL2.UpdateFlag 
FROM eSSLSmartOfficeSource2.[dbo].DeviceLogs DL2    
WHERE  DL1.DeviceId =DL2.DeviceId
 and DL1.UserId collate  Latin1_General_CS_AS=DL2.UserId collate  Latin1_General_CS_AS
  and DL1.LogDate =DL2.LogDate )

Using env variable in Spring Boot's application.properties

Maybe I write this too late, but I have gotten the similar problem when I have tried to override methods for reading properties.

My problem have been: 1) Read property from env if this property has been set in env 2) Read property from system property if this property have been setted in system property 3) And last, read from application properties.

So, for resolving this problem I go to my bean configuration class

@Validated
@Configuration
@ConfigurationProperties(prefix = ApplicationConfiguration.PREFIX)
@PropertySource(value = "${application.properties.path}", factory = PropertySourceFactoryCustom.class)
@Data // lombok
public class ApplicationConfiguration {

    static final String PREFIX = "application";

    @NotBlank
    private String keysPath;

    @NotBlank
    private String publicKeyName;

    @NotNull
    private Long tokenTimeout;

    private Boolean devMode;

    public void setKeysPath(String keysPath) {
        this.keysPath = StringUtils.cleanPath(keysPath);
    }
}

And overwrite factory in @PropertySource. And then I have created my own implementation for reading properties.

    public class PropertySourceFactoryCustom implements PropertySourceFactory {

        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            return name != null ? new PropertySourceCustom(name, resource) : new PropertySourceCustom(resource);
        }


    }

And created PropertySourceCustom

public class PropertySourceCustom extends ResourcePropertySource {


    public LifeSourcePropertySource(String name, EncodedResource resource) throws IOException {
        super(name, resource);
    }

    public LifeSourcePropertySource(EncodedResource resource) throws IOException {
        super(resource);
    }

    public LifeSourcePropertySource(String name, Resource resource) throws IOException {
        super(name, resource);
    }

    public LifeSourcePropertySource(Resource resource) throws IOException {
        super(resource);
    }

    public LifeSourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException {
        super(name, location, classLoader);
    }

    public LifeSourcePropertySource(String location, ClassLoader classLoader) throws IOException {
        super(location, classLoader);
    }

    public LifeSourcePropertySource(String name, String location) throws IOException {
        super(name, location);
    }

    public LifeSourcePropertySource(String location) throws IOException {
        super(location);
    }

    @Override
    public Object getProperty(String name) {

        if (StringUtils.isNotBlank(System.getenv(name)))
            return System.getenv(name);

        if (StringUtils.isNotBlank(System.getProperty(name)))
            return System.getProperty(name);

        return super.getProperty(name);
    }
}

So, this has helped me.

How do you reinstall an app's dependencies using npm?

Follow this step to re install node modules and update them

works even if node_modules folder does not exist. now execute the following command synchronously. you can also use "npm update" but I think this'd preferred way

npm outdated // not necessary to run this command, but this will show outdated dependencies

npm install -g npm-check-updates // to install the "ncu" package

ncu -u --packageFile=package.json // to update dependencies version in package.json...don't run this command if you don't need to update the version

npm install: will install dependencies in your package.json file.

if you're okay with the version of your dependencies in your package.json file, no need to follow those steps just run

 npm install

Prevent cell numbers from incrementing in a formula in Excel

There is something called 'locked reference' in excel which you can use for this, and you use $ symbols to lock a range. For your example, you would use:

=IF(B4<>"",B4/B$1,"")

This locks the 1 in B1 so that when you copy it to rows below, 1 will remain the same.

If you use $B$1, the range will not change when you copy it down a row or across a column.

How can I trim beginning and ending double quotes from a string?

You can use String#replaceAll() with a pattern of ^\"|\"$ for this.

E.g.

string = string.replaceAll("^\"|\"$", "");

To learn more about regular expressions, have al ook at http://regular-expression.info.

That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.

chrome undo the action of "prevent this page from creating additional dialogs"

If you wish dialog box to be re-activated for the page you set as prevent dialog box to show.

Chrome: select settings, a google page for chrome will open with all your settings for chrome.

At the very bottom, go to advance settings and at the bottom of the advance settings you may click on Resset Browser Settings... this will make dialog box appear as they should.

Is a GUID unique 100% of the time?

I have experienced the GUIDs not being unique during multi-threaded/multi-process unit-testing (too?). I guess that has to do with, all other tings being equal, the identical seeding (or lack of seeding) of pseudo random generators. I was using it for generating unique file names. I found the OS is much better at doing that :)

Trolling alert

You ask if GUIDs are 100% unique. That depends on the number of GUIDs it must be unique among. As the number of GUIDs approach infinity, the probability for duplicate GUIDs approach 100%.

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

How to rename with prefix/suffix?

In Bash and zsh you can do this with Brace Expansion. This simply expands a list of items in braces. For example:

# echo {vanilla,chocolate,strawberry}-ice-cream
vanilla-ice-cream chocolate-ice-cream strawberry-ice-cream

So you can do your rename as follows:

mv {,new.}original.filename

as this expands to:

mv original.filename new.original.filename