Programs & Examples On #Bitconverter

Class in C# and Java that converts base data types to an array of bytes, and an array of bytes to base data types.

Byte[] to ASCII

As an alternative to reading a data from a stream to a byte array, you could let the framework handle everything and just use a StreamReader set up with an ASCII encoding to read in the string. That way you don't need to worry about getting the appropriate buffer size or larger data sizes.

using (var reader = new StreamReader(stream, Encoding.ASCII))
{
    string theString = reader.ReadToEnd();
    // do something with theString
}

Converting from hex to string

Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

Java 8 Streams: multiple filters vs. complex condition

The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool()) by filter(ItemType::isCool). That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter invocation using a lambda expression with &&.

But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.

In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.

So there is no simple answer.

The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.


¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation

Why would I use dirname(__FILE__) in an include or include_once statement?

I used this below if this is what you are thinking. It it worked well for me.

<?php
    include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>

What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.

Is there an exponent operator in C#?

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:

public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;

Remember the types must be (uint) << (int).

Setting the height of a DIV dynamically

Simplest I could come up...

function resizeResizeableHeight() {
    $('.resizableHeight').each( function() {
        $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )
    });
}

Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).

How do I remove the non-numeric character from a string in java?

Simple way without using Regex:

public static String getOnlyNumerics(String str) {
    if (str == null) {
        return null;
    }
    StringBuffer strBuff = new StringBuffer();
    char c;
    for (int i = 0; i < str.length() ; i++) {
        c = str.charAt(i);
        if (Character.isDigit(c)) {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}

Vim: How to insert in visual block mode?

if you want to add new text before or after the selected colum:

  • press ctrl+v
  • select columns
  • press shift+i
  • write your text
  • press esc
  • press "jj"

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

Angular2 get clicked element id

There is no need to pass the entire event (unless you need other aspects of the event than you have stated). In fact, it is not recommended. You can pass the element reference with just a little modification.

import {Component} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
    <button #btn1 (click)="toggle(btn1)" class="someclass" id="btn1">Button 1</button>
    <button #btn2 (click)="toggle(btn2)" class="someclass" id="btn2">Button 2</button>
  `
})
export class AppComponent {
  buttonValue: string;

  toggle(button) {
    this.buttonValue = button.id;
  }

}

StackBlitz demo

Technically, you don't need to find the button that was clicked, because you have passed the actual element.

Angular guidance

Copy existing project with a new name in Android Studio

Go to the source folder where your project is.

  1. Copy the project and past and change the name.
  2. Open Android Studio and refresh.
  3. Go to ->Settings.gradle.
  4. Include ':your new project name '

GIT: Checkout to a specific folder

I defined an git alias to achieve just this (before I found this question).

It's a short bash function which saves the current path, switch to the git repo, does a checkout and return where it started.

git checkto develop ~/my_project_git

This e.g. would checkout the develop branch into "~/my_project_git" directory.

This is the alias code inside ~/.gitconfig:

[alias]
    checkTo = "!f(){ [ -z \"$1\" ] && echo \"Need to specify branch.\" && \
               exit 1; [ -z \"$2\" ] && echo \"Need to specify target\
               dir\" && exit 2; cDir=\"$(pwd)\"; cd \"$2\"; \
               git checkout \"$1\"; cd \"$cDir\"; };f"

Reloading the page gives wrong GET request with AngularJS HTML5 mode

There are few things to set up so your link in the browser will look like http://yourdomain.com/path and these are your angular config + server side

1) AngularJS

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true);

2) server side, just put .htaccess inside your root folder and paste this

RewriteEngine On 
Options FollowSymLinks

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode Also this question might help you $location / switching between html5 and hashbang mode / link rewriting

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How do I use disk caching in Picasso?

Add followning code in Application.onCreate then use it normal

    Picasso picasso = new Picasso.Builder(context)
            .downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE))
            .build();
    picasso.setIndicatorsEnabled(true);
    picasso.setLoggingEnabled(true);
    Picasso.setSingletonInstance(picasso);

If you cache images first then do something like this in ProductImageDownloader.doBackground

final Callback callback = new Callback() {
            @Override
            public void onSuccess() {
                downLatch.countDown();
                updateProgress();
            }

            @Override
            public void onError() {
                errorCount++;
                downLatch.countDown();
                updateProgress();
            }
        };
        Picasso.with(context).load(Constants.imagesUrl+productModel.getGalleryImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
        Picasso.with(context).load(Constants.imagesUrl+productModel.getLeftImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
        Picasso.with(context).load(Constants.imagesUrl+productModel.getRightImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);

        try {
            downLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(errorCount == 0){
            products.remove(productModel);
            productModel.isDownloaded = true;
            productsDatasource.updateElseInsert(productModel);
        }else {
            //error occurred while downloading images for this product
            //ignore error for now
            // FIXME: 9/27/2017 handle error
            products.remove(productModel);

        }
        errorCount = 0;
        downLatch = new CountDownLatch(3);

        if(!products.isEmpty() /*&& testCount++ < 30*/){
            startDownloading(products.get(0));
        }else {
            //all products with images are downloaded
            publishProgress(100);
        }

and load your images like normal or with disk caching

    Picasso.with(this).load(Constants.imagesUrl+batterProduct.getGalleryImage())
        .networkPolicy(NetworkPolicy.OFFLINE)
        .placeholder(R.drawable.GalleryDefaultImage)
        .error(R.drawable.GalleryDefaultImage)
        .into(viewGallery);

Note:

Red color indicates that image is fetched from network.

Green color indicates that image is fetched from cache memory.

Blue color indicates that image is fetched from disk memory.

Before releasing the app delete or set it false picasso.setLoggingEnabled(true);, picasso.setIndicatorsEnabled(true); if not required. Thankx

Compiling C++11 with g++

If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:

The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.

How should I call 3 functions in order to execute them one after the other?

In Javascript, there are synchronous and asynchronous functions.

Synchronous Functions

Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

they will execute in order. doSomethingElse will not start until doSomething has completed. doSomethingUsefulThisTime, in turn, will not start until doSomethingElse has completed.

Asynchronous Functions

Asynchronous function, however, will not wait for each other. Let us look at the same code sample we had above, this time assuming that the functions are asynchronous

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

The functions will be initialized in order, but they will all execute roughly at the same time. You can't consistently predict which one will finish first: the one that happens to take the shortest amount of time to execute will finish first.

But sometimes, you want functions that are asynchronous to execute in order, and sometimes you want functions that are synchronous to execute asynchronously. Fortunately, this is possible with callbacks and timeouts, respectively.

Callbacks

Let's assume that we have three asynchronous functions that we want to execute in order, some_3secs_function, some_5secs_function, and some_8secs_function.

Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.

If we create the functions like this

function some_3secs_function(value, callback){
  //do stuff
  callback();
}

then you can call then in order, like this:

some_3secs_function(some_value, function() {
  some_5secs_function(other_value, function() {
    some_8secs_function(third_value, function() {
      //All three functions have completed, in order.
    });
  });
});

Timeouts

In Javascript, you can tell a function to execute after a certain timeout (in milliseconds). This can, in effect, make synchronous functions behave asynchronously.

If we have three synchronous functions, we can execute them asynchronously using the setTimeout function.

setTimeout(doSomething, 10);
setTimeout(doSomethingElse, 10);
setTimeout(doSomethingUsefulThisTime, 10);

This is, however, a bit ugly and violates the DRY principle[wikipedia]. We could clean this up a bit by creating a function that accepts an array of functions and a timeout.

function executeAsynchronously(functions, timeout) {
  for(var i = 0; i < functions.length; i++) {
    setTimeout(functions[i], timeout);
  }
}

This can be called like so:

executeAsynchronously(
    [doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);

In summary, if you have asynchronous functions that you want to execute syncronously, use callbacks, and if you have synchronous functions that you want to execute asynchronously, use timeouts.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Javascript - get array of dates between 2 dates

Try this, remember to include moment js,

function getDates(startDate, stopDate) {
    var dateArray = [];
    var currentDate = moment(startDate);
    var stopDate = moment(stopDate);
    while (currentDate <= stopDate) {
        dateArray.push( moment(currentDate).format('YYYY-MM-DD') )
        currentDate = moment(currentDate).add(1, 'days');
    }
    return dateArray;
}

Storing SHA1 hash values in MySQL

Reference taken from this blog:

Below is a list of hashing algorithm along with its require bit size:

  • MD5 = 128-bit hash value.
  • SHA1 = 160-bit hash value.
  • SHA224 = 224-bit hash value.
  • SHA256 = 256-bit hash value.
  • SHA384 = 384-bit hash value.
  • SHA512 = 512-bit hash value.

Created one sample table with require CHAR(n):

CREATE TABLE tbl_PasswordDataType
(
    ID INTEGER
    ,MD5_128_bit CHAR(32)
    ,SHA_160_bit CHAR(40)
    ,SHA_224_bit CHAR(56)
    ,SHA_256_bit CHAR(64)
    ,SHA_384_bit CHAR(96)
    ,SHA_512_bit CHAR(128)
); 
INSERT INTO tbl_PasswordDataType
VALUES 
(
    1
    ,MD5('SamplePass_WithAddedSalt')
    ,SHA1('SamplePass_WithAddedSalt')
    ,SHA2('SamplePass_WithAddedSalt',224)
    ,SHA2('SamplePass_WithAddedSalt',256)
    ,SHA2('SamplePass_WithAddedSalt',384)
    ,SHA2('SamplePass_WithAddedSalt',512)
);

PHP mkdir: Permission denied problem

Don't set permissions to 777 when using mkdir in PHP

Link only answers are not considered good practice on StackOverflow, but the advice that is given here should generally NOT be followed up.

I would like to revert to this great answer on a similar question. I quote:

Please stop suggesting to use 777. You're making your file writeable by everyone, which pretty much means you lose all security that the permission system was designed for. If you suggest this, think about the consequences it may have on a poorly configured webserver: it would become incredibly easy to "hack" the website, by overwriting the files. So, don't.

How to call URL action in MVC with javascript function?

Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:

 <input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />

Then you just get the value in your ajax call:

var path = $("#GetIndexDataPath").val();
$.ajax({
        type: "GET",
        url: path,
        data: { id = e.value},  
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.

window.history.pushState refreshing the browser

The short answer is that history.pushState (not History.pushState, which would throw an exception, the window part is optional) will never do what you suggest.

If pages are refreshing, then it is caused by other things that you are doing (for example, you might have code running that goes to a new location in the case of the address bar changing).

history.pushState({urlPath:'/page2.php'},"",'/page2.php') works exactly like it is supposed to in the latest versions of Chrome, IE and Firefox for me and my colleagues.

In fact you can put whatever you like into the function: history.pushState({}, '', 'So long and thanks for all the fish.not a real file').

If you post some more code (with special attention for code nearby the history.pushState and anywhere document.location is used), then we'll be more than happy to help you figure out where exactly this issue is coming from.

If you post more code, I'll update this answer (I have your question favourited) :).

Hash table runtime complexity (insert, search and delete)

Depends on the how you implement hashing, in the worst case it can go to O(n), in best case it is 0(1) (generally you can achieve if your DS is not that big easily)

Converting a PDF to PNG

Couldn't get the accepted answer to work. Then found out that actually the solution is much simpler anyway as Ghostscript not just natively supports PNG but even multiple different "encodings":

  • png256
  • png16
  • pnggray
  • pngmono
  • ...

The shell command that works for me is:

gs -dNOPAUSE -q -sDEVICE=pnggray -r500 -dBATCH -dFirstPage=2 -dLastPage=2 -sOutputFile=test.png test.pdf

It will save page 2 of test.pdf to test.png using the pnggray encoding and 500 DPI.

Safely limiting Ansible playbooks to a single machine?

We have some generic playbooks that are usable by a large number of teams. We also have environment specific inventory files, that contain multiple group declarations.

To force someone calling a playbook to specify a group to run against, we seed a dummy entry at the top of the playbook:

[ansible-dummy-group]
dummy-server

We then include the following check as a first step in the shared playbook:

- hosts: all
  gather_facts: False
  run_once: true
  tasks:
  - fail:
      msg: "Please specify a group to run this playbook against"
    when: '"dummy-server" in ansible_play_batch'

If the dummy-server shows up in the list of hosts this playbook is scheduled to run against (ansible_play_batch), then the caller didn't specify a group and the playbook execution will fail.

All shards failed

If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:

curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
    "index" : {
        "number_of_replicas" : 0
    }
}'

Doing this you'll force to use es without replicas

What's the difference between "git reset" and "git checkout"?

brief mnemonics:

git reset HEAD           :             index = HEAD
git checkout             : file_tree = index
git reset --hard HEAD    : file_tree = index = HEAD

How do I replace a character in a string in Java?

String taskLatLng = task.getTask_latlng().replaceAll( "\\(","").replaceAll("\\)","").replaceAll("lat/lng:", "").trim();

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

What should be the package name of android app?

Presently Package name starting with "com.example" is not allowed to upload in the app -store. Otherwise , all other package names starting with "com" are allowed .

jquery smooth scroll to an anchor?

Best solution I have seen so far: jQuery: Smooth Scrolling Internal Anchor Links

HTML:

<a href="#comments" class="scroll">Scroll to comments</a>

Script:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

Declaring variables inside loops, good practice or bad practice?

It's a very good practice, as all above answer provide very good theoretical aspect of the question let me give a glimpse of code, i was trying to solve DFS over GEEKSFORGEEKS, i encounter the optimization problem...... If you try to solve the code declaring the integer outside the loop will give you Optimization Error..

stack<int> st;
st.push(s);
cout<<s<<" ";
vis[s]=1;
int flag=0;
int top=0;
while(!st.empty()){
    top = st.top();
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            st.push(g[top][i]);
            cout<<g[top][i]<<" ";
            vis[g[top][i]]=1;
            flag=1;
            break;
        }
    }
    if(!flag){
        st.pop();
    }
}

Now put integers inside the loop this will give you correct answer...

stack<int> st;
st.push(s);
cout<<s<<" ";
vis[s]=1;
// int flag=0;
// int top=0;
while(!st.empty()){
    int top = st.top();
    int flag = 0;
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            st.push(g[top][i]);
            cout<<g[top][i]<<" ";
            vis[g[top][i]]=1;
            flag=1;
            break;
        }
    }
    if(!flag){
        st.pop();
    }
}

this completely reflect what sir @justin was saying in 2nd comment.... try this here https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1. just give it a shot.... you will get it.Hope this help.

How do I force files to open in the browser instead of downloading (PDF)?

Oops, there were typing errors in my previous post.

    header("Content-Type: application/force-download");
    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=\"".$name."\";");

If you don't want the browser to prompt the user then use "inline" for the third string instead of "attachment". Inline works very well. The PDF display immediately without asking the user to click on Open. I've used "attachment" and this will prompt the user for Open, Save. I've tried to change the browser setting nut it doesn't prevent the prompt.

H.264 file size for 1 hr of HD video

It would be a couple of gigs per hour.

MPEG-4 (of which H.264 is a sub-part) define high quality as around 4Mbps. which would be 1.8GB per hour.

This can vary depending on the type of video and the type of compression used.

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

what is the difference between json and xml

XML uses a tag structures for presenting items, like <tag>item</tag>, so an XML document is a set of tags nested into each other. And JSON syntax looks like a construction from Javascript language, with all stuff like lists and dictionaries:

{
 'attrib' : 'value',
 'array' : [1, 2, 3]
}

So if you use JSON it's really simple to use a JSON strings in many script languages, especially Javascript and Python.

How to check if array is not empty?

An easy way is to use Boolean expressions:

if not self.table[5]:
    print('list is empty')
else:
    print('list is not empty')

Or you can use another Boolean expression :

if self.table[5] == []:
    print('list is empty')
else:
    print('list is not empty')

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

Excel VBA Macro: User Defined Type Not Defined

I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"

PDO Prepared Inserts multiple rows in single query

My real world example to insert all german postcodes into an empty table (to add town names later):

// obtain column template
$stmt = $db->prepare('SHOW COLUMNS FROM towns');
$stmt->execute();
$columns = array_fill_keys(array_values($stmt->fetchAll(PDO::FETCH_COLUMN)), null);
// multiple INSERT
$postcode = '01000';// smallest german postcode
while ($postcode <= 99999) {// highest german postcode
    $values = array();
    while ($postcode <= 99999) {
        // reset row
        $row = $columns;
        // now fill our row with data
        $row['postcode'] = sprintf('%05d', $postcode);
        // build INSERT array
        foreach ($row as $value) {
            $values[] = $value;
        }
        $postcode++;
        // avoid memory kill
        if (!($postcode % 10000)) {
            break;
        }
    }
    // build query
    $count_columns = count($columns);
    $placeholder = ',(' . substr(str_repeat(',?', $count_columns), 1) . ')';//,(?,?,?)
    $placeholder_group = substr(str_repeat($placeholder, count($values) / $count_columns), 1);//(?,?,?),(?,?,?)...
    $into_columns = implode(',', array_keys($columns));//col1,col2,col3
    // this part is optional:
    $on_duplicate = array();
    foreach ($columns as $column => $row) {
        $on_duplicate[] = $column;
        $on_duplicate[] = $column;
    }
    $on_duplicate = ' ON DUPLICATE KEY UPDATE' . vsprintf(substr(str_repeat(', %s = VALUES(%s)', $count_columns), 1), $on_duplicate);
    // execute query
    $stmt = $db->prepare('INSERT INTO towns (' . $into_columns . ') VALUES' . $placeholder_group . $on_duplicate);//INSERT INTO towns (col1,col2,col3) VALUES(?,?,?),(?,?,?)... {ON DUPLICATE...}
    $stmt->execute($values);
}

As you can see its fully flexible. You don't need to check the amount of columns or check on which position your column is. You only need to set the insert data:

    $row['postcode'] = sprintf('%05d', $postcode);

I'm proud of some of the query string constructors as they work without heavy array-functions like array_merge. Especially vsprintf() was a good find.

Finally I needed to add 2x while() to avoid exceeding the memory limit. This depends on your memory limit but at all its a good general solution to avoid problems (and having 10 queries is still much better than 10.000).

'Java' is not recognized as an internal or external command

In case you are using a laptop and do not have the Pause\Break button. For windows 10 users with 20h2 and above:

1 WIN ? type "About your PC" ? scroll at the bottom ? Advanced system settings ? Environment variables or WIN+R ? shell:::{bb06c0e4-d293-4f75-8a90-cb05b6477eee} to open Classic System Properties ? on the left side ? Advanced system settings ? Environment variables

Also for Windows 10 and Windows 7:

1 WIN ? This PC ? properties ? Advanced system settings ? Environment variables

  1. In the System variables section click on New…
  2. In Variable name write: JAVA_HOME
  3. In Variable value write: C:\Program Files\Java\jdk-15.0.2\bin, press OK

I have taken steps 2-4 from Vijay Bhatt

Adding a new system variable in UI

There is a bit faster way to set a system variable. Run a console (terminal) as an administrator.

General command synax to add a new variable:

setx variableName value /M

In our example, we would need to set it as

setx JAVA_HOME "C:\Program Files\Java\jdk-15.0.2\bin" /M`

Like this: Adding a new system variable using admin console

/M - flag specifies to set the variable in the system environment. After command execution, you should see the message: SUCCESS: Specified value was saved.

How can I check that it is added?

  1. Close your active terminal;
  2. Open your favorite terminal;
  3. Type java -version.

You should see something similar to this: Result image

Notice: User variables can be created w/o having a root (administrator privileges), whereas to create System variable; You need to open a console as a root.

I have used C:\Program Files\Java\jdk-15.0.2\bin as an example, in your case, it could be different from mine.

How to align footer (div) to the bottom of the page?

Your title and comments imply that you weren't looking for a sticky footer (stuck to the bottom of the window as content scrolls below it). I assume you were looking for a footer that would be forced to the bottom of the window if the content does not fill the window, and push down to the bottom of the content if the content exceeds the window boundary.

You can accomplish this with the following.

<style>
html,
body {
    margin:0;
    padding:0;
    height:100%;
}
#container {
    min-height:100%;
    position:relative;
}
#header {
    background:#ff0;
    padding:10px;
}
#body {
    padding:10px;
    padding-bottom:60px;   /* Height of the footer */
}
#footer {
    position:absolute;
    bottom:0;
    width:100%;
    height:60px;   /* Height of the footer */
    background:#6cf;
}
</style>

<div id="container">
    <div id="header">header</div>
    <div id="body">body</div>
    <div id="footer">footer</div>
</div>

Source: How to keep footers at the bottom of the page

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Converting double to string

The exception probably comes from the parseDouble() calls. Check that the values given to that function really reflect a double.

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

Can I use a :before or :after pseudo-element on an input field?

Here's another approach (assuming you have control of the HTML): add an empty <span></span> right after the input, and target that in CSS using input.mystyle + span:after

_x000D_
_x000D_
.field_with_errors {_x000D_
  display: inline;_x000D_
  color: red;_x000D_
}_x000D_
.field_with_errors input+span:after {_x000D_
  content: "*"_x000D_
}
_x000D_
<div class="field_with_errors">Label:</div>_x000D_
<div class="field_with_errors">_x000D_
  <input type="text" /><span></span> _x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm using this approach in AngularJS because it will add .ng-invalid classes automatically to <input> form elements, and to the form, but not to the <label>.

Laravel Eloquent limit and offset

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();

How to secure MongoDB with username and password

This is what i did for ubuntu 20.04 and mongodb enterprise 4.4.2:

  1. start mongo shell by typing mongo in terminal.

  2. use admin database:

use admin
  1. create a new user and assign your intended role:
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
  1. exit mongo and add the following line to etc/mongod.conf:
security:
    authorization: enabled
  1. restart mongodb server

(optional) 6.If you want your user to have root access you can either specify it when creating your user like:

db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

or you can change user role using:

db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])

How can I disable a button on a jQuery UI dialog?

If you're using knockout, then this even cleaner. Imagine you have the following:

_x000D_
_x000D_
var dialog = $('#my-dialog').dialog({_x000D_
    width: '100%',_x000D_
    buttons: [_x000D_
        { text: 'Submit', click: $.noop, 'data-bind': 'enable: items() && items().length > 0, click: onSubmitClicked' },_x000D_
        { text: 'Enable Submit', click: $.noop, 'data-bind': 'click: onEnableSubmitClicked' }_x000D_
    ]_x000D_
});_x000D_
_x000D_
function ViewModel(dialog) {_x000D_
    var self = this;_x000D_
_x000D_
    this.items = ko.observableArray([]);_x000D_
_x000D_
    this.onSubmitClicked = function () {_x000D_
        dialog.dialog('option', 'title', 'On Submit Clicked!');_x000D_
    };_x000D_
_x000D_
    this.onEnableSubmitClicked = function () {_x000D_
        dialog.dialog('option', 'title', 'Submit Button Enabled!');_x000D_
        self.items.push('TEST ITEM');_x000D_
        dialog.text('Submit button is enabled.');_x000D_
    };_x000D_
}_x000D_
_x000D_
var vm = new ViewModel(dialog);_x000D_
ko.applyBindings(vm, dialog.parent()[0]); //Don't forget to bind to the dialog parent, or the buttons won't get bound.
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>_x000D_
_x000D_
<div id="my-dialog">_x000D_
  Submit button is disabled at initialization._x000D_
</div>
_x000D_
_x000D_
_x000D_

The magic comes from the jQuery UI source:

$( "<button></button>", props )

You can basically call ANY jQuery instance function by passing it through the button object.

For example, if you want to use HTML:

{ html: '<span class="fa fa-user"></span>User' }

Or, if you want to add a class to the button (you can do this multiple ways):

{ addClass: 'my-custom-button-class' }

Maybe you're nuts, and you want to remove the button from the dom when it's hovered:

{ mouseover: function () { $(this).remove(); } }

I'm really surprised that no one seems to have mentioned this in the countless number of threads like this...

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

How to change file encoding in NetBeans?

On project explorer, right click on the project, Properties -> General -> Encoding. This will allow you to choose the encoding per project.

How to explicitly obtain post data in Spring MVC?

You can simply just pass the attribute you want without any annotations in your controller:

@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
 //do stuff with valueOne variable here
}

Works with GET and POST

Convert integer to hex and hex to integer

To convert Hex strings to INT, I have used this in the past. It can be modified to convert any base to INT in fact (Octal, Binary, whatever)

Declare @Str varchar(200)
Set @str = 'F000BE1A'

Declare @ndx int
Set @ndx = Len(@str)
Declare @RunningTotal  BigInt
Set @RunningTotal = 0

While @ndx > 0
Begin
    Declare @Exponent BigInt
    Set @Exponent = Len(@Str) - @ndx

    Set @RunningTotal = @RunningTotal + 

    Power(16 * 1.0, @Exponent) *
    Case Substring(@str, @ndx, 1)
        When '0' then 0
        When '1' then 1
        When '2' then 2 
        When '3' then 3
        When '4' then 4
        When '5' then 5
        When '6' then 6
        When '7' then 7
        When '8' then 8
        When '9' then 9
        When 'A' then 10
        When 'B' then 11
        When 'C' then 12
        When 'D' then 13
        When 'E' then 14
        When 'F' then 15
    End
    Set @ndx = @ndx - 1
End

Print @RunningTotal

What is the significance of load factor in HashMap?

If the buckets get too full, then we have to look through

a very long linked list.

And that's kind of defeating the point.

So here's an example where I have four buckets.

I have elephant and badger in my HashSet so far.

This is a pretty good situation, right?

Each element has zero or one elements.

Now we put two more elements into our HashSet.

     buckets      elements
      -------      -------
        0          elephant
        1          otter
         2          badger
         3           cat

This isn't too bad either.

Every bucket only has one element . So if I wanna know, does this contain panda?

I can very quickly look at bucket number 1 and it's not

there and

I known it's not in our collection.

If I wanna know if it contains cat, I look at bucket

number 3,

I find cat, I very quickly know if it's in our

collection.

What if I add koala, well that's not so bad.

             buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala 
         2          badger
         3           cat

Maybe now instead of in bucket number 1 only looking at

one element,

I need to look at two.

But at least I don't have to look at elephant, badger and

cat.

If I'm again looking for panda, it can only be in bucket

number 1 and

I don't have to look at anything other then otter and

koala.

But now I put alligator in bucket number 1 and you can

see maybe where this is going.

That if bucket number 1 keeps getting bigger and bigger and

bigger, then I'm basically having to look through all of

those elements to find

something that should be in bucket number 1.

            buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala ->alligator
         2          badger
         3           cat

If I start adding strings to other buckets,

right, the problem just gets bigger and bigger in every

single bucket.

How do we stop our buckets from getting too full?

The solution here is that

          "the HashSet can automatically

        resize the number of buckets."

There's the HashSet realizes that the buckets are getting

too full.

It's losing this advantage of this all of one lookup for

elements.

And it'll just create more buckets(generally twice as before) and

then place the elements into the correct bucket.

So here's our basic HashSet implementation with separate

chaining. Now I'm going to create a "self-resizing HashSet".

This HashSet is going to realize that the buckets are

getting too full and

it needs more buckets.

loadFactor is another field in our HashSet class.

loadFactor represents the average number of elements per

bucket,

above which we want to resize.

loadFactor is a balance between space and time.

If the buckets get too full then we'll resize.

That takes time, of course, but

it may save us time down the road if the buckets are a

little more empty.

Let's see an example.

Here's a HashSet, we've added four elements so far.

Elephant, dog, cat and fish.

          buckets      elements
      -------      -------
        0          
        1          elephant
         2          cat ->dog
         3           fish
          4         
           5

At this point, I've decided that the loadFactor, the

threshold,

the average number of elements per bucket that I'm okay

with, is 0.75.

The number of buckets is buckets.length, which is 6, and

at this point our HashSet has four elements, so the

current size is 4.

We'll resize our HashSet, that is we'll add more buckets,

when the average number of elements per bucket exceeds

the loadFactor.

That is when current size divided by buckets.length is

greater than loadFactor.

At this point, the average number of elements per bucket

is 4 divided by 6.

4 elements, 6 buckets, that's 0.67.

That's less than the threshold I set of 0.75 so we're

okay.

We don't need to resize.

But now let's say we add woodchuck.

                  buckets      elements
      -------      -------
        0          
        1          elephant
         2        woodchuck-> cat ->dog
         3           fish
          4         
           5

Woodchuck would end up in bucket number 3.

At this point, the currentSize is 5.

And now the average number of elements per bucket

is the currentSize divided by buckets.length.

That's 5 elements divided by 6 buckets is 0.83.

And this exceeds the loadFactor which was 0.75.

In order to address this problem, in order to make the

buckets perhaps a little

more empty so that operations like determining whether a

bucket contains

an element will be a little less complex, I wanna resize

my HashSet.

Resizing the HashSet takes two steps.

First I'll double the number of buckets, I had 6 buckets,

now I'm going to have 12 buckets.

Note here that the loadFactor which I set to 0.75 stays the same.

But the number of buckets changed is 12,

the number of elements stayed the same, is 5.

5 divided by 12 is around 0.42, that's well under our

loadFactor,

so we're okay now.

But we're not done because some of these elements are in

the wrong bucket now.

For instance, elephant.

Elephant was in bucket number 2 because the number of

characters in elephant

was 8.

We have 6 buckets, 8 minus 6 is 2.

That's why it ended up in number 2.

But now that we have 12 buckets, 8 mod 12 is 8, so

elephant does not belong in bucket number 2 anymore.

Elephant belongs in bucket number 8.

What about woodchuck?

Woodchuck was the one that started this whole problem.

Woodchuck ended up in bucket number 3.

Because 9 mod 6 is 3.

But now we do 9 mod 12.

9 mod 12 is 9, woodchuck goes to bucket number 9.

And you see the advantage of all this.

Now bucket number 3 only has two elements whereas before it had 3.

So here's our code,

where we had our HashSet with separate chaining that

didn't do any resizing.

Now, here's a new implementation where we use resizing.

Most of this code is the same,

we're still going to determine whether it contains the

value already.

If it doesn't, then we'll figure it out which bucket it

should go into and

then add it to that bucket, add it to that LinkedList.

But now we increment the currentSize field.

currentSize was the field that kept track of the number

of elements in our HashSet.

We're going to increment it and then we're going to look

at the average load,

the average number of elements per bucket.

We'll do that division down here.

We have to do a little bit of casting here to make sure

that we get a double.

And then, we'll compare that average load to the field

that I've set as

0.75 when I created this HashSet, for instance, which was

the loadFactor.

If the average load is greater than the loadFactor,

that means there's too many elements per bucket on

average, and I need to reinsert.

So here's our implementation of the method to reinsert

all the elements.

First, I'll create a local variable called oldBuckets.

Which is referring to the buckets as they currently stand

before I start resizing everything.

Note I'm not creating a new array of linked lists just yet.

I'm just renaming buckets as oldBuckets.

Now remember buckets was a field in our class, I'm going

to now create a new array

of linked lists but this will have twice as many elements

as it did the first time.

Now I need to actually do the reinserting,

I'm going to iterate through all of the old buckets.

Each element in oldBuckets is a LinkedList of strings

that is a bucket.

I'll go through that bucket and get each element in that

bucket.

And now I'm gonna reinsert it into the newBuckets.

I will get its hashCode.

I will figure out which index it is.

And now I get the new bucket, the new LinkedList of

strings and

I'll add it to that new bucket.

So to recap, HashSets as we've seen are arrays of Linked

Lists, or buckets.

A self resizing HashSet can realize using some ratio or

Why is PHP session_destroy() not working?

session_destroy() is effective after the page load is complete. So in the second upload, the session is terminated. But with unset() you can also log out from within the page.

Getting IPV4 address from a sockaddr structure

You can use getnameinfo for Windows and for Linux.

Assuming you have a good (i.e. it's members have appropriate values) sockaddr* called pSockaddr:

char clienthost[NI_MAXHOST];  //The clienthost will hold the IP address.
char clientservice[NI_MAXSERV];
int theErrorCode = getnameinfo(pSockaddr, sizeof(*pSockaddr), clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV);

if( theErrorCode != 0 )
{
    //There was an error.
    cout << gai_strerror(e1) << endl;
}else{
    //Print the info.
    cout << "The ip address is = " << clienthost << endl;
    cout << "The clientservice = " << clientservice << endl;
}

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.

However, there is an easy "hack" for fixing this issue:

Before you execute your command(s) you first have to disable the foreign key constraints check using this command:

SET FOREIGN_KEY_CHECKS = 0;

Then you are able to execute your command(s).

After you are done, don't forget to enable the foreign key constraints check again, using this command:

SET FOREIGN_KEY_CHECKS = 1;

Good luck with your endeavor.

How to test if JSON object is empty in Java

A JSON notation {} represents an empty object, meaning an object without members. This is not the same as null. Neither it is string as you are trying to compare it with string "{}". I don't know which json library are you using, but try to look for method something like:

isEmptyObject() 

Printing prime numbers from 1 through 100

#include<iostream>
using namespace std;
void main()
{
        int num,i,j,prime;
    cout<<"Enter the upper limit :";
    cin>>num;
    cout<<"Prime numbers till "<<num<<" are :2, ";

    for(i=3;i<=num;i++)
    {
        prime=1;
        for(j=2;j<i;j++)
        {
            if(i%j==0)
            {
                prime=0;
                break;
            }
        }
        if(prime==1)
            cout<<i<<", ";
    }
}

random.seed(): What does it do?

Seed() can be used for later use ---

Example:
>>> import numpy as np
>>> np.random.seed(12)
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
>>>
>>> np.random.seed(12) # When you use same seed as before you will get same random output as before
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>

Custom Date/Time formatting in SQL Server

If dt is your datetime column, then

For 1:

SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)
    + UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))

For 2:

SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)
    + SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)

How to set HttpResponse timeout for Android in Java

If you are using the HttpURLConnection, call setConnectTimeout() as described here:

URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);

Difference between $(window).load() and $(document).ready() functions

From jquery prospective - it's just adding load/onload event to window and document. Check this out:

window.onload vs document.onload

Clear data in MySQL table with PHP?

TRUNCATE TABLE `table`

unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer

DELETE FROM `table`

though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using

ALTER TABLE `table` AUTO_INCREMENT = value

will happen a lot faster.

How do I replace text inside a div element?

Here's an easy jQuery way:

var el = $('#yourid .yourclass');

el.html(el.html().replace(/Old Text/ig, "New Text"));

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

I also have this problem today. The solution is setting your "ssh key". Click the url below, follow the steps, then you will sovle it.

http://github.com/guides/providing-your-ssh-key

Table fixed header and scrollable body

I made some kinda working CSS only solution by using position: sticky. Should work on evergreen browsers. Try to resize browser. Still have some layout issue in FF, will fix it later, but at least table headers handle vertical and horizontal scrolling. Codepen Example

Operator overloading ==, !=, Equals

In fact, this is a "how to" subject. So, here is the reference implementation:

    public class BOX
    {
        double height, length, breadth;

        public static bool operator == (BOX b1, BOX b2)
        {
            if ((object)b1 == null)
                return (object)b2 == null;

            return b1.Equals(b2);
        }

        public static bool operator != (BOX b1, BOX b2)
        {
            return !(b1 == b2);
        }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
                return false;

            var b2 = (BOX)obj;
            return (length == b2.length && breadth == b2.breadth && height == b2.height);
        }

        public override int GetHashCode()
        {
            return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode();
        }
    }

REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples

UPDATE: the cast to (object) in the operator == implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.

This (object) cast trick is from Microsoft String == implementaiton. SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643

JavaScript push to array

It's not an array.

var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;

or

var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;

you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)

var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});

Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Sergey is correct, but if you need to get a response from your home-spun dialog(s) for evaluation in the same block of code that invoked it, you should use .showAndWait(), not .show(). Here's my rendition of a couple of the dialog types that are provided in Swing's OptionPane:

public class FXOptionPane {

public enum Response { NO, YES, CANCEL };

private static Response buttonSelected = Response.CANCEL;

private static ImageView icon = new ImageView();

static class Dialog extends Stage {
    public Dialog( String title, Stage owner, Scene scene, String iconFile ) {
        setTitle( title );
        initStyle( StageStyle.UTILITY );
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        setResizable( false );
        setScene( scene );
        icon.setImage( new Image( getClass().getResourceAsStream( iconFile ) ) );
    }
    public void showDialog() {
        sizeToScene();
        centerOnScreen();
        showAndWait();
    }
}

static class Message extends Text {
    public Message( String msg ) {
        super( msg );
        setWrappingWidth( 250 );
    }
}

public static Response showConfirmDialog( Stage owner, String message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Confirm.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button yesButton = new Button( "Yes" );
    yesButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.YES;
        }
    } );
    Button noButton = new Button( "No" );
    noButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.NO;
        }
    } );
    BorderPane bp = new BorderPane();
    HBox buttons = new HBox();
    buttons.setAlignment( Pos.CENTER );
    buttons.setSpacing( 10 );
    buttons.getChildren().addAll( yesButton, noButton );
    bp.setCenter( buttons );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, new Message( message ) );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
    return buttonSelected;
}

public static void showMessageDialog( Stage owner, String message, String title ) {
    showMessageDialog( owner, new Message( message ), title );
}
public static void showMessageDialog( Stage owner, Node message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Info.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button okButton = new Button( "OK" );
    okButton.setAlignment( Pos.CENTER );
    okButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
        }
    } );
    BorderPane bp = new BorderPane();
    bp.setCenter( okButton );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, message );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
}

}

Python Remove last char from string and return it

Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with split() or separate it into two parts using indices:

a = "abc"
a, result = a[:-1], a[-1]

This shows that you're splitting your string in two. If you'll be examining every byte of the string, you can iterate over it (in reverse, if you wish):

for result in reversed(a):
    ...

I should add this seems a little contrived: Your string is more likely to have some separator, and then you'll use split:

ans = "foo,blah,etc."
for a in ans.split(","):
    ...

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

How to use 'find' to search for files created on a specific date?

You could do this:

find ./ -type f -ls |grep '10 Sep'

Example:

[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24

Java BigDecimal: Round to the nearest whole value

If i go by Grodriguez's answer

System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);

This is the output

100.23 -> 100
100.77 -> 101

Which isn't quite what i want, so i ended up doing this..

System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);

This is what i get

100.23 -> 100.00
100.77 -> 101.00

This solves my problem for now .. : ) Thank you all.

How to pass boolean parameter value in pipeline to downstream jobs?

Jenkins "boolean" parameters are really just a shortcut for the "choice parameter" type with the choices hardcoded to the strings "true" and "false", and with a checkbox to set the string variable. But in the end, it is just that: a string variable, with nothing to do with a true boolean. That's why you need to convert the string to a boolean if you don't want to do a string comparison like:

if (myBoolean == "true")

Installing Java 7 on Ubuntu

Oracle as well as modern versions of Ubuntu have moved to newer versions of Java. The default for Ubuntu 20.04 is OpenJDK 11 which is good enough for most purposes.

If you really need it for running legacy programs, OpenJDK 8 is also available for Ubuntu 20.04 from the official repositories.

If you really need exactly Java 7, the best bet as of 2020 is to download a Zulu distribution. The easiest to install if you have root privileges is the .DEB version, otherwise download the .ZIP one.

https://www.azul.com/downloads/zulu-community/?version=java-7-lts&os=ubuntu&architecture=x86-64-bit&package=jdk

Executing periodic actions in Python

Here's a nice implementation using the Thread class: http://g-off.net/software/a-python-repeatable-threadingtimer-class

the code below is a little more quick and dirty:

from threading import Timer
from time import sleep

def hello():
    print "hello, world"
    t = Timer(3,hello)
    t.start()

t = Timer(3, hello)
t.start() # after 3 seconds, "hello, world" will be printed

# timer will wake up ever 3 seconds, while we do something else
while True:
    print "do something else"
    sleep(10)

How to push a docker image to a private repository

Following are the steps to push Docker Image to Private Repository of DockerHub

1- First check Docker Images using command

docker images

2- Check Docker Tag command Help

docker tag help

3- Now Tag a name to your created Image

docker tag localImgName:tagName DockerHubUser\Private-repoName:tagName(tag name is optional. Default name is latest)

4- Before pushing Image to DockerHub Private Repo, first login to DockerHub using command

docker login [provide dockerHub username and Password to login]

5- Now push Docker Image to your private Repo using command

docker push [options] ImgName[:tag] e.g docker push DockerHubUser\Private-repoName:tagName

6- Now navigate to the DockerHub Private Repo and you will see Docker image is pushed on your private Repository with name written as TagName in previous steps

Get most recent file in a directory on Linux

ls -t -1 | sed '1q'

Will show the last modified item in the folder. Pair with grep to find latest entries with keywords

ls -t -1 | grep foo | sed '1q'

Count textarea characters

They say IE has issues with the input event but other than that, the solution is rather straightforward.

_x000D_
_x000D_
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
  count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
_x000D_
_x000D_

Merge development branch with master

If you are on Mac or Ubuntu, go to the working folder of the branch. In the terminal

suppose harisdev is the branchname.

git checkout master

if there are untracked or uncommitted files you will get an error and you have to commit or delete all the untracked or uncommitted files.

git merge harisdev 

git push origin master

One last command to delete the branch.

$ git branch -d harisdev

How to make a query with group_concat in sql server

Please run the below query, it doesn't requires STUFF and GROUP BY in your case:

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , CAST((
          SELECT  T.maskdetail+','
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH(''))as varchar(max)) as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

How to save image in database using C#

//Arrange the Picture Of Path.***

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

                    string[] PicPathArray;
                    string ArrangePathOfPic;

                    PicPathArray = openFileDialog1.FileName.Split('\\');

                    ArrangePathOfPic = PicPathArray[0] + "\\\\" + PicPathArray[1];
                    for (int a = 2; a < PicPathArray.Length; a++)
                    {
                        ArrangePathOfPic = ArrangePathOfPic + "\\\\" + PicPathArray[a];
                    }
               }

// Save the path Of Pic in database

                    SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                    con.Open();

                    SqlCommand cmd = new SqlCommand("insert into PictureTable (Pic_Path) values (@Pic_Path)", con);
                    cmd.Parameters.Add("@Pic_Path", SqlDbType.VarChar).Value = ArrangePathOfPic;

                    cmd.ExecuteNonQuery();

***// Get the Picture Path in Database.***

SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                con.Open();

                SqlCommand cmd = new SqlCommand("Select * from Pic_Path where ID = @ID", con);

                SqlDataAdapter adp = new SqlDataAdapter();
                cmd.Parameters.Add("@ID",SqlDbType.VarChar).Value = "1";
                adp.SelectCommand = cmd;

                DataTable DT = new DataTable();

                adp.Fill(DT);

                DataRow DR = DT.Rows[0];
                pictureBox1.Image = Image.FromFile(DR["Pic_Path"].ToString());

Clearing an input text field in Angular2

What about something like this, without a button:

<input type="text" placeholder="Search..." [value]="searchValue" onblur="this.value=''">

How to plot multiple functions on the same figure, in Matplotlib?

To plot multiple graphs on the same figure you will have to do:

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, 'r') # plotting t, a separately 
plt.plot(t, b, 'b') # plotting t, b separately 
plt.plot(t, c, 'g') # plotting t, c separately 
plt.show()

enter image description here

Deep cloning objects

This method solved the problem for me:

private static MyObj DeepCopy(MyObj source)
        {

            var DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };

            return JsonConvert.DeserializeObject<MyObj >(JsonConvert.SerializeObject(source), DeserializeSettings);

        }

Use it like this: MyObj a = DeepCopy(b);

Call method in directive controller from other controller

You can also use events to trigger the Popdown.

Here's a fiddle based on satchmorun's solution. It dispenses with the PopdownAPI, and the top-level controller instead $broadcasts 'success' and 'error' events down the scope chain:

$scope.success = function(msg) { $scope.$broadcast('success', msg); };
$scope.error   = function(msg) { $scope.$broadcast('error', msg); };

The Popdown module then registers handler functions for these events, e.g:

$scope.$on('success', function(event, msg) {
    $scope.status = 'success';
    $scope.message = msg;
    $scope.toggleDisplay();
});

This works, at least, and seems to me to be a nicely decoupled solution. I'll let others chime in if this is considered poor practice for some reason.

Show div when radio button selected

var switchData = $('#show-me');
switchData.hide();
$('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});

JSFIDDLE

Cannot drop database because it is currently in use

Just wanted to give a vb.net (as with c language if want to convert..) I was having similar problem for uninstal of one of my programs, dropping the DB was bit tricky, yes could get users to go into server drop it using Express, but thats not clean, after few looks around got a perfect little bit of code together...

    Sub DropMyDatabase()
    Dim Your_DB_To_Drop_Name As String = "YourDB"
    Dim Your_Connection_String_Here As String = "SERVER=MyServer;Integrated Security=True"
    Dim Conn As SqlConnection = New SqlConnection(Your_Connection_String_Here)

    Dim AlterStr As String = "ALTER DATABASE " & Your_DB_To_Drop_Name & " SET OFFLINE WITH ROLLBACK IMMEDIATE"
    Dim AlterCmd = New SqlCommand(AlterStr, Conn)

    Dim DropStr As String = "DROP DATABASE " & Your_DB_To_Drop_Name
    Dim DropCmd = New SqlCommand(DropStr, Conn)

    Try
        Conn.Open()
        AlterCmd.ExecuteNonQuery()
        DropCmd.ExecuteNonQuery()
        Conn.Close()

    Catch ex As Exception
        If (Conn.State = ConnectionState.Open) Then
            Conn.Close()
        End If
        MsgBox("Failed... Sorry!" & vbCrLf & vbCrLf & ex.Message)
    End Try
End Sub

Hope this helps anyone looking xChickenx

UPDATE Using this converter here is the C# version :

public void DropMyDatabase()
    {
        var Your_DB_To_Drop_Name = "YourDB";
        var Your_Connection_String_Here = "SERVER=MyServer;Integrated Security=True";
        var Conn = new SqlConnection(Your_Connection_String_Here);

        var AlterStr = "ALTER DATABASE " + Your_DB_To_Drop_Name + " SET OFFLINE WITH ROLLBACK IMMEDIATE";
        var AlterCmd = new SqlCommand(AlterStr, Conn);

        var DropStr = "DROP DATABASE " + Your_DB_To_Drop_Name;
        var DropCmd = new SqlCommand(DropStr, Conn);

        try
        {
            Conn.Open();
            AlterCmd.ExecuteNonQuery();
            DropCmd.ExecuteNonQuery();
            Conn.Close();

        }
        catch(Exception ex)
        {
            if((Conn.State == ConnectionState.Open))
            {
                Conn.Close();
            }
            Trace.WriteLine("Failed... Sorry!" + Environment.NewLine + ex.Message);
        }
    }

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

EDIT these lines in host file and it should work.

Host file usually located in C:\Windows\System32\drivers\etc\hosts

::1             localhost.localdomain localhost
127.0.0.1       localhost

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

Install php-mcrypt on CentOS 6

I was having same issue in centos 6.5

Finaly solution below worked for me

-go to http://dl.fedoraproject.org/pub/epel/6/x86_64/
-search for php-mcrypt(http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm)
-execute wget http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm
-rpm -ivh php-mcrypt-5.3.3-3.el6.x86_64.rpm

if there are any dependencies you can download same using http://dl.fedoraproject.org/pub/epel/6/x86_64/

How do you find out the type of an object (in Swift)?

Swift 2.0:

The proper way to do this kind of type introspection would be with the Mirror struct,

    let stringObject:String = "testing"
    let stringArrayObject:[String] = ["one", "two"]
    let viewObject = UIView()
    let anyObject:Any = "testing"

    let stringMirror = Mirror(reflecting: stringObject)
    let stringArrayMirror = Mirror(reflecting: stringArrayObject)
    let viewMirror = Mirror(reflecting: viewObject)
    let anyMirror = Mirror(reflecting: anyObject)

Then to access the type itself from the Mirror struct you would use the property subjectType like so:

    // Prints "String"
    print(stringMirror.subjectType)

    // Prints "Array<String>"
    print(stringArrayMirror.subjectType)

    // Prints "UIView"
    print(viewMirror.subjectType)

    // Prints "String"
    print(anyMirror.subjectType)

You can then use something like this:

    if anyMirror.subjectType == String.self {
        print("anyObject is a string!")
    } else {
        print("anyObject is not a string!")
    }

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

Since version 5, Qt uses a platform abstraction system (QPA) to abstract from the underlying platform.

The implementation for each platform is provided by plugins. For X11 it is the XCB plugin. See Qt for X11 requirements for more information about the dependencies.

I am not able launch JNLP applications using "Java Web Start"?

I know this is an older question but this past week I started to get a similar problem, so I leave here some notes regarding the solution that fits me.

This happened only in some Windows machines using even the last JRE to date (1.8.0_45).

The Java Web Start started to load but nothing happened and none of the previous solution attempts worked.

After some digging i've found this thread, which gives the same setup and a great explanation.

https://community.oracle.com/thread/3676876

So, in conclusion, it was a memory problem in x86 JRE and since our JNLP's max heap was defined as 1024MB, we changed to 780MB as suggested and it was fixed.

However, if you need more than 780MB, can always try launching in a x64 JRE version.

difference between throw and throw new Exception()

throw; rethrows the original exception and preserves its original stack trace.

throw ex; throws the original exception but resets the stack trace, destroying all stack trace information until your catch block.


NEVER write throw ex;


throw new Exception(ex.Message); is even worse. It creates a brand new Exception instance, losing the original stack trace of the exception, as well as its type. (eg, IOException).
In addition, some exceptions hold additional information (eg, ArgumentException.ParamName).
throw new Exception(ex.Message); will destroy this information too.

In certain cases, you may want to wrap all exceptions in a custom exception object, so that you can provide additional information about what the code was doing when the exception was thrown.

To do this, define a new class that inherits Exception, add all four exception constructors, and optionally an additional constructor that takes an InnerException as well as additional information, and throw your new exception class, passing ex as the InnerException parameter. By passing the original InnerException, you preserve all of the original exception's properties, including the stack trace.

C# Passing Function as Argument

Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:

public delegate double MyFunction(double x);

public double Diff(double x, MyFunction f)
{
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

public double MyFunctionMethod(double x)
{
    // Can add more complicated logic here
    return x + 10;
}

public void Client()
{
    double result = Diff(1.234, x => x * 456.1234);
    double secondResult = Diff(2.345, MyFunctionMethod);
}

How to make HTML input tag only accept numerical values?

It's better to add "+" to REGEX condition in order to accept multiple digits (not only one digit):

<input type="text" name="your_field" pattern="[0-9]+">

Where can I download IntelliJ IDEA Color Schemes?

If you're just looking for a dark color scheme for IntelliJ IDEA, this is the first link I get in a Google search:

Dark Pastels theme for IntelliJ IDEA Dark Pastels theme for IntelliJ IDEA

Of course, you can tweak either of these two schemes to your satisfaction. Don't feel like you have to stick to the fonts and the colors that the original authors have chosen. We programmers don't get nearly enough change to try our hand at interior decorating to pass up this opportunity.

Is there any reason these won't work in the version you have? As best I can tell, you can simply import any theme that you want.

Conda version pip install -r requirements.txt --target ./lib

You can run conda install --file requirements.txt instead of the loop, but there is no target directory in conda install. conda install installs a list of packages into a specified conda environment.

What is the difference between DBMS and RDBMS?

DBMS is the software program that is used to manage all the database that are stored on the network or system hard disk. whereas RDBMS is the database system in which the relationship among different tables are maintained.

Access Tomcat Manager App from different host

Each deployed webapp has a context.xml file that lives in

$CATALINA_BASE/conf/[enginename]/[hostname]

(conf/Catalina/localhost by default)

and has the same name as the webapp (manager.xml in this case). If no file is present, default values are used.

So, you need to create a file conf/Catalina/localhost/manager.xml and specify the rule you want to allow remote access. For example, the following content of manager.xml will allow access from all machines:

<Context privileged="true" antiResourceLocking="false" 
         docBase="${catalina.home}/webapps/manager">
    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>

Note that the allow attribute of the Valve element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).

Other Valve classes cater for other rules (e.g. RemoteHostValve for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.

Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml you should have access to the Manager.

Format date and time in a Windows batch script

Using % you will run into a hex operation error when the time value is 7-9. To avoid this, use DelayedExpansion and grab time values with !min:~1!

An alternate method, if you have PowerShell is to call that:

for /F "usebackq delims=Z" %%i IN (`powershell Get-Date -format u`) do (set server-time=%%i)

How to specify test directory for mocha?

I am on Windows 7 using node.js v0.10.0 and mocha v1.8.2 and npm v1.2.14. I was just trying to get mocha to use the path test/unit to find my tests, After spending to long and trying several things I landed,

Using the "test/unit/*.js" option does not work on windows. For good reasons that windows shell doesn't expand wildcards like unixen.

However using "test/unit" does work, without the file pattern. eg. "mocha test/unit" runs all files found in test/unit folder.

This only still runs one folder files as tests but you can pass multiple directory names as parameters.

Also to run a single test file you can specify the full path and filename. eg. "mocha test/unit/mytest1.js"

I actually setup in package.json for npm "scripts": { "test": "mocha test/unit" },

So that 'npm test' runs my unit tests.

git ignore vim temporary files

sure,

just have to create a ".gitignore" on the home directory of your project and have to contain

*.swp

that's it

in one command

project-home-directory$ echo '*.swp' >> .gitignore

Quicksort: Choosing the pivot

Don't try and get too clever and combine pivoting strategies. If you combined median of 3 with random pivot by picking the median of the first, last and a random index in the middle, then you'll still be vulnerable to many of the distributions which send median of 3 quadratic (so its actually worse than plain random pivot)

E.g a pipe organ distribution (1,2,3...N/2..3,2,1) first and last will both be 1 and the random index will be some number greater than 1, taking the median gives 1 (either first or last) and you get an extermely unbalanced partitioning.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

If non of above works for you, make sure tomcat has access to manager folder under webapps (chown ...). The message is the exact same message, and It took me 2 hours to figure out the problem. :-)

just for someone else who came here for the same issue as me.

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

Probably the easiest way is:

SELECT EXTRACT(epoch FROM my_interval)/3600

Processing $http response in service

When binding the UI to your array you'll want to make sure you update that same array directly by setting the length to 0 and pushing the data into the array.

Instead of this (which set a different array reference to data which your UI won't know about):

 myService.async = function() {
    $http.get('test.json')
    .success(function (d) {
      data = d;
    });
  };

try this:

 myService.async = function() {
    $http.get('test.json')
    .success(function (d) {
      data.length = 0;
      for(var i = 0; i < d.length; i++){
        data.push(d[i]);
      }
    });
  };

Here is a fiddle that shows the difference between setting a new array vs emptying and adding to an existing one. I couldn't get your plnkr working but hopefully this works for you!

How to check if a character in a string is a digit or letter

This is the way how to check whether a given character is alphabet or not

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    char c = sc.next().charAt(0); 
    if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
         System.out.println(c + " is an alphabet.");
    else
        System.out.println(c + " is not an alphabet.");
}

How to hide a TemplateField column in a GridView

For Each dcfColumn As DataControlField In gvGridview.Columns
    If dcfColumn.HeaderText = "ColumnHeaderText" Then
        dcfColumn.Visible = false                    
    End If
Next

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

jQuery get the name of a select option

Using name on a select option is not valid.

Other have suggested the data- attribute, an alternative is a lookup table

Here the "this" refers to the select so no need to "find" the option

_x000D_
_x000D_
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
  $('#band_type_choices').on('change', function() {_x000D_
    $('.checkboxlist').hide();_x000D_
    var idx = this.selectedIndex;_x000D_
    if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
  });_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
  <option vlaue="0"></option>_x000D_
  <option value="100" name="acoustic">Acoustic</option>_x000D_
  <option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
  <option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
  <option value="0" name="party">Party</option>_x000D_
  <option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
  <option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
  <option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
  <input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
  <input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
  <input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
  <input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
  <input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
  <input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
  <input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
  <input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
  <input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
  <input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
  <input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Changing permissions via chmod at runtime errors with "Operation not permitted"

This is a tricky question.

There a set of problems about file permissions. If you can do this at the command line

$ sudo chown myaccount /path/to/file

then you have a standard permissions problem. Make sure you own the file and have permission to modify the directory.

If you cannnot get permissions, then you have probably mounted a FAT-32 filesystem. If you ls -l the file, and you find it is owned by root and a member of the "plugdev" group, then you are certain its the issue. FAT-32 permissions are set at the time of mounting, using the line of /etc/fstab file. You can set the uid/gid of all the files like this:

UUID=C14C-CE25  /big            vfat    utf8,umask=007,uid=1000,gid=1000 0       1

Also, note that the FAT-32 won't take symbolic links.

Wrote the whole thing up at http://www.charlesmerriam.com/blog/2009/12/operation-not-permitted-and-the-fat-32-system/

Resolving IP Address from hostname with PowerShell

Use Resolve-DnsName cmdlet.

Resolve-DnsName computername | FT Name, IPAddress -HideTableHeaders | Out-File -Append c:\filename.txt

PS C:\> Resolve-DnsName stackoverflow.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
stackoverflow.com                              A      130   Answer     151.101.65.69
stackoverflow.com                              A      130   Answer     151.101.129.69
stackoverflow.com                              A      130   Answer     151.101.193.69
stackoverflow.com                              A      130   Answer     151.101.1.69

PS C:\> Resolve-DnsName stackoverflow.com | Format-Table Name, IPAddress -HideTableHeaders

stackoverflow.com 151.101.65.69
stackoverflow.com 151.101.1.69
stackoverflow.com 151.101.193.69
stackoverflow.com 151.101.129.69

PS C:\> Resolve-DnsName -Type A google.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
google.com                                     A      16    Answer     216.58.193.78


PS C:\> Resolve-DnsName -Type AAAA google.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
google.com                                     AAAA   223   Answer     2607:f8b0:400e:c04::64

ActionBarActivity is deprecated

android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."

checkout changes for Android Support Library, revision 22.1.0 (April 2015)

How to get named excel sheets while exporting from SSRS

There is no direct way. You either export XML and then right an XSLT to format it properly (this is the hard way). An easier way is to write multiple reports with no explicit page breaks so each exports into one sheet only in excel and then write a script that would merge for you. Either way it requires a postprocessing step.

How can I clear the SQL Server query cache?

While the question is just a bit old, this might still help. I'm running into similar issues and using the option below has helped me. Not sure if this is a permanent solution, but it's fixing it for now.

OPTION (OPTIMIZE FOR UNKNOWN)

Then your query will be like this

select * from Table where Col = 'someval' OPTION (OPTIMIZE FOR UNKNOWN)

Resetting a form in Angular 2 after submit

Now NgForm supports two methods: .reset() vs .resetForm() the latter also changes the submit state of the form to false reverting form and its controls to initial states.

Deploy a project using Git push

In essence all you need to do are the following:

server = $1
branch = $2
git push $server $branch
ssh <username>@$server "cd /path/to/www; git pull"

I have those lines in my application as an executable called deploy.

so when I want to do a deploy I type ./deploy myserver mybranch.

How to create XML file with specific structure in Java

Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

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

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

How to change the name of an iOS app?

  1. Go to Targets in Xcode.
  2. Get Info on your project's target (your current development name).
  3. Search for Product Name under Packaging. Change its value to what you want your new project name to be.

How to get random value out of an array?

You can also do just:

$k = array_rand($array);
$v = $array[$k];

This is the way to do it when you have an associative array.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

How to validate a date?

Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'? I think NOT, because the YEAR is not validated ;(

My proposition is to use improved version of this function:

//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
        var bits = input.split('-');
        var d = new Date(bits[0], bits[1] - 1, bits[2]);
        return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}

How to detect when a UIScrollView has finished scrolling

I've tried Ashley Smart's answer and it worked like a charm. Here's another idea, with using only scrollViewDidScroll

-(void)scrollViewDidScroll:(UIScrollView *)sender 
{   
    if(self.scrollView_Result.contentOffset.x == self.scrollView_Result.frame.size.width)       {
    // You have reached page 1
    }
}

I just had two pages so it worked for me. However, if you have more than one page, it could be problematic (you could check whether the current offset is a multiple of the width but then you wouldn't know if the user stopped at 2nd page or is on his way to 3rd or more)

ERROR: Google Maps API error: MissingKeyMapError

All Google Maps JavaScript API applications require authentication( API KEY )

  1. Go to https://developers.google.com/maps/documentation/javascript/get-api-key.
  2. Login with Google Account
  3. Click on Get a key button 3 Select or create a project
  4. Click on Enable API ( Google Maps API)
  5. Copy YOUR API KEY in your Project: <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>

Docker is installed but Docker Compose is not ? why?

first of all please check if docker-compose is installed,

$ docker-compose -v

If it is not installed, please refer to the installation guide https://docs.docker.com/compose/install/ If installed give executable permission to the binary.

$ chmod +x /usr/local/bin/docker-compose

check if this works.

PHP function ssh2_connect is not working

If you are running a bomebrew on OSX, I used the following to install it:

brew install php56-ssh2

That worked for me. I pulled it from here. There should also be Ubuntu and OSX using mac port as well.

What is a quick way to force CRLF in C# / .NET?

input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")

This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.

PHP: how can I get file creation date?

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';

if (file_exists($filename)) {

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

How to download all dependencies and packages to directory

This will download all packages and dependencies (no already installed) to a directory of your choice:

sudo apt-get install -d -o Dir::Cache=/path-to/directory/apt/cache -o Dir::State::Lists=/path-to/directory/apt/lists packages

Make sure /path-to/directory/apt/cache and /path-to/directory/apt/lists exist. If you don't set -o Dir::Cache it points to /var/cache/apt, Dir::State::Lists points to /var/lib/apt/lists (which keeps the index files of available packages)

Both -o options can be used with update and upgrade instead of install.

On different machine run the same command without '-d'

Razor View Engine : An expression tree may not contain a dynamic operation

It seems to me that you have an untyped view. By default, Razor views in MVC3 RC are typed as dynamic. However, lambdas do not support dynamic members. You have to strongly type your model. At the top of your view file add

@model SampleModel

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

Python allows you to use a string as an iterator:

for character in 'string':
    print(character)

I'm guessing it's your job to figure out how to turn that into a while loop.

Strict Standards: Only variables should be assigned by reference PHP 5.4

You should remove the & (ampersand) symbol, so that line 4 will look like this:

$conn = ADONewConnection($config['db_type']);

This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0

How do I create a folder in a GitHub repository?

TL;DR Use / in the file name field to create folder(s), e.g. typing folder1/file1 in the file name field will create a folder folder1 and a file file1.

Original answer
You cannot create an empty folder and then add files to that folder, but rather creation of a folder must happen together with adding of at least a single file. This is because got doesn't track empty folders.

On GitHub you can do it this way:

  • Go to the folder inside which you want to create another folder
  • Click on New file
  • On the text field for the file name, first write the folder name you want to create
  • Then type /. This creates a folder
  • You can add more folders similarly
  • Finally, give the new file a name (for example, .gitkeep which is conventionally used to make Git track otherwise empty folders; it is not a Git feature though)
  • Finally, click Commit new file.

Java: How to Indent XML Generated by Transformer

Neither of the suggested solutions worked for me. So I kept on searching for an alternative solution, which ended up being a mixture of the two before mentioned and a third step.

  1. set the indent-number into the transformerfactory
  2. enable the indent in the transformer
  3. wrap the otuputstream with a writer (or bufferedwriter)
//(1)
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", new Integer(2));

//(2)
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");

//(3)
t.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "utf-8"));

You must do (3) to workaround a "buggy" behavior of the xml handling code.

Source: johnnymac75 @ http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446

(If I have cited my source incorrectly please let me know)

How to concat a string to xsl:value-of select="...?

Use:

<a href="wantedText{/*/properties/property[@name='report']/@value)}"></a>

Android: how to hide ActionBar on certain activities

Add New Style in your style.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="LoginTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

and then add following line in your manifest

<activity android:name=".Login"
        android:label="@string/app_name"
        android:theme="@style/LoginTheme"
        >

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

TLDR: Changing the DNS server to the loop back address worked for me.

I am working in VirtualBox and had setup two Windows Server 2016 instances. Server A is configure as a Domain Controller and Server B as an SQL Server. After adding Server B to the domain I cold not connect to with Management Studio from Server A. I was getting the "The login is from an untrusted domain and cannot be used with Windows authentication".

My initial configuration had the server getting its IP from the VirtualBox DHCP server.

I changed this to use static IP and entered the 127.0.0.1 address in the Primary DNS and this worked for me.

Hope this helps someone passing by.

How to change the default docker registry from docker.io to my private registry?

There is the use case of a mirror of Docker Hub (such as Artifactory or a custom one), which I haven't seen mentioned here. This is one of the most valid cases where changing the default registry is needed.

Luckily, Docker (at least version 19.03.3) allows you to set a mirror (tested in Docker CE). I don't know if this will work with additional images pushed to that mirror that aren't on Docker Hub, but I do know it will use the mirror instead. Docker documentation: https://docs.docker.com/registry/recipes/mirror/#configure-the-docker-daemon.

Essentially, you need to add "registry-mirrors": [] to the /etc/docker/daemon.json configuration file. So if you have a mirror hosted at https://my-docker-repo.my.company.com, your /etc/docker/daemon.json should contain:

{
  "registry-mirrors": ["https://my-docker-repo-mirror.my.company.com"]
}

Afterwards, restart the Docker daemon. Now if you do a docker pull postgres:12, Docker should fetch the image from the mirror instead of directly from Docker Hub. This is much better than prepending all images with my-docker-repo.my.company.com

Checking letter case (Upper/Lower) within a string in Java

A quick look through the documentation on regular expression sytanx should bring up ways to tell if it contains a lower/upper case character at some point.

How to print a percentage value in python?

Just for the sake of completeness, since I noticed no one suggested this simple approach:

>>> print("%.0f%%" % (100 * 1.0/3))
33%

Details:

  • %.0f stands for "print a float with 0 decimal places", so %.2f would print 33.33
  • %% prints a literal %. A bit cleaner than your original +'%'
  • 1.0 instead of 1 takes care of coercing the division to float, so no more 0.0

Copy every nth line from one sheet to another

insert a new column and put a series in 1,2,3,4, etc. Then create another new column and use the command =if(int(a1/7)=(a1/7),1,0) you should get a 1 in every 7th row, filter the column on the 1

What is a good pattern for using a Global Mutex in C#?

I want to make sure this is out there, because it's so hard to get right:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

Equivalent of .bat in mac os

May be you can find answer here? Equivalent of double-clickable .sh and .bat on Mac?

Usually you can create bash script for Mac OS, where you put similar commands as in batch file. For your case create bash file and put same command, but change back-slashes with regular ones.

Your file will look something like:

#! /bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;./supportlibraries/Framework_DataTable.jar;./supportlibraries/Framework_Reporting.jar;./supportlibraries/Framework_Utilities.jar;./supportlibraries/poi-3.8-20120326.jar;PATH_TO_YOUR_SELENIUM_SERVER_FOLDER/selenium-server-standalone-2.19.0.jar" allocator.testTrack

Change folders in path above to relevant one.

Then make this script executable: open terminal and navigate to folder with your script. Then change read-write-execute rights for this file running command:

chmod 755 scriptname.sh

Then you can run it like any other regular script: ./scriptname.sh

or you can run it passing file to bash:

bash scriptname.sh

Strings in C, how to get subString

char largeSrt[] = "123456789-123";  // original string

char * substr;
substr = strchr(largeSrt, '-');     // we save the new string "-123"
int substringLength = strlen(largeSrt) - strlen(substr); // 13-4=9 (bigger string size) - (new string size) 

char *newStr = malloc(sizeof(char) * substringLength + 1);// keep memory free to new string
strcpy(newStr, largeSrt, substringLength);  // copy only 9 characters 
newStr[substringLength] = '\0'; // close the new string with final character

printf("newStr=%s\n", newStr);

free(newStr);   // you free the memory 

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

Using jquery to delete all elements with a given id

id of dom element shout be unique. Use class instead (<span class='myclass'>). To remove all span with this class:

$('.myclass').remove()

wordpress contactform7 textarea cols and rows change in smaller screens

I know this post is old, sorry for that.

You can also type 10x for cols and x2 for rows, if you want to have only one attribute.

[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->

RSpec: how to test if a method was called?

it "should call 'bar' with appropriate arguments" do
  expect(subject).to receive(:bar).with("an argument I want")
  subject.foo
end

Can't find SDK folder inside Android studio path, and SDK manager not opening

Make sure all the folders are visible. click start>control panel>Appearance and Personalization>Show hidden files and folders then click "Show hidden files, folders and drives" The file should be in C:\Users\Username\AppData\Local\Android as mentioned above. otherwise you can check by opening Android SDK Manager - top left under SDK path.

Should I call Close() or Dispose() for stream objects?

On many classes which support both Close() and Dispose() methods, the two calls would be equivalent. On some classes, however, it is possible to re-open an object which has been closed. Some such classes may keep some resources alive after a Close, in order to permit reopening; others may not keep any resources alive on Close(), but might set a flag on Dispose() to explicitly forbid re-opening.

The contract for IDisposable.Dispose explicitly requires that calling it on an object which will never be used again will be at worst harmless, so I would recommend calling either IDisposable.Dispose or a method called Dispose() on every IDisposable object, whether or not one also calls Close().

Handling the null value from a resultset in JAVA

To treat validation when a field is null in the database, you could add the following condition.

String name = (oRs.getString ("name_column"))! = Null? oRs.getString ("name_column"): "";

with this you can validate when a field is null and do not mark an exception.

Does calling clone() on an array also clone its contents?

The clone is a shallow copy of the array.

This test code prints:

[1, 2] / [1, 2]
[100, 200] / [100, 2]

because the MutableInteger is shared in both arrays as objects[0] and objects2[0], but you can change the reference objects[1] independently from objects2[1].

import java.util.Arrays;                                                                                                                                 

public class CloneTest {                                                                                                                                 
    static class MutableInteger {                                                                                                                        
        int value;                                                                                                                                       
        MutableInteger(int value) {                                                                                                                      
            this.value = value;                                                                                                                          
        }                                                                                                                                                
        @Override                                                                                                                                        
        public String toString() {                                                                                                                       
            return Integer.toString(value);                                                                                                              
        }                                                                                                                                                
    }                                                                                                                                                    
    public static void main(String[] args) {                                                                                                             
        MutableInteger[] objects = new MutableInteger[] {
                new MutableInteger(1), new MutableInteger(2) };                                                
        MutableInteger[] objects2 = objects.clone();                                                                                                     
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                                
        objects[0].value = 100;                                                                                                                          
        objects[1] = new MutableInteger(200);                                                                                                            
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                               
    }                                                                                                                                                    
}                                                                                                                                                        

SQL to LINQ Tool

I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).

When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.

It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.

How can I use a DLL file from Python?

ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.

I would encourage you to check out Boost Python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from Microsoft.

How to remove lines in a Matplotlib plot

This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around.

WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.

Okay, here we go. Each matplotlib object (Figure, Axes, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating.

We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id()).

>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]

>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)

>>> #The object in ax is the same as the object in fig.axes[0], which is 
>>> #   a list of axes objects attached to fig 
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8)  #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects

This also extends to lines in an axes object:

>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))

>>> #Lines and ax.lines contain the same line2D instances 
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]

>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)

>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)

If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line:

A figure containing a set of axes and a single line

Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:

>>> id(lines), id(ax.lines)
(212754584, 211335288)

As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:

>>> #THIS DOES NOTHING:
>>> lines.pop(0)

>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)

So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:

>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and two lines

>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and only the second line

All of the above works for fig.axes just as well as it works for ax.lines

Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn't get garbage collected:

>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]

>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn't have the same ID as ax.lines but contained the same elements? Well, that's the problem.

>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.

>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>

So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.

open the file upload dialogue box onclick the image

HTML Code:

 <form method="post" action="#" id="#">
<div class="form-group files color">
    <input type="file" class="form-control" multiple="">
</div>

CSS:

.files input {
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
padding: 120px 0px 85px 35%;
text-align: center !important;
margin: 0;
width: 100% !important;
height: 400px;

}

.files input:focus{    
    outline: 2px dashed #92b0b3; 
    outline-offset: -10px;
   -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
    transition: outline-offset .15s ease-in-out, background-color .15s linear;
  border:1px solid #92b0b3;

}

.files{ position:relative}
   .files:after {  pointer-events: none;
     position: absolute;
     top: 60px;
     left: 0;
    width: 50px;
   right: 0;
   height: 400px;
  content: "";
  background-image: url('../../images/');
  display: block;
  margin: 0 auto;
  background-size: 100%;
  background-repeat: no-repeat;

}

.color input{ background-color:#f1f1f1;}
.files:before {
  position: absolute;
  bottom: 10px;
   left: 0;  pointer-events: none;
  width: 100%;
  right: 0;
  height: 400px;
  display: block;
  margin: 0 auto;
  color: #2ea591;
  font-weight: 600;
  text-transform: capitalize;
  text-align: center;

}

What is the official name for a credit card's 3 digit code?

It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).

Card Security Code

Binary search (bisection) in Python

def binary_search_length_of_a_list(single_method_list):
    index = 0
    first = 0
    last = 1

    while True:
        mid = ((first + last) // 2)
        if not single_method_list.get(index):
            break
        index = mid + 1
        first = index
        last = index + 1
    return mid

How to inherit constructors?

As Foo is a class can you not create virtual overloaded Initialise() methods? Then they would be available to sub-classes and still extensible?

public class Foo
{
   ...
   public Foo() {...}

   public virtual void Initialise(int i) {...}
   public virtual void Initialise(int i, int i) {...}
   public virtual void Initialise(int i, int i, int i) {...}
   ... 
   public virtual void Initialise(int i, int i, ..., int i) {...}

   ...

   public virtual void SomethingElse() {...}
   ...
}

This shouldn't have a higher performance cost unless you have lots of default property values and you hit it a lot.

Vue.js get selected option on @change

The changed value will be in event.target.value

_x000D_
_x000D_
const app = new Vue({_x000D_
  el: "#app",_x000D_
  data: function() {_x000D_
    return {_x000D_
      message: "Vue"_x000D_
    }_x000D_
  },_x000D_
  methods: {_x000D_
    onChange(event) {_x000D_
      console.log(event.target.value);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <select name="LeaveType" @change="onChange" class="form-control">_x000D_
   <option value="1">Annual Leave/ Off-Day</option>_x000D_
   <option value="2">On Demand Leave</option>_x000D_
</select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Method call if not null in C#

Events can be initialized with an empty default delegate which is never removed:

public event EventHandler MyEvent = delegate { };

No null-checking necessary.

[Update, thanks to Bevan for pointing this out]

Be aware of the possible performance impact, though. A quick micro benchmark I did indicates that handling an event with no subscribers is 2-3 times slower when using the the "default delegate" pattern. (On my dual core 2.5GHz laptop that means 279ms : 785ms for raising 50 million not-subscribed events.). For application hot spots, that might be an issue to consider.

Is it better practice to use String.format over string Concatenation in Java?

There could be a perceptible difference.

String.format is quite complex and uses a regular expression underneath, so don't make it a habit to use it everywhere, but only where you need it.

StringBuilder would be an order of magnitude faster (as someone here already pointed out).

How to retrieve all keys (or values) from a std::map and put them into a vector?

There is a boost range adaptor for this purpose:

#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/copy.hpp>
vector<int> keys;
boost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));

There is a similar map_values range adaptor for extracting the values.

Is it possible to delete an object's property in PHP?

This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

Fast Linux file count for a large number of files

Fast Linux file count

The fastest Linux file count I know is

locate -c -r '/home'

There is no need to invoke grep! But as mentioned, you should have a fresh database (updated daily by a cron job, or manual by sudo updatedb).

From man locate

-c, --count
    Instead  of  writing  file  names on standard output, write the number of matching
    entries only.

Additional, you should know that it also counts the directories as files!


BTW: If you want an overview of your files and directories on your system type

locate -S

It outputs the number of directories, files, etc.

Change fill color on vector asset in Android Studio

To change vector image color you can directly use android:tint="@color/colorAccent"

<ImageView
        android:id="@+id/ivVectorImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_account_circle_black_24dp"
        android:tint="@color/colorAccent" />

To change color programatically

ImageView ivVectorImage = (ImageView) findViewById(R.id.ivVectorImage);
ivVectorImage.setColorFilter(getResources().getColor(R.color.colorPrimary));

Connecting to Oracle Database through C#?

Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:

  • Install Oracle Client , and add bin location to Path environment varaible of windows OR
  • Copy oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version), oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Create Elasticsearch curl query for not null and not empty("")

You need to use bool query with must/must_not and exists

To get where place is null

{
  "query": {
    "bool": {
      "must_not": {
        "exists": {
          "field": "place"
        }
      }
    }
  }
}

To get where place is not null

{
  "query": {
    "bool": {
      "must": {
        "exists": {
          "field": "place"
        }
      }
    }
  }
}

MySQL - Operand should contain 1 column(s)

(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)

Here you using sub-query but this sub-query must return only one column. Separate it otherwise it will shows error.

How can I get the content of CKEditor using JQuery?

var value = CKEDITOR.instances['YourInstanceName'].getData()
 alert( value);

Replace YourInstanceName with the name of your instance and you will get the desired results.

The module ".dll" was loaded but the entry-point was not found

I had this problem and

dumpbin /exports mydll.dll

and

depends mydll.dll

showed 'DllRegisterServer'.

The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

If you are loading JSON string from a file & file contents arabic texts. Then this will work.

Assume File like: arabic.json

{ 
"key1" : "?????????",
"key2" : "????? ??????"
}

Get the arabic contents from the arabic.json file

with open(arabic.json, encoding='utf-8') as f:
   # deserialises it
   json_data = json.load(f)
   f.close()


# json formatted string
json_data2 = json.dumps(json_data, ensure_ascii = False)

To use JSON Data in Django Template follow below steps:

# If have to get the JSON index in Django Template file, then simply decode the encoded string.

json.JSONDecoder().decode(json_data2)

done! Now we can get the results as JSON index with arabic value.

Get Current date in epoch from Unix shell script

Update: The answer previously posted here linked to a custom script that is no longer available, solely because the OP indicated that date +'%s' didn't work for him. Please see UberAlex' answer and cadrian's answer for proper solutions. In short:

  1. For the number of seconds since the Unix epoch use date(1) as follows:

    date +'%s'
    
  2. For the number of days since the Unix epoch divide the result by the number of seconds in a day (mind the double parentheses!):

    echo $(($(date +%s) / 60 / 60 / 24))
    

ansible : how to pass multiple commands

To run multiple shell commands with ansible you can use the shell module with a multi-line string (note the pipe after shell:), as shown in this example:

  - name: Build nginx 
    shell: |
      cd nginx-1.11.13
      sudo ./configure
      sudo make
      sudo make install

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

How about playing with these two properties?

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

hasBackdrop: boolean - Whether the dialog has a backdrop.

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

Rename package in Android Studio

for example if you want change package from com.example.a to com.example.b

1)change project style folder from android to package (in project side)

2)right click top of folder and click replace in path

3)select in project button

4)in first input write com.example.a

5)in second input write com.example.b

6)when you see warning select replace all to replace value

after finish replace you can see your package name is com.example.b

Does Java have an exponential operator?

To do this with user input:

public static void getPow(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first integer: ");    // 3
    int first = sc.nextInt();
    System.out.println("Enter second integer: ");    // 2
    int second = sc.nextInt();
    System.out.println(first + " to the power of " + second + " is " + 
        (int) Math.pow(first, second));    // outputs 9

Is it safe to use Project Lombok?

There are long-term maintenance risks as well. First, I'd recommend reading about how Lombok actually works, e.g. some answers from its developers here.

The official site also contains a list of downsides, including this quote from Reinier Zwitserloot:

It's a total hack. Using non-public API. Presumptuous casting (knowing that an annotation processor running in javac will get an instance of JavacAnnotationProcessor, which is the internal implementation of AnnotationProcessor (an interface), which so happens to have a couple of extra methods that are used to get at the live AST).

On eclipse, it's arguably worse (and yet more robust) - a java agent is used to inject code into the eclipse grammar and parser class, which is of course entirely non-public API and totally off limits.

If you could do what lombok does with standard API, I would have done it that way, but you can't. Still, for what its worth, I developed the eclipse plugin for eclipse v3.5 running on java 1.6, and without making any changes it worked on eclipse v3.4 running on java 1.5 as well, so it's not completely fragile.

As a summary, while Lombok may save you some development time, if there is a non-backwards compatible javac update (e.g. a vulnerability mitigation) Lombok might get you stuck with an old version of Java while the developers scramble to update their usage of those internal APIs. Whether this is a serious risk obviously depends on the project.

How to add icon to mat-icon-button

My preference is to utilize the inline attribute. This will cause the icon to correctly scale with the size of the button.

    <button mat-button>
      <mat-icon inline=true>local_movies</mat-icon>
      Movies
    </button>

    <!-- Link button -->
    <a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>

I add this to my styles.css to:

  • solve the vertical alignment problem of the icon inside the button
  • material icon fonts are always a little too small compared to button text
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
  vertical-align: top;
  font-size: 1.25em;
}

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

Strange "java.lang.NoClassDefFoundError" in Eclipse

While this is a wild guess and may not be applicable in your specific situation, this could've saved me an hour or so.

In case you have "converted" a plain project into Java project (by editing .project file and adding appropriate tag), make sure you also have a proper specified - my project didn't get built even though Eclipse attempted to and run no builders (success!):

<buildSpec>
    <buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
    </buildCommand>
</buildSpec>

CSS3 :unchecked pseudo-class

The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!

Using Linq select list inside list

list.Where(m => m.application == "applicationName" && 
           m.users.Any(u => u.surname=="surname"));

if you want to filter users as TimSchmelter commented, you can use

list.Where(m => m.application == "applicationName")
    .Select(m => new Model
    {
        application = m.application,
        users = m.users.Where(u => u.surname=="surname").ToList()
    });

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

Node Version Manager (NVM) on Windows

Nvm can be used to manage various node version :

  • Step1: Download nvm for Windows

  • Step2: Choose nvm-setup.zip

  • Step3: Unzip & click on installer.

  • Step4: Check if nvm properly installed, In new command prompt type nvm

  • Step5: Install node js using nvm : nvm install <version> : The version can be a node.js version or "latest" for the latest stable version

  • Step6: check node version - node -v

  • Step7(Optional)If you want to install another version of node js - Use STEP 5 with different version.

  • Step8: Check list node js version - nvm list

  • Step9: If you want to use specific node version do - nvm use <version>

Why doesn't Java support unsigned ints?

This is from an interview with Gosling and others, about simplicity:

Gosling: For me as a language designer, which I don't really count myself as these days, what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. That definition says that, for instance, Java isn't -- and in fact a lot of these languages end up with a lot of corner cases, things that nobody really understands. Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex. The language part of Java is, I think, pretty simple. The libraries you have to look up.

Get connection status on Socket.io client

You can check the socket.connected property:

var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
  console.log('check 2', socket.connected);
});

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

Another solution would be to catch disconnect events and track the status yourself.

MySQL JOIN ON vs USING?

Wikipedia has the following information about USING:

The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join. In the case above, there will be a single DepartmentID column and no employee.DepartmentID or department.DepartmentID.

Tables that it was talking about:

enter image description here

The Postgres documentation also defines them pretty well:

The ON clause is the most general kind of join condition: it takes a Boolean value expression of the same kind as is used in a WHERE clause. A pair of rows from T1 and T2 match if the ON expression evaluates to true.

The USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.

Furthermore, the output of JOIN USING suppresses redundant columns: there is no need to print both of the matched columns, since they must have equal values. While JOIN ON produces all columns from T1 followed by all columns from T2, JOIN USING produces one output column for each of the listed column pairs (in the listed order), followed by any remaining columns from T1, followed by any remaining columns from T2.

Checking if a variable is not nil and not zero in ruby

unless discount.nil? || discount == 0
  # ...
end

Regex to get string between curly braces

Try this:

/[^{\}]+(?=})/g

For example

Welcome to RegExr v2.1 by #{gskinner.com},  #{ssd.sd} hosted by Media Temple!

will return gskinner.com, ssd.sd.

Password Strength Meter

Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/

I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?

c# replace \" characters

Try it like this:

Replace("\\\"","");

This will replace occurrences of \" with empty string.

Ex:

string t = "\\\"the dog is my friend\\\"";
t = t.Replace("\\\"","");

This will result in:

the dog is my friend