Programs & Examples On #Message forwarding

Apache won't run in xampp

Skype, try closing it and then running xampp, if it works then change the skype port to stop using port 80

Safely override C++ virtual functions

Make the function abstract, so that derived classes have no other choice than to override it.

@Ray Your code is invalid.

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

Abstract functions cannot have bodies defined inline. It must be modified to become

class parent {
public:
  virtual void handle_event(int something) const = 0;
};

void parent::handle_event( int something ) { /* do w/e you want here. */ }

How to get text from EditText?

Well, it depends on your needs. Very often I keep my references to widgets in activity (as a class fields) - and set them in onCreate method. I think that is a good idea
Probably the reason for your nulls is that you are trying to call findViewById() before you set contentView() in your onCreate() method - please check that.

Creating a UIImage from a UIColor to use as a background image for UIButton

CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Tools >> Options >> Designers and uncheck “Prevent Saving changes that require table re-creation”:

Description in Photos format

How to convert a string to integer in C?

Don't use functions from ato... group. These are broken and virtually useless. A moderately better solution would be to use sscanf, although it is not perfect either.

To convert string to integer, functions from strto... group should be used. In your specific case it would be strtol function.

How to delete the first row of a dataframe in R?

I am not expert, but this may work as well,

dat <- dat[2:nrow(dat), ]

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

Regex how to match an optional character

You have to mark the single letter as optional too:

([A-Z]{1})? +.*? +

or make the whole part optional

(([A-Z]{1}) +.*? +)?

Sublime Text 2 - Show file navigation in sidebar

This is not exactly a solution, but for opening new files this works great:

AdvancedNewFile

https://github.com/skuroda/Sublime-AdvancedNewFile

Command + Option + n to save a file in a new or existing directory.

enter image description here

So this would place your_file.html.erb in the existing views directory in a Rails app. If you needed a new directory -you would just type that as the path and then hit enter.

You can also Tab like in terminal to autocomplete for existing directories.

This does not give the sidebar navigation I am looking for, but at least helps with one significant need that is repeated often.

generate random string for div id

I also needed a random id, I went with using base64 encoding:

btoa(Math.random()).substring(0,12)

Pick however many characters you want, the result is usually at least 24 characters.

Docker container will automatically stop after "docker run -d"

I have this code snippet run from the ENTRYPOINT in my docker file:

while true
do
    echo "Press [CTRL+C] to stop.."
    sleep 1
done

Run the built docker image as:

docker run -td <image name>

Log in to the container shell:

docker exec -it <container id> /bin/bash

Convert a list to a string in C#

If your list has fields/properties and you want to use a specific value (e.g. FirstName), then you can do this:

string combindedString = string.Join( ",", myList.Select(t=>t.FirstName).ToArray() );

What is the difference between pull and clone in git?

git clone <remote-url> <=>

  • create a new directory
  • git init // init new repository
  • git remote add origin <remote-url> // add remote
  • git fetch // fetch all remote branchs
  • git switch <default_branch> // switch to the default branch

git pull <=>

  • fetch ALL remote branches
  • merge CURRENT local branch with tracking remote branch (not another branch) (if local branch existed)

git pull <remote> <branch> <=>

  • fetch the remote branch
  • merge CURRENT local branch with the remote branch (if local branch existed)

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

Even if above solutions don't work, check permissions to destination file of aws ec2 instance. May be you can try with- sudo chmod 777 -R destinationFolder/*

How can I use grep to show just filenames on Linux?

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case.

How to select the last column of dataframe

This is another way to do it. I think maybe a little more general:

df.ix[:,-1]

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

Extracting time from POSIXct

Here's an update for those looking for a tidyverse method to extract hh:mm::ss.sssss from a POSIXct object. Note that time zone is not included in the output.

library(hms)
as_hms(times)

Renaming files using node.js

For linux/unix OS, you can use the shell syntax

const shell = require('child_process').execSync ; 

const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;

shell(`mv ${currentPath} ${newPath}`);

That's it!

Get keys of a Typescript interface as array of strings

I had a similar problem that I had a giant list of properties that I wanted to have both an interface, and an object out of it.

NOTE: I didn't want to write (type with keyboard) the properties twice! Just DRY.


One thing to note here is, interfaces are enforced types at compile-time, while objects are mostly run-time. (Source)

As @derek mentioned in another answer, the common denominator of interface and object can be a class that serves both a type and a value.

So, TL;DR, the following piece of code should satisfy the needs:

class MyTableClass {
    // list the propeties here, ONLY WRITTEN ONCE
    id = "";
    title = "";
    isDeleted = false;
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// This is the pure interface version, to be used/exported
interface IMyTable extends MyTableClass { };

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Props type as an array, to be exported
type MyTablePropsArray = Array<keyof IMyTable>;

// Props array itself!
const propsArray: MyTablePropsArray =
    Object.keys(new MyTableClass()) as MyTablePropsArray;

console.log(propsArray); // prints out  ["id", "title", "isDeleted"]


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Example of creating a pure instance as an object
const tableInstance: MyTableClass = { // works properly!
    id: "3",
    title: "hi",
    isDeleted: false,
};

(Here is the above code in Typescript Playground to play more)

PS. If you don't want to assign initial values to the properties in the class, and stay with the type, you can do the constructor trick:

class MyTableClass {
    // list the propeties here, ONLY WRITTEN ONCE
    constructor(
        readonly id?: string,
        readonly title?: string,
        readonly isDeleted?: boolean,
    ) {}
}

console.log(Object.keys(new MyTableClass()));  // prints out  ["id", "title", "isDeleted"] 

Constructor Trick in TypeScript Playground.

Using Jquery Ajax to retrieve data from Mysql


You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.

AjaxGet = function (url) {
    var result = $.ajax({
        type: "POST",
        url: url,
       param: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
       async: false,
        success: function (data) {
            // nothing needed here
      }
    }) .responseText ;
    return  result;
}

jQuery return ajax result into outside variable

You are missing a comma after

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }

Also, if you want return_first to hold the result of your anonymous function, you need to make a function call:

var return_first = function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
}();

Note () at the end.

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

You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm

Through this command you will become the owner of the file.

Or, you can be a member of a group that owns this file and then you can use chmod.

But, talk with your sysadmin.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

Read response body in JAX-RS client from a post request

I just found a solution for jaxrs-ri-2.16 - simply use

String output = response.readEntity(String.class)

this delivers the content as expected.

Returning Arrays in Java

You need to do something with the return value...

import java.util.Arrays;

public class trial1{

    public static void main(String[] args){
        int[] B = numbers();
        System.out.println(Arrays.toString(B));
    }

    public static int[] numbers(){
        int[] A = {1,2,3};
        return A;
    }
}

In a Bash script, how can I exit the entire script if a certain condition occurs?

I have the same question but cannot ask it because it would be a duplicate.

The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).

Here is a little script on how to do it:

#!/bin/bash

boom() {
    while true; do sleep 1.2; echo boom; done
}

f() {
    echo Hello
    N=0
    while
        ((N++ <10))
    do
        sleep 1
        echo $N
        #        ((N > 5)) && exit 4 # does not work
        ((N > 5)) && { kill -9 $$; exit 5; } # works 
    done
}

boom &
f &

while true; do sleep 0.5; echo beep; done

This is a better answer but still incomplete a I really don't know how to get rid of the boom part.

PHP, Get tomorrows date from date

Use DateTime

$datetime = new DateTime('tomorrow');
echo $datetime->format('Y-m-d H:i:s');

Or:

$datetime = new DateTime('2013-01-22');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

Or:

$datetime = new DateTime('2013-01-22');
$datetime->add(new DateInterval("P1D"));
echo $datetime->format('Y-m-d H:i:s');

Or in PHP 5.4+:

echo (new DateTime('2013-01-22'))->add(new DateInterval("P1D"))
                                 ->format('Y-m-d H:i:s');

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

Executing multi-line statements in the one-line command-line?

The problem is not with the import statement. The problem is that the control flow statements don't work inlined in a python command. Replace that import statement with any other statement and you'll see the same problem.

Think about it: python can't possibly inline everything. It uses indentation to group control-flow.

Pip - Fatal error in launcher: Unable to create process using '"'

I fixed my issue by...

  1. downloading Python 3 at the official website and installing it via express installation
  2. Copy & Paste the standalone python into the ampps/python folder and overwriting the python version provided by AMPPS
  3. running python -m pip install --upgrade pip in cmd

Now pip and python 3 are installed in their latest version.

It seems that AMPPS doesnt't provide a full-fledged python build. So you need to update python yourself.

Thanks to y'all.

How to watch for form changes in Angular

If you are using FormBuilder, see @dfsq's answer.

If you are not using FormBuilder, there are two ways to be notified of changes.

Method 1

As discussed in the comments on the question, use an event binding on each input element. Add to your template:

<input type="text" class="form-control" required [ngModel]="model.first_name"
         (ngModelChange)="doSomething($event)">

Then in your component:

doSomething(newValue) {
  model.first_name = newValue;
  console.log(newValue)
}

The Forms page has some additional information about ngModel that is relevant here:

The ngModelChange is not an <input> element event. It is actually an event property of the NgModel directive. When Angular sees a binding target in the form [(x)], it expects the x directive to have an x input property and an xChange output property.

The other oddity is the template expression, model.name = $event. We're used to seeing an $event object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an Angular EventEmitter property that returns the input box value when it fires..

We almost always prefer [(ngModel)]. We might split the binding if we had to do something special in the event handling such as debounce or throttle the key strokes.

In your case, I suppose you want to do something special.

Method 2

Define a local template variable and set it to ngForm.
Use ngControl on the input elements.
Get a reference to the form's NgForm directive using @ViewChild, then subscribe to the NgForm's ControlGroup for changes:

<form #myForm="ngForm" (ngSubmit)="onSubmit()">
  ....
  <input type="text" ngControl="firstName" class="form-control" 
   required [(ngModel)]="model.first_name">
  ...
  <input type="text" ngControl="lastName" class="form-control" 
   required [(ngModel)]="model.last_name">

class MyForm {
  @ViewChild('myForm') form;
  ...
  ngAfterViewInit() {
    console.log(this.form)
    this.form.control.valueChanges
      .subscribe(values => this.doSomething(values));
  }
  doSomething(values) {
    console.log(values);
  }
}

plunker

For more information on Method 2, see Savkin's video.

See also @Thierry's answer for more information on what you can do with the valueChanges observable (such as debouncing/waiting a bit before processing changes).

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

Fit cell width to content

Simple :

    <div style='overflow-x:scroll;overflow-y:scroll;width:100%;height:100%'>

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

Algorithm to randomly generate an aesthetically-pleasing color palette

Use distinct-colors.

Written in javascript.

It generates a palette of visually distinct colors.

distinct-colors is highly configurable:

  • Choose how many colors are in the palette
  • Restrict the hue to a specific range
  • Restrict the chroma (saturation) to a specific range
  • Restrict the lightness to a specific range
  • Configure general quality of the palette

Toolbar overlapping below status bar

None of the answers worked for me, but this is what finally worked after I set:

android:fitsSystemWindows="false"

In parent activity layout file it's not suggested at many places but it's work for me and saves my day

What happened to console.log in IE8?

I'm using Walter's approach from above (see: https://stackoverflow.com/a/14246240/3076102)

I mix in a solution I found here https://stackoverflow.com/a/7967670 to properly show Objects.

This means the trap function becomes:

function trap(){
    if(debugging){
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var index;
        for (index = 0; index < args.length; ++index) {
            //fix for objects
            if(typeof args[index] === 'object'){ 
                args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
            }
        }
        var message = args.join(' ');
        console.messages.push(message);
        // instead of a fallback function we use the next few lines to output logs
        // at the bottom of the page with jQuery
        if($){
            if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
            $('#_console_log').append(message).append($('<br />'));
        }
    }
} 

I hope this is helpful:-)

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

How do you fade in/out a background color using jquery?

javascript fade to white without jQuery or other library:

<div id="x" style="background-color:rgb(255,255,105)">hello world</div>
<script type="text/javascript">
var gEvent=setInterval("toWhite();", 100);
function toWhite(){
    var obj=document.getElementById("x");
    var unBlue=10+parseInt(obj.style.backgroundColor.split(",")[2].replace(/\D/g,""));
    if(unBlue>245) unBlue=255;
    if(unBlue<256) obj.style.backgroundColor="rgb(255,255,"+unBlue+")";
    else clearInterval(gEvent)
}
</script>

In printing, yellow is minus blue, so starting with the 3rd rgb element (blue) at less than 255 starts out with a yellow highlight. Then the 10+ in setting the var unBlue value increments the minus blue until it reaches 255.

What is the function __construct used for?

class Person{
 private $fname;
 private $lname;

 public function __construct($fname,$lname){
  $this->fname = $fname;
  $this->lname = $lname;
 }
}
$objPerson1 = new Person('john','smith');

How to create a HTTP server in Android?

Another server you can try http://tjws.sf.net, actually it already provides Android enabled version.

How to call Stored Procedure in a View?

exec sp_addlinkedserver 
        @server = 'local',
        @srvproduct = '',
        @provider='SQLNCLI',
        @datasrc = @@SERVERNAME
go

create view ViewTest
as
select * from openquery(local, 'sp_who')
go

select * from ViewTest
go

How to calculate modulus of large numbers?

What you're looking for is modular exponentiation, specifically modular binary exponentiation. This wikipedia link has pseudocode.

convert float into varchar in SQL server without scientific notation

select format(convert(float,@your_column),'0.0#########')

Advantage: This solution is irrespective of the source datatype (float, scientific, varchar, date etc)

String is limited to 10 digits, bigInt gets rid of decimal values

Check if list contains element that contains a string and get that element

string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
  //found
}

Java - Convert int to Byte Array of 4 Bytes?

This should work:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

Code taken from here.

Edit An even simpler solution is given in this thread.

How to insert DECIMAL into MySQL database

I noticed something else about your coding.... look

INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')

in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be

'0',

you put

0,

lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)

UPDATE.....

I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol

When to use margin vs padding in CSS

Here is some HTML that demonstrates how padding and margin affect clickability, and background filling. An object receives clicks to its padding, but clicks on an objects margin'd area go to its parent.

_x000D_
_x000D_
$(".outer").click(function(e) {_x000D_
  console.log("outer");_x000D_
  e.stopPropagation();_x000D_
});_x000D_
_x000D_
$(".inner").click(function(e) {_x000D_
  console.log("inner");_x000D_
  e.stopPropagation();_x000D_
});
_x000D_
.outer {_x000D_
  padding: 10px;_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  margin: 10px;_x000D_
  padding: 10px;_x000D_
  background: blue;_x000D_
  border: solid white 1px;_x000D_
}
_x000D_
<script src="http://code.jquery.com/jquery-latest.js"></script>_x000D_
_x000D_
<div class="outer">_x000D_
  <div class="inner" style="position:relative; height:0px; width:0px">_x000D_
_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is it worth using Python's re.compile?

I've had a lot of experience running a compiled regex 1000s of times versus compiling on-the-fly, and have not noticed any perceivable difference. Obviously, this is anecdotal, and certainly not a great argument against compiling, but I've found the difference to be negligible.

EDIT: After a quick glance at the actual Python 2.5 library code, I see that Python internally compiles AND CACHES regexes whenever you use them anyway (including calls to re.match()), so you're really only changing WHEN the regex gets compiled, and shouldn't be saving much time at all - only the time it takes to check the cache (a key lookup on an internal dict type).

From module re.py (comments are mine):

def match(pattern, string, flags=0):
    return _compile(pattern, flags).match(string)

def _compile(*key):

    # Does cache check at top of function
    cachekey = (type(key[0]),) + key
    p = _cache.get(cachekey)
    if p is not None: return p

    # ...
    # Does actual compilation on cache miss
    # ...

    # Caches compiled regex
    if len(_cache) >= _MAXCACHE:
        _cache.clear()
    _cache[cachekey] = p
    return p

I still often pre-compile regular expressions, but only to bind them to a nice, reusable name, not for any expected performance gain.

Integer to hex string in C++

Just have a look on my solution,[1] that I verbatim copied from my project, so there a German is API doc included. My goal was to combine flexibility and safety within my actual needs:[2]

  • no 0x prefix added: caller may decide
  • automatic width deduction: less typing
  • explicit width control: widening for formatting, (lossless) shrinking to save space
  • capable for dealing with long long
  • restricted to integral types: avoid surprises by silent conversions
  • ease of understanding
  • no hard-coded limit
#include <string>
#include <sstream>
#include <iomanip>

/// Vertextet einen Ganzzahlwert val im Hexadezimalformat.
/// Auf die Minimal-Breite width wird mit führenden Nullen aufgefüllt;
/// falls nicht angegeben, wird diese Breite aus dem Typ des Arguments
/// abgeleitet. Funktion geeignet von char bis long long.
/// Zeiger, Fließkommazahlen u.ä. werden nicht unterstützt, ihre
/// Übergabe führt zu einem (beabsichtigten!) Compilerfehler.
/// Grundlagen aus: http://stackoverflow.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
    std::stringstream ss;
    ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
    return ss.str();
}

[1] based on the answer by Kornel Kisielewicz
[2] Translated into the language of CppTest, this is how it reads:

TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
// with deduction test as suggested by Lightness Races in Orbit:
TEST_ASSERT(int_to_hex(short(0x12)) == "0012"); 

Best way to represent a fraction in Java?

Class Fraction:

     public class Fraction {
        private int num;            // numerator 
        private int denom;          // denominator 
        // default constructor
        public Fraction() {}
        // constructor
        public Fraction( int a, int b ) {
            num = a;
            if ( b == 0 )
                throw new ZeroDenomException();
            else
                denom = b;
        }
        // return string representation of ComplexNumber
        @Override
        public String toString() {
            return "( " + num + " / " + denom + " )";
        }
        // the addition operation
        public Fraction add(Fraction x){
            return new Fraction(
                    x.num * denom + x.denom * num, x.denom * denom );
        }
        // the multiplication operation
        public Fraction multiply(Fraction x) {
            return new Fraction(x.num * num, x.denom * denom);
        } 
}

The main program:

    static void main(String[] args){
    Scanner input = new Scanner(System.in);
    System.out.println("Enter numerator and denominator of first fraction");
    int num1 =input.nextInt();
    int denom1 =input.nextInt();
    Fraction x = new Fraction(num1, denom1);
    System.out.println("Enter numerator and denominator of second fraction");
    int num2 =input.nextInt();
    int denom2 =input.nextInt();
    Fraction y = new Fraction(num2, denom2);
    Fraction result = new Fraction();
    System.out.println("Enter required operation: A (Add), M (Multiply)");
    char op = input.next().charAt(0);
    if(op == 'A') {
        result = x.add(y);
        System.out.println(x + " + " + y + " = " + result);
    }

Timer function to provide time in nano seconds using C++

Here is a nice Boost timer that works well:

//Stopwatch.hpp

#ifndef STOPWATCH_HPP
#define STOPWATCH_HPP

//Boost
#include <boost/chrono.hpp>
//Std
#include <cstdint>

class Stopwatch
{
public:
    Stopwatch();
    virtual         ~Stopwatch();
    void            Restart();
    std::uint64_t   Get_elapsed_ns();
    std::uint64_t   Get_elapsed_us();
    std::uint64_t   Get_elapsed_ms();
    std::uint64_t   Get_elapsed_s();
private:
    boost::chrono::high_resolution_clock::time_point _start_time;
};

#endif // STOPWATCH_HPP


//Stopwatch.cpp

#include "Stopwatch.hpp"

Stopwatch::Stopwatch():
    _start_time(boost::chrono::high_resolution_clock::now()) {}

Stopwatch::~Stopwatch() {}

void Stopwatch::Restart()
{
    _start_time = boost::chrono::high_resolution_clock::now();
}

std::uint64_t Stopwatch::Get_elapsed_ns()
{
    boost::chrono::nanoseconds nano_s = boost::chrono::duration_cast<boost::chrono::nanoseconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(nano_s.count());
}

std::uint64_t Stopwatch::Get_elapsed_us()
{
    boost::chrono::microseconds micro_s = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(micro_s.count());
}

std::uint64_t Stopwatch::Get_elapsed_ms()
{
    boost::chrono::milliseconds milli_s = boost::chrono::duration_cast<boost::chrono::milliseconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(milli_s.count());
}

std::uint64_t Stopwatch::Get_elapsed_s()
{
    boost::chrono::seconds sec = boost::chrono::duration_cast<boost::chrono::seconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(sec.count());
}

Is Fortran easier to optimize than C for heavy calculations?

Using modern standards and compiler, no!

Some of the folks here have suggested that FORTRAN is faster because the compiler doesn't need to worry about aliasing (and hence can make more assumptions during optimisation). However, this has been dealt with in C since the C99 (I think) standard with the inclusion of the restrict keyword. Which basically tells the compiler, that within a give scope, the pointer is not aliased. Furthermore C enables proper pointer arithmetic, where things like aliasing can be very useful in terms of performance and resource allocation. Although I think more recent version of FORTRAN enable the use of "proper" pointers.

For modern implementations C general outperforms FORTRAN (although it is very fast too).

http://benchmarksgame.alioth.debian.org/u64q/fortran.html

EDIT:

A fair criticism of this seems to be that the benchmarking may be biased. Here is another source (relative to C) that puts result in more context:

http://julialang.org/benchmarks/

You can see that C typically outperforms Fortran in most instances (again see criticisms below that apply here too); as others have stated, benchmarking is an inexact science that can be easily loaded to favour one language over others. But it does put in context how Fortran and C have similar performance.

Assigning out/ref parameters in Moq

I struggled with many of the suggestions here before I simple created an instance of a new 'Fake' class that implements whatever interface you are trying to Mock out. Then you can simply set the value of the out parameter with the method itself.

Plotting a 2D heatmap with Matplotlib

For a 2d numpy array, simply use imshow() may help you:

import matplotlib.pyplot as plt
import numpy as np


def heatmap2d(arr: np.ndarray):
    plt.imshow(arr, cmap='viridis')
    plt.colorbar()
    plt.show()


test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)

The heatmap of the example code

This code produces a continuous heatmap.

You can choose another built-in colormap from here.

Updating address bar with new URL without hash or reloading the page

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>

EDIT

I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

@Component
public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

Show loading gif after clicking form submit using jQuery

Better and clean example using JS only

Reference: TheDeveloperBlog.com

Step 1 - Create your java script and place it in your HTML page.

<script type="text/javascript">
    function ShowLoading(e) {
        var div = document.createElement('div');
        var img = document.createElement('img');
        img.src = 'loading_bar.GIF';
        div.innerHTML = "Loading...<br />";
        div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
        div.appendChild(img);
        document.body.appendChild(div);
        return true;
        // These 2 lines cancel form submission, so only use if needed.
        //window.event.cancelBubble = true;
        //e.stopPropagation();
    }
</script>

in your form call the java script function on submit event.

<form runat="server"  onsubmit="ShowLoading()">
</form>

Soon after you submit the form, it will show you the loading image.

Call angularjs function using jquery/javascript

One doesn't need to give id for the controller. It can simply called as following

angular.element(document.querySelector('[ng-controller="HeaderCtrl"]')).scope().myFunc()

Here HeaderCtrl is the controller name defined in your JS

Xcode "Build and Archive" from command line

I found some of the other answers here hard to get going. This article did if for me. Some paths may need to be absolute, as mentioned in the other answers.

The Command:

xcrun -sdk iphoneos PackageApplication \
    "/path/to/build/MyApp.app" \
    -o "output/path/to/MyApp.ipa" \
    --sign "iPhone Distribution: My Company" \
    --embed "/path/to/something.mobileprovision"

How to parse a query string into a NameValueCollection in .NET

HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:

NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      queryParameters.Add(key, val);
   }
}

Can I start the iPhone simulator without "Build and Run"?

The simulator is just an application, and as such you can run it like any other application.

To run the simulator straight from terminal prepend these locations with the open command

Xcode 7.x, 8.x, and 9.x

In Xcode 7.x, the iPhone Simulator has moved again: /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app.

Xcode 6.x

In Xcode 6.x, the iPhone Simulator has moved yet again, and now resides here: /Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app.


Xcode 4.x, 5.x

In Xcode 4.x (through 4.5 on Mountain Lion) and Xcode 5.0.x on Mavericks, it lives here: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/

In my version of Xcode (4.5.2), I find it quite convenient to use the Open Developer Tool menu from either the dock icon or the Xcode menu:

open iOS Simulator


Xcode 3.x

In Xcode 3.x, it lives here:

/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone Simulator.app


In some future version of Xcode, it will probably move again, it's a squirrelly little app.

SQL Inner join more than two tables

A possible solution:

SELECT Company.Company_Id,Company.Company_Name,
    Invoice_Details.Invoice_No, Product_Details.Price
  FROM Company inner join Invoice_Details
    ON Company.Company_Id=Invoice_Details.Company_Id
 INNER JOIN Product_Details
        ON Invoice_Details.Invoice_No= Product_Details.Invoice_No
 WHERE Price='60000';

-- tets changes

How do I parse a string into a number with Dart?

As per dart 2.6

The optional onError parameter of int.parse is deprecated. Therefore, you should use int.tryParse instead.

Note: The same applies to double.parse. Therefore, use double.tryParse instead.

  /**
   * ...
   *
   * The [onError] parameter is deprecated and will be removed.
   * Instead of `int.parse(string, onError: (string) => ...)`,
   * you should use `int.tryParse(string) ?? (...)`.
   *
   * ...
   */
  external static int parse(String source, {int radix, @deprecated int onError(String source)});

The difference is that int.tryParse returns null if the source string is invalid.

  /**
   * Parse [source] as a, possibly signed, integer literal and return its value.
   *
   * Like [parse] except that this function returns `null` where a
   * similar call to [parse] would throw a [FormatException],
   * and the [source] must still not be `null`.
   */
  external static int tryParse(String source, {int radix});

So, in your case it should look like:

// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345

// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
  print(parsedValue2); // null
  //
  // handle the error here ...
  //
}

How to run vi on docker container?

Alternatively, keep your docker images small by not installing unnecessary editors. You can edit the files over ssh from the docker host to the container:

vim scp://remoteuser@container-ip//path/to/document

How do I update the GUI from another thread?

Here's a new look on an age-old issue using a more functional style. If you keep the TaskXM class in all of your projects you only have one line of code to never worry about cross-thread updates again.

public class Example
{
    /// <summary>
    /// No more delegates, background workers, etc. Just one line of code as shown below.
    /// Note it is dependent on the Task Extension method shown next.
    /// </summary>
    public async void Method1()
    {
        // Still on the GUI thread here if the method was called from the GUI thread
        // This code below calls the extension method which spins up a new task and calls back.
        await TaskXM.RunCodeAsync(() =>
        {
            // Running an asynchronous task here
            // Cannot update the GUI thread here, but can do lots of work
        });
        // Can update GUI on this line
    }
}


/// <summary>
/// A class containing extension methods for the Task class
/// </summary>
public static class TaskXM
{
    /// <summary>
    /// RunCodeAsyc is an extension method that encapsulates the Task.run using a callback
    /// </summary>
    /// <param name="Code">The caller is called back on the new Task (on a different thread)</param>
    /// <returns></returns>
    public async static Task RunCodeAsync(Action Code)
    {
        await Task.Run(() =>
        {
            Code();
        });
        return;
    }
}

Using Postman to access OAuth 2.0 Google APIs

  1. go to https://console.developers.google.com/apis/credentials
  2. create web application credentials.

Postman API Access

  1. use these settings with oauth2 in Postman:

SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema

post https: //www.googleapis.com/admin/directory/v1/customer/customer-id/schemas

{
  "fields": [
    {
      "fieldName": "role",
      "fieldType": "STRING",
      "multiValued": true,
      "readAccessType": "ADMINS_AND_SELF"
    }
  ],
  "schemaName": "SAML"
}
  1. to patch user use:

SCOPE = https://www.googleapis.com/auth/admin.directory.user

PATCH https://www.googleapis.com/admin/directory/v1/users/[email protected]

 {
  "customSchemas": {
     "SAML": {
       "role": [
         {
          "value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
          "customType": "Admin"
         }
       ]
     }
   }
}

failed to find target with hash string android-23

I fixed the issue for me by opening the Android SDK Manager and installing the build tools for all 23.x.x versions.

See the screenshot.

enter image description here

Short circuit Array.forEach like calling break

Another concept I came up with:

_x000D_
_x000D_
function forEach(array, cb) {_x000D_
  var shouldBreak;_x000D_
  function _break() { shouldBreak = true; }_x000D_
  for (var i = 0, bound = array.length; i < bound; ++i) {_x000D_
    if (shouldBreak) { break; }_x000D_
    cb(array[i], i, array, _break);_x000D_
  }_x000D_
}_x000D_
_x000D_
// Usage_x000D_
_x000D_
forEach(['a','b','c','d','e','f'], function (char, i, array, _break) {_x000D_
  console.log(i, char);_x000D_
  if (i === 2) { _break(); }_x000D_
});
_x000D_
_x000D_
_x000D_

how to remove "," from a string in javascript

If U want to delete more than one characters, say comma and dots you can write

<script type="text/javascript">
  var mystring = "It,is,a,test.string,of.mine" 
  mystring = mystring.replace(/[,.]/g , ''); 
  alert( mystring);
</script>

Copying formula to the next row when inserting a new row

You need to insert the new row and then copy from the source row to the newly inserted row. Excel allows you to paste special just formulas. So in Excel:

  • Insert the new row
  • Copy the source row
  • Select the newly created target row, right click and paste special
  • Paste as formulas

VBA if required with Rows("1:1") being source and Rows("2:2") being target:

Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("2:2").Clear

Rows("1:1").Copy
Rows("2:2").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

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

One more solution with resolving by name:

@Resource(name="country")

It uses javax.annotation package, so it's not Spring specific, but Spring supports it.

read word by word from file in C++

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word;
while (file >> word)
{
    ...
}

Scroll Automatically to the Bottom of the Page

Below should be the cross browser solution. It has been tested on Chrome, Firefox, Safari and IE11

window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);

window.scrollTo(0,document.body.scrollHeight); doesn't work on Firefox, at least for Firefox 37.0.2

Data access object (DAO) in Java

I think the best example (along with explanations) you can find on the oracle website : here. Another good tuturial could be found here.

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Tooltip with HTML content without JavaScript

Using the title attribute:

_x000D_
_x000D_
<a href="#" title="Tooltip here">Link</a>
_x000D_
_x000D_
_x000D_

document.getElementById("test").style.display="hidden" not working

Using jQuery:

   $('#test').hide();

Using Javascript:

document.getElementById("test").style.display="none";

Threw an error "Cannot set property 'display' of undefined"

So, fix for this would be:

document.getElementById("test").style="display:none";

where your html code will look like this:

<div style="display:inline-block" id="test"></div>

ipynb import another ipynb file

It is really simple in newer Jupyter:

%run MyOtherNotebook.ipynb

regular expression: match any word until first space

Perhaps you could try ([^ ]+) .*, which should give you everything to the first blank in your first group.

How to select different app.config for several build configurations

Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :

 <None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />

 <None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />

Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!

Alter MySQL table to add comments on columns

The information schema isn't the place to treat these things (see DDL database commands).

When you add a comment you need to change the table structure (table comments).

From MySQL 5.6 documentation:

INFORMATION_SCHEMA is a database within each MySQL instance, the place that stores information about all the other databases that the MySQL server maintains. The INFORMATION_SCHEMA database contains several read-only tables. They are actually views, not base tables, so there are no files associated with them, and you cannot set triggers on them. Also, there is no database directory with that name.

Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.

Chapter 21 INFORMATION_SCHEMA Tables

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

Swift 2.0

// Checking if app is running iOS 8
    if application.respondsToSelector("isRegisteredForRemoteNotifications") {

        print("registerApplicationForPushNotifications - iOS 8")

        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil));
        application.registerForRemoteNotifications()

    } else {
        // Register for Push Notifications before iOS 8
        print("registerApplicationForPushNotifications - <iOS 8")
        application.registerForRemoteNotificationTypes([UIRemoteNotificationType.Alert, UIRemoteNotificationType.Badge, UIRemoteNotificationType.Sound])

    }

Removing the fragment identifier from AngularJS urls (# symbol)

Be sure to check browser support for the html5 history API:

  if(window.history && window.history.pushState){
    $locationProvider.html5Mode(true);
  }

How to change the display name for LabelFor in razor in mvc3?

You can change the labels' text by adorning the property with the DisplayName attribute.

[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }

Or, you could write the raw HTML explicitly:

<label for="SomekingStatus" class="control-label">Someking Status</label>

PHPDoc type hinting for array of objects?

To specify a variable is an array of objects:

$needles = getAllNeedles();
/* @var $needles Needle[] */
$needles[1]->...                        //codehinting works

This works in Netbeans 7.2 (I'm using it)

Works also with:

$needles = getAllNeedles();
/* @var $needles Needle[] */
foreach ($needles as $needle) {
    $needle->...                        //codehinting works
}

Therefore use of declaration inside the foreach is not necessary.

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

What key shortcuts are to comment and uncomment code?

This is how I did it,

Menu ToolsOptions on the EnvironmentKeyboard window

One can alter the default shortcuts following the below steps

  • Select Edit.CommentSelection in the listbox
  • Click on "Remove" button
  • Select "Text Editor" option in the dropdown under "Use new shortcut in:"
  • Press your own shortcut in the textbox under "Press shortcut keys:" Example: Pressing Ctrl+E and then C will give you Ctrl+E, C
  • Click on "Assign" button
  • Repeat the same for Edit.UnCommentSelection (Ctrl+E, U)

How can I reverse the order of lines in a file?

EDIT the following generates a randomly sorted list of numbers from 1 to 10:

seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') **...**

where dots are replaced with actual command which reverses the list

tac

seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') \
<(tac)

python: using [::-1] on sys.stdin

seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') \
<(python -c "import sys; print(''.join(([line for line in sys.stdin])[::-1]))")

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

Regex to check with starts with http://, https:// or ftp://

test.matches() method checks all text.use test.find()

What's the difference between struct and class in .NET?

Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.

Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.

The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

How do I create a SQL table under a different schema?

                           create a database schema in SQL Server 2008
1. Navigate to Security > Schemas
2. Right click on Schemas and select New Schema
3. Complete the details in the General tab for the new schema. Like, the schema name is "MySchema" and the schema owner is "Admin".
4. Add users to the schema as required and set their permissions:
5. Add any extended properties (via the Extended Properties tab)
6. Click OK.
                           Add a Table to the New Schema "MySchema"
1. In Object Explorer, right click on the table name and select "Design":
2. Changing database schema for a table in SQL Server Management Studio
3. From Design view, press F4 to display the Properties window.
4. From the Properties window, change the schema to the desired schema:
5. Close Design View by right clicking the tab and selecting "Close":
6. Closing Design View
7. Click "OK" when prompted to save
8. Your table has now been transferred to the "MySchema" schema.

Refresh the Object Browser view To confirm the changes
Done

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

Check your Elastic version.

I had these problem because I was looking at the incorrect version's documentation.

enter image description here

Finding blocking/locking queries in MS SQL (mssql)

You may find this query useful:

SELECT * 
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName' 
AND blocking_session_id <> 0

How do you add CSS with Javascript?

This is my solution to add a css rule at the end of the last style sheet list:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

Android set height and width of Custom view programmatically

spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));

spin12 is your spinner and 200,120 is width and height for your spinner.

jQuery-- Populate select from json

Only change the DOM once...

var listitems = '';
$.each(temp, function(key, value){
    listitems += '<option value=' + key + '>' + value + '</option>';
});
$select.append(listitems);

How to implement debounce in Vue2?

Please note that I posted this answer before the accepted answer. It's not correct. It's just a step forward from the solution in the question. I have edited the accepted question to show both the author's implementation and the final implementation I had used.


Based on comments and the linked migration document, I've made a few changes to the code:

In template:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

In script:

watch: {
  searchInput: function () {
    this.debounceInput();
  }
},

And the method that sets the filter key stays the same:

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

This looks like there is one less call (just the v-model, and not the v-on:input).

is it possible to get the MAC address for machine using nmap

With the recent version of nmap 6.40, it will automatically show you the MAC address. example:

nmap 192.168.0.1-255

this command will scan your network from 192.168.0.1 to 255 and will display the hosts with their MAC address on your network.

in case you want to display the mac address for a single client, use this command make sure you are on root or use "sudo"

sudo nmap -Pn 192.168.0.1

this command will display the host MAC address and the open ports.

hope that is helpful.

Build an iOS app without owning a mac?

You can use Smartface for developing your app with javascript and deploy to stores directly without a Mac. What they say is below.

With the Cloud Build module, Smartface removes all the hassle of application deployment. You don’t need to worry about managing code signing certificates and having a Mac to sign your apps. Smartface Cloud can store all your iOS certificates and Android keystores in one place and signing and building is fully in the cloud. No matter which operating system you use, you can get store-ready (or enterprise distribution) binaries. Smartface frees you from the lock-in to Mac and allows you to use your favorite operating system for development.

https://www.smartface.io/smartface/

Git: How configure KDiff3 as merge tool and diff tool

To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool will be

git config --global merge.guitool kdiff3 

That is because "git mergetool" learned to take the "--[no-]gui" option, just like "git difftool" does.

See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 87c15d1, 30 Oct 2018)

mergetool: accept -g/--[no-]gui as arguments

In line with how difftool accepts a -g/--[no-]gui option, make mergetool accept the same option in order to use the merge.guitool variable to find the default mergetool instead of merge.tool.

Chart.js canvas resize

I was having the same problem. I was able to solve it by setting option:

_x000D_
_x000D_
responsive: false,_x000D_
maintainAspectRatio: true,_x000D_
showScale: false,
_x000D_
_x000D_
_x000D_

And in css, set the width of the container div the same as the canvas:

_x000D_
_x000D_
    #canvasContainer { _x000D_
      width: 300px;_x000D_
    }_x000D_
    _x000D_
    canvas {_x000D_
      width: 300px;_x000D_
    }
_x000D_
_x000D_
_x000D_

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

Could not locate Gemfile

I solved similar problem just by backing out of the project directory, then cd back into the project directory and bundle install.

How to loop and render elements in React.js without an array of objects to map?

I'm using Object.keys(chars).map(...) to loop in render

// chars = {a:true, b:false, ..., z:false}

render() {
    return (
       <div>
        {chars && Object.keys(chars).map(function(char, idx) {
            return <span key={idx}>{char}</span>;
        }.bind(this))}
        "Some text value"
       </div>
    );
}

getting file size in javascript

You cannot.

JavaScript cannot access files on the local computer for security reasons, even to check their size.

The only thing you can do is use JavaScript to submit the form with the file field to a server-side script, which can then measure its size and return it.

Converting PHP result array to JSON

json_encode is available in php > 5.2.0:

echojson_encode($row);

What is the difference between Cloud Computing and Grid Computing?

Cloud Computing is For Service Oriented where as Grid Computing is for Application Oriented. Grid computing is used to build Virtual supercomputer using a middler ware to achieve a common task that can be shared among several resources. most probably this task will be kind of computing or data storage.

Cloud computing is providing services over the internet through several servers uses Virtualization.In cloud computing either you can provide service in three types Iaas , Paas, Saas . This will give you solution when you don't have any resources for a short time Business service over the Internet.

How does one capture a Mac's command key via JavaScript?

if you use Vuejs, just make it by vue-shortkey plugin, everything will be simple

https://www.npmjs.com/package/vue-shortkey

v-shortkey="['meta', 'enter']"·
@shortkey="metaEnterTrigged"

How do I get the value of a textbox using jQuery?

Use the .val() method to get the actual value of the element you need.

How can I get the number of records affected by a stored procedure?

For Microsoft SQL Server you can return the @@ROWCOUNT variable to return the number of rows affected by the last statement in the stored procedure.

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

Why is the gets function so dangerous that it should not be used?

In order to use gets safely, you have to know exactly how many characters you will be reading, so that you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.

Instead of using gets, you want to use fgets, which has the signature

char* fgets(char *string, int length, FILE * stream);

(fgets, if it reads an entire line, will leave the '\n' in the string; you'll have to deal with that.)

It remained an official part of the language up to the 1999 ISO C standard, but it was officially removed by the 2011 standard. Most C implementations still support it, but at least gcc issues a warning for any code that uses it.

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

Enable the display of line numbers in Visual Studio

Are you talking about seeing the line numbers or knowing the total number of lines in a project? Here is the 1st one

Non greedy (reluctant) regex matching in sed?

echo "/home/one/two/three/myfile.txt" | sed 's|\(.*\)/.*|\1|'

don bother, i got it on another forum :)

The name does not exist in the namespace error in XAML

Dunno if this will help anyone else

I'm new to WPF and still a novice with VB.net - so I was assuming that getting this error was being caused by me doing summit silly........ suppose I was really! I've managed to get rid of it by moving my project from a shared drive to one of my local drives. Error's disappeared, project compiles perfectly no further issues - yet. Looks like VS2015 still has problems with projects held on a shared drive.

How to replace ${} placeholders in a text file?

Lots of choices here, but figured I'd toss mine on the heap. It is perl based, only targets variables of the form ${...}, takes the file to process as an argument and outputs the converted file on stdout:

use Env;
Env::import();

while(<>) { $_ =~ s/(\${\w+})/$1/eeg; $text .= $_; }

print "$text";

Of course I'm not really a perl person, so there could easily be a fatal flaw (works for me though).

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.

in the case above you could write

CREATE DEFINER = control_panel_username@localhost FUNCTION fnc_calcWalkedDistance

then upload the file. Hope it helps

How to use format() on a moment.js duration?

This works for me:

moment({minutes: 150}).format('HH:mm') // 01:30

How to access /storage/emulated/0/

Try it from

ftp://ip_my_s5:2221/mnt/sdcard/Pictures/Screenshots

which point onto /storage/emulated/0

Hiding the address bar of a browser (popup)

You could make the webpage scroll down to a position where you can't see the address bar, and if the user scrolls, the page should return to your set position. In that way, Mobile browsers when scrolled down , will try to guve you full-screen experience. So it will hide the address bar. I don't know the code, someone else might put up the code.

Android: How do I prevent the soft keyboard from pushing my view up?

This was the best which worked for me

android:windowSoftInputMode="adjustNothing"

Try it!

C++ printing boolean, what is displayed?

0 will get printed.

As in C++ true refers to 1 and false refers to 0.

In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.

#include <iostream>
int main()
{
  std::cout << std::boolalpha << false << std::endl;
}

output:

false

IDEONE

How do I get video durations with YouTube API version 3?

This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.

<?php
    function getDuration($videoID){
       $apikey = "YOUR-Youtube-API-KEY"; // Like this AIcvSyBsLA8znZn-i-aPLWFrsPOlWMkEyVaXAcv
       $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$videoID&key=$apikey");
       $VidDuration =json_decode($dur, true);
       foreach ($VidDuration['items'] as $vidTime)
       {
           $VidDuration= $vidTime['contentDetails']['duration'];
       }
       preg_match_all('/(\d+)/',$VidDuration,$parts);
       return $parts[0][0] . ":" .
              $parts[0][1] . ":".
              $parts[0][2]; // Return 1:11:46 (i.e.) HH:MM:SS
    }

    echo getDuration("zyeubYQxHyY"); // Video ID
?>

You can get your domain's own YouTube API key on https://console.developers.google.com and generate credentials for your own requirement.

What is the difference between HTTP status code 200 (cache) vs status code 304?

For your last question, why ? I'll try to explain with what I know

A brief explanation of those three status codes in layman's terms.

  • 200 - success (browser requests and get file from server)

If caching is enabled in the server

  • 200 (from memory cache) - file found in browser, so browser is not going request from server
  • 304 - browser request a file but it is rejected by server

For some files browser is deciding to request from server and for some it's deciding to read from stored (cached) files. Why is this ? Every files has an expiry date, so

If a file is not expired then the browser will use from cache (200 cache).

If file is expired, browser requests server for a file. Server check file in both places (browser and server). If same file found, server refuses the request. As per protocol browser uses existing file.

look at this nginx configuration

location / {
    add_header Cache-Control must-revalidate;
    expires     60;
    etag on;

    ...
}

Here the expiry is set to 60 seconds, so all static files are cached for 60 seconds. So if u request a file again within 60 seconds browser will read from memory (200 memory). If u request after 60 seconds browser will request server (304).

I assumed that the file is not changed after 60 seconds, in that case you would get 200 (ie, updated file will be fetched from server).

So, if the servers are configured with different expiring and caching headers (policies), the status may differ.

In your case you are using cdn, the main purpose of cdn is high availability and fast delivery. Therefore they use multiple servers. Even though it seems like files are in same directory, cdn might use multiple servers to provide u content, if those servers have different configurations. Then these status can change. Hope it helps.

twitter bootstrap navbar fixed top overlapping site

I would do this:

// add appropriate media query if required to target mobile nav only
.nav { overflow-y: hidden !important }

This should make sure the nav block doesn't stretch downpage and covers the page content.

How do I determine k when using k-means clustering?

I'm surprised nobody has mentioned this excellent article: http://www.ee.columbia.edu/~dpwe/papers/PhamDN05-kmeans.pdf

After following several other suggestions I finally came across this article while reading this blog: https://datasciencelab.wordpress.com/2014/01/21/selection-of-k-in-k-means-clustering-reloaded/

After that I implemented it in Scala, an implementation which for my use cases provide really good results. Here's code:

import breeze.linalg.DenseVector
import Kmeans.{Features, _}
import nak.cluster.{Kmeans => NakKmeans}

import scala.collection.immutable.IndexedSeq
import scala.collection.mutable.ListBuffer

/*
https://datasciencelab.wordpress.com/2014/01/21/selection-of-k-in-k-means-clustering-reloaded/
 */
class Kmeans(features: Features) {
  def fkAlphaDispersionCentroids(k: Int, dispersionOfKMinus1: Double = 0d, alphaOfKMinus1: Double = 1d): (Double, Double, Double, Features) = {
    if (1 == k || 0d == dispersionOfKMinus1) (1d, 1d, 1d, Vector.empty)
    else {
      val featureDimensions = features.headOption.map(_.size).getOrElse(1)
      val (dispersion, centroids: Features) = new NakKmeans[DenseVector[Double]](features).run(k)
      val alpha =
        if (2 == k) 1d - 3d / (4d * featureDimensions)
        else alphaOfKMinus1 + (1d - alphaOfKMinus1) / 6d
      val fk = dispersion / (alpha * dispersionOfKMinus1)
      (fk, alpha, dispersion, centroids)
    }
  }

  def fks(maxK: Int = maxK): List[(Double, Double, Double, Features)] = {
    val fadcs = ListBuffer[(Double, Double, Double, Features)](fkAlphaDispersionCentroids(1))
    var k = 2
    while (k <= maxK) {
      val (fk, alpha, dispersion, features) = fadcs(k - 2)
      fadcs += fkAlphaDispersionCentroids(k, dispersion, alpha)
      k += 1
    }
    fadcs.toList
  }

  def detK: (Double, Features) = {
    val vals = fks().minBy(_._1)
    (vals._3, vals._4)
  }
}

object Kmeans {
  val maxK = 10
  type Features = IndexedSeq[DenseVector[Double]]
}

Inserting an item in a Tuple

You can cast it to a list, insert the item, then cast it back to a tuple.

a = ('Product', '500.00', '1200.00')
a = list(a)
a.insert(3, 'foobar')
a = tuple(a)
print a

>> ('Product', '500.00', '1200.00', 'foobar')

Can't bind to 'routerLink' since it isn't a known property

In my case I just need to import my newly created component to RouterModule

{path: 'newPath', component: newComponent}

Then in your app.module import the router and configure the routes:

import { RouterModule } from '@angular/router';

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent},
            {path: 'newPath', component: newComponent}
        ])
    ],

Hope this helps to some one !!!

Compress images on client side before uploading

You might be able to resize the image with canvas and export it using dataURI. Not sure about compression, though.

Take a look at this: Resizing an image in an HTML5 canvas

Failed to resolve version for org.apache.maven.archetypes

The problem may also come from that you haven't set MAVEN_HOME environment variable. So the Maven embedded in Eclipse can't do its job to download the archetype.Check if that variable is set upfront.

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Updating user data - ASP.NET Identity

If you leave any of the fields for ApplicationUser OR IdentityUser null the update will come back as successful but wont save the data in the database.

Example solution:

ApplicationUser model = UserManager.FindById(User.Identity.GetUserId())

Add the newly updated fields:

model.Email = AppUserViewModel.Email;
model.FName = AppUserViewModel.FName;
model.LName = AppUserViewModel.LName;
model.DOB = AppUserViewModel.DOB;
model.Gender = AppUserViewModel.Gender;

Call UpdateAsync

IdentityResult result = await UserManager.UpdateAsync(model);

I have tested this and it works.

Docker: Multiple Dockerfiles in project

When working on a project that requires the use of multiple dockerfiles, simply create each dockerfile in a separate directory. For instance,

app/ db/

Each of the above directories will contain their dockerfile. When an application is being built, docker will search all directories and build all dockerfiles.

Get environment variable value in Dockerfile

Load environment variables from a file you create at runtime.

export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF

... then in the Dockerfile

ADD build /build
RUN /build/test.sh

where test.sh loads MYVAR from env.sh

#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile

How do I specify different layouts for portrait and landscape orientations?

The last line below is an example for applying two quantifiers: landscape and smallest width(600dp) screen. Update 600dp with the ones you need.

res/layout/main_activity.xml                # For handsets
res/layout-land/main_activity.xml           # For handsets in landscape
res/layout-sw600dp/main_activity.xml        # For 7” tablets
res/layout-sw600dp-land/main_activity.xml   # For 7” tablets in landscape

The above applies to dimens as well

res/values/dimens.xml                # For handsets
res/values-land/dimens.xml           # For handsets in landscape
res/values-sw600dp/dimens.xml        # For 7” tablets
res/values-sw600dp-land/dimens.xml   # For 7” tablets in landscape

A useful device metrics: https://material.io/tools/devices/

How to get a .csv file into R?

As Dirk said, the function you are after is 'read.csv' or one of the other read.table variants. Given your sample data above, I think you will want to do something like this:

setwd("c:/random/directory")

df <- read.csv("myRandomFile.csv", header=TRUE)

All we did in the above was set the directory to where your .csv file is and then read the .csv into a dataframe named df. You can check that the data loaded properly by checking the structure of the object with:

str(df)

Assuming the data loaded properly, you can think go on to perform any number of statistical methods with the data in your data frame. I think summary(df) would be a good place to start. Learning how to use the help in R will be immensely useful, and a quick read through the help on CRAN will save you lots of time in the future: http://cran.r-project.org/

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

For Angular versions 5 and above, the updated importing line looks like :

import { map } from 'rxjs/operators';

OR

import { map } from 'rxjs/operators';

Also these versions totally supports Pipable Operators so you can easily use .pipe() and .subscribe().

If you are using Angular version 2, then the following line should work absolutely fine :

import 'rxjs/add/operator/map';

OR

import 'rxjs/add/operators/map';

If you still encounter a problem then you must go with :

import 'rxjs/Rx';

I won't prefer you to use it directly bcoz it boosts the Load time, as it has a large number of operators in it (useful and un-useful ones) which is not a good practice according to the industry norms, so make sure you try using the above mentioned importing lines first, and if that not works then you should go for rxjs/Rx

How to convert ASCII code (0-255) to its corresponding character?

This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.

public class sample6
{
    public static void main(String... asf)
    {

        for(int i =0; i<256; i++)
        {
            System.out.println( i + ". " + (char)i);
        }
    }
}

Why does Date.parse give incorrect results?

The accepted answer from CMS is correct, I have just added some features :

  • trim and clean input spaces
  • parse slashes, dashes, colons and spaces
  • has default day and time

// parse a date time that can contains spaces, dashes, slashes, colons
function parseDate(input) {
    // trimes and remove multiple spaces and split by expected characters
    var parts = input.trim().replace(/ +(?= )/g,'').split(/[\s-\/:]/)
    // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
    return new Date(parts[0], parts[1]-1, parts[2] || 1, parts[3] || 0, parts[4] || 0, parts[5] || 0); // Note: months are 0-based
}

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

Move textfield when keyboard appears swift

You can use this library and just one line of code in appDidFinishedLaunching and u are done..

func application(application: UIApplication,didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    IQKeyboardManager.sharedManager().enable = true
    return true
}

IQKeyboardManager - adjust view whenever keyboard appear link - https://github.com/hackiftekhar/IQKeyboardManager

How to merge 2 List<T> and removing duplicate values from it in C#

Union has not good performance : this article describe about compare them with together

var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
        dict[person.Number] = person;
}
var merged = dict.Values.ToList();

Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms

Is it possible to hide the cursor in a webpage using CSS or Javascript?

With CSS:

selector { cursor: none; }

An example:

_x000D_
_x000D_
<div class="nocursor">_x000D_
   Some stuff_x000D_
</div>_x000D_
<style type="text/css">_x000D_
    .nocursor { cursor:none; }_x000D_
</style>
_x000D_
_x000D_
_x000D_

To set this on an element in Javascript, you can use the style property:

<div id="nocursor"><!-- some stuff --></div>
<script type="text/javascript">
    document.getElementById('nocursor').style.cursor = 'none';
</script>

If you want to set this on the whole body:

<script type="text/javascript">
    document.body.style.cursor = 'none';
</script>

Make sure you really want to hide the cursor, though. It can really annoy people.

Different ways of adding to Dictionary

Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.

I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.

The dict[key] = value represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.

get basic SQL Server table structure information

Name and datatype:

USE OurDatabaseName
GO

SELECT 
    sc.name AS [Columne Name], 
    st1.name AS [User Type],
    st2.name AS [Base Type]
FROM dbo.syscolumns sc
    INNER JOIN dbo.systypes st1 ON st1.xusertype = sc.xusertype
    INNER JOIN dbo.systypes st2 ON st2.xusertype = sc.xtype
-- STEP TWO: Change OurTableName to the table name
WHERE sc.id = OBJECT_ID('OurTableName')
ORDER BY sc.colid

Or:

SELECT COLUMN_NAME AS ColumnName, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS CharacterLength
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'OurTableName'

Get contentEditable caret index position

//global savedrange variable to store text range in
var savedrange = null;

function getSelection()
{
    var savedRange;
    if(window.getSelection && window.getSelection().rangeCount > 0) //FF,Chrome,Opera,Safari,IE9+
    {
        savedRange = window.getSelection().getRangeAt(0).cloneRange();
    }
    else if(document.selection)//IE 8 and lower
    { 
        savedRange = document.selection.createRange();
    }
    return savedRange;
}

$('#contentbox').keyup(function() { 
    var currentRange = getSelection();
    if(window.getSelection)
    {
        //do stuff with standards based object
    }
    else if(document.selection)
    { 
        //do stuff with microsoft object (ie8 and lower)
    }
});

Note: the range object its self can be stored in a variable, and can be re-selected at any time unless the contents of the contenteditable div change.

Reference for IE 8 and lower: http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx

Reference for standards (all other) browsers: https://developer.mozilla.org/en/DOM/range (its the mozilla docs, but code works in chrome, safari, opera and ie9 too)

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

How to install a specific version of a ruby gem?

You can use the -v or --version flag. For example

gem install bitclock -v '< 0.0.2'

To specify upper AND lower version boundaries you can specify the --version flag twice

gem install bitclock -v '>= 0.0.1' -v '< 0.0.2'

or use the syntax (for example)

gem install bitclock -v '>= 0.0.1, < 0.0.2'

The other way to do it is

gem install bitclock:'>= 0.0.1'

but with the last option it is not possible to specify upper and lower bounderies simultaneously.

[gem 3.0.3 and ruby 2.6.6]

Versioning SQL Server database

You could also look at a migrations solution. These allow you to specify your database schema in C# code, and roll your database version up and down using MSBuild.

I'm currently using DbUp, and it's been working well.

Excel SUMIF between dates

this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...

=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))

How to enable PHP short tags?

sed -i "s/short_open_tag = .*/short_open_tag = On/" /etc/php/7.2/apache2/php.ini

That works on php7.2 on ubuntu 16, same answer as above by Bradley Flood, although the directory in which the config file is stored has changed.

Also you can change the version in the php string to match your currently installed version.

Undefined reference to sqrt (or other mathematical functions)

I had the same issue, but I simply solved it by adding -lm after the command that runs my code. Example. gcc code.c -lm

Retrieving JSON Object Literal from HttpServletRequest

are you looking for this ?

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = request.getReader();
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } finally {
        reader.close();
    }
    System.out.println(sb.toString());
}

Which Python memory profiler is recommended?

My module memory_profiler is capable of printing a line-by-line report of memory usage and works on Unix and Windows (needs psutil on this last one). Output is not very detailed but the goal is to give you an overview of where the code is consuming more memory, not an exhaustive analysis on allocated objects.

After decorating your function with @profile and running your code with the -m memory_profiler flag it will print a line-by-line report like this:

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

Programmatically get the version number of a DLL

You can use System.Reflection.Assembly.Load*() methods and then grab their AssemblyInfo.

How can you find the height of text on an HTML canvas?

I found that JUST FOR ARIAL the simplest, fastest and accuratest way to find height of bounding box is to use the width of certain letters. If you plan to use a certain font without letting user to choose one different, you can do a little research to find the right letter that do the job for that font.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<canvas id="myCanvas" width="700" height="200" style="border:1px solid #d3d3d3;">_x000D_
Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
_x000D_
<script>_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
ctx.font = "100px Arial";_x000D_
var txt = "Hello guys!"_x000D_
var Hsup=ctx.measureText("H").width;_x000D_
var Hbox=ctx.measureText("W").width;_x000D_
var W=ctx.measureText(txt).width;_x000D_
var W2=ctx.measureText(txt.substr(0, 9)).width;_x000D_
_x000D_
ctx.fillText(txt, 10, 100);_x000D_
ctx.rect(10,100, W, -Hsup);_x000D_
ctx.rect(10,100+Hbox-Hsup, W2, -Hbox);_x000D_
ctx.stroke();_x000D_
</script>_x000D_
_x000D_
<p><strong>Note:</strong> The canvas tag is not supported in Internet _x000D_
Explorer 8 and earlier versions.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Calling functions in a DLL from C++

You can either go the LoadLibrary/GetProcAddress route (as Harper mentioned in his answer, here's link to the run-time dynamic linking MSDN sample again) or you can link your console application to the .lib produced from the DLL project and include the hea.h file with the declaration of your function (as described in the load-time dynamic linking MSDN sample)

In both cases, you need to make sure your DLL exports the function you want to call properly. The easiest way to do it is by using __declspec(dllexport) on the function declaration (as shown in the creating a simple dynamic-link library MSDN sample), though you can do it also through the corresponding .def file in your DLL project.

For more information on the topic of DLLs, you should browse through the MSDN About Dynamic-Link Libraries topic.

When is a timestamp (auto) updated?

Give the command SHOW CREATE TABLE whatever

Then look at the table definition.

It probably has a line like this

logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

in it. DEFAULT CURRENT_TIMESTAMP means that any INSERT without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP means that any update without an explicit timestamp results in an update to the current timestamp value.

You can control this default behavior when creating your table.

Or, if the timestamp column wasn't created correctly in the first place, you can change it.

ALTER TABLE whatevertable
     CHANGE whatevercolumn 
            whatevercolumn TIMESTAMP NOT NULL
                           DEFAULT CURRENT_TIMESTAMP 
                           ON UPDATE CURRENT_TIMESTAMP;

This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable without changing the timestamp, that is,

To prevent the column from updating when other columns change

then you need to issue this kind of update.

UPDATE whatevertable
   SET something = 'newvalue',
       whatevercolumn = whatevercolumn
 WHERE someindex = 'indexvalue'

This works with TIMESTAMP and DATETIME columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMPs) When you use TIMESTAMPs, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.

How to view data saved in android database(SQLite)?

I recommend the firefox plugin(SQLLite Manager) if you always use firefox.

Here is the link

Getting DOM element value using pure JavaScript

In the second version, you're passing the String returned from this.id. Not the element itself.

So id.value won't give you what you want.

You would need to pass the element with this.

doSomething(this)

then:

function(el){
    var value = el.value;
    ...
}

Note: In some browsers, the second one would work if you did:

window[id].value 

because element IDs are a global property, but this is not safe.

It makes the most sense to just pass the element with this instead of fetching it again with its ID.

How does one reorder columns in a data frame?

You can also use the subset function:

data <- subset(data, select=c(3,2,1))

You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.

Update:

You can also use the select function from the dplyr package:

data = data %>% select(Time, out, In, Files)

I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:

mtcars %>% select(carb:mpg)

And the following will reorder only some columns, and discard others:

mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))

Read more about dplyr's select syntax.

Disable Proximity Sensor during call

After trying a whole bunch of fixes including:

  • Phone app's menu option (my phone did not have a option to disable)
  • Proximity Screen Off Lite (did not work)
  • Xposed Framework with sensor disabler (works till phone is rebooted or app updates)
  • Macrodroid macro (Macrodroid does not run on my phone for some reason)
  • put some tin foil in front of it?(i don't know what i was thinking)

Here is My fix: I figured you cannot break it more so I opened up my phone and removed the proximity sensor all together from the motherboard. The sensor tester app now shows "no_value" where it use to give "Distance: 0" and my screen no longer goes black after dialing. Please note I can only confirm this working on a Samsung I8190 Galaxy S III mini with CM MOD 5.1.1. Here is a picture of the device i removed: prox sensor I have removed it using a SMD solder station's heat gun at 400 degrees, some tweezers and flux.But a sharp hobby knife might work too.

How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

Convert DataTable to IEnumerable<T>

Simple method using System.Data.DataSetExtensions:

table.AsEnumerable().Select(row => new TankReading{
        TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
        TankID = Convert.ToInt32(row["TankID"]),
        ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
        ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
        ReadingInches = Convert.ToInt32(row["ReadingInches"]),
        MaterialNumber = row["MaterialNumber"].ToString(),
        EnteredBy = row["EnteredBy"].ToString(),
        ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
        MaterialID = Convert.ToInt32(row["MaterialID"]),
        Submitted = Convert.ToBoolean(row["Submitted"]),
    });

Or:

TankReading TankReadingFromDataRow(DataRow row){
    return new TankReading{
        TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
        TankID = Convert.ToInt32(row["TankID"]),
        ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
        ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
        ReadingInches = Convert.ToInt32(row["ReadingInches"]),
        MaterialNumber = row["MaterialNumber"].ToString(),
        EnteredBy = row["EnteredBy"].ToString(),
        ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
        MaterialID = Convert.ToInt32(row["MaterialID"]),
        Submitted = Convert.ToBoolean(row["Submitted"]),
    };
}

// Now you can do this
table.AsEnumerable().Select(row => return TankReadingFromDataRow(row));

Or, better yet, create a TankReading(DataRow r) constructor, then this becomes:

    table.AsEnumerable().Select(row => return new TankReading(row));

How to get current time in milliseconds in PHP?

Short answer:

64 bits platforms only!

function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

[ If you are running 64 bits PHP then the constant PHP_INT_SIZE equals to 8 ]


Long answer:

If you want an equilvalent function of time() in milliseconds first you have to consider that as time() returns the number of seconds elapsed since the "epoch time" (01/01/1970), the number of milliseconds since the "epoch time" is a big number and doesn't fit into a 32 bits integer.

The size of an integer in PHP can be 32 or 64 bits depending on platform.

From http://php.net/manual/en/language.types.integer.php

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

If you have 64 bits integers then you may use the following function:

function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

microtime() returns the number of seconds since the "epoch time" with precision up to microseconds with two numbers separated by space, like...

0.90441300 1409263371

The second number is the seconds (integer) while the first one is the decimal part.

The above function milliseconds() takes the integer part multiplied by 1000

1409263371000

then adds the decimal part multiplied by 1000 and rounded to 0 decimals

1409263371904

Note that both $mt[1] and the result of round are casted to int. This is necessary because they are floats and the operation on them without casting would result in the function returning a float.

Finally, that function is slightly more precise than

round(microtime(true)*1000);

that with a ratio of 1:10 (approx.) returns 1 more millisecond than the correct result. This is due to the limited precision of the float type (microtime(true) returns a float). Anyway if you still prefer the shorter round(microtime(true)*1000); I would suggest casting to int the result.


Even if it's beyond the scope of the question it's worth mentioning that if your platform supports 64 bits integers then you can also get the current time in microseconds without incurring in overflow.

If fact 2^63 - 1 (biggest signed integer) divided by 10^6 * 3600 * 24 * 365 (approximately the microseconds in one year) gives 292471.

That's the same value you get with

echo (int)( PHP_INT_MAX / ( 1000000 * 3600 * 24 * 365 ) );

In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.

You may have then

function microseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000000 + ((int)round($mt[0] * 1000000));
}

Why are elementwise additions much faster in separate loops than in a combined loop?

OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.

There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.

@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.

That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.

The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.

Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:

  1. It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)

  2. It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)

The result using initialized data:

Enter image description here

The result using uninitialized data (this is what Mysticial tested):

Enter image description here

And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:

Enter image description here

Proposal

Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

mcrypt is deprecated, what is the alternative?

Pure-PHP implementation of Rijndael exists with phpseclib available as composer package and works on PHP 7.3 (tested by me).

There's a page on the phpseclib docs, which generates sample code after you input the basic variables (cipher, mode, key size, bit size). It outputs the following for Rijndael, ECB, 256, 256:

a code with mycrypt

$decoded = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, ENCRYPT_KEY, $term, MCRYPT_MODE_ECB);

works like this with the library

$rijndael = new \phpseclib\Crypt\Rijndael(\phpseclib\Crypt\Rijndael::MODE_ECB);
$rijndael->setKey(ENCRYPT_KEY);
$rijndael->setKeyLength(256);
$rijndael->disablePadding();
$rijndael->setBlockLength(256);

$decoded = $rijndael->decrypt($term);

* $term was base64_decoded

Installing Node.js (and npm) on Windows 10

You should run the installer as administrator.

  1. Run the command prompt as administrator
  2. cd directory where msi file is present
  3. launch msi file by typing the name in the command prompt
  4. You should be happy to see all node commands work from new command prompt shell

How to send string from one activity to another?

Say there is EditText et1 in ur MainActivity and u wanna pass this to SecondActivity

String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);

now in Second Activity, say u wanna put the string passed from EditText et1 to TextView txt1 of SecondActivity

Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);

How to get column values in one comma separated value

You can do this with the following SQL:

SELECT STUFF
(
    (
        SELECT ',' + s.FirstName 
        FROM Employee s
        ORDER BY s.FirstName FOR XML PATH('')
    ),
     1, 1, ''
) AS Employees

TestNG ERROR Cannot find class in classpath

I just had this problem and was because the skip test option in the run configuration was checked. made that unchecked and build, then run the testNg, worked.

Regular expression for first and last name

So, with customer we create this crazy regex:

(^$)|(^([^\-!#\$%&\(\)\*,\./:;\?@\[\\\]_\{\|\}¨?“”€\+<=>§°\d\s¤®™©]| )+$)

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Deserializing using JsonConvert.DeserializeObject() function

public class ApiValues
    {
        [JsonProperty("Address")]
        public string Address { get; set; }

        [JsonProperty("BaseUrl")]
        public string BaseUrl{ get; set; }
    }

var json = 
{ 
    "Address":"some-address",
    "BaseUrl":"some-url-value"
}


var values = JsonConvert.DeserializeObject<ApiValues>(json);

Checking if date is weekend PHP

Here:

function isweekend($year, $month, $day)
{
    $time = mktime(0, 0, 0, $month, $day, $year);
    $weekday = date('w', $time);
    return ($weekday == 0 || $weekday == 6);
}

Convert tabs to spaces in Notepad++

The following way is the best way in my opinion:

Download:

  1. Notepad++
  2. The plugin http://sourceforge.net/projects/tabstospacesnpp/?source=typ
  3. Read the instructions and it will convert tabs to spaces.

List all devices, partitions and volumes in Powershell

You can also do it on the CLI with

net use

CSS background image alt attribute

The classical way to achieve this is to put the text into the div and use an image replacement technique.

<div class"ir background-image">Your alt text</div>

with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

Insert the same fixed value into multiple rows

To create a new empty column and fill it with the same value (here 100) for every row (in Toad for Oracle):

ALTER TABLE my_table ADD new_column INT;
UPDATE my_table SET new_column = 100;

Changing Vim indentation behavior by file type

Put autocmd commands based on the file suffix in your ~/.vimrc

autocmd BufRead,BufNewFile   *.c,*.h,*.java set noic cin noexpandtab
autocmd BufRead,BufNewFile   *.pl syntax on

The commands you're looking for are probably ts= and sw=

Remove redundant paths from $PATH variable

In bash you simply can ${var/find/replace}

PATH=${PATH/%:\/home\/wrong\/dir\//}

Or in this case (as the replace bit is empty) just:

PATH=${PATH%:\/home\/wrong\/dir\/}

I came here first but went else ware as I thought there would be a parameter expansion to do this. Easier than sed!.

How to replace placeholder character or word in variable with value from another variable in Bash?

How do I use properly CASE..WHEN in MySQL

Remove the course_enrollment_settings.base_price immediately after CASE:

SELECT
   CASE
    WHEN course_enrollment_settings.base_price = 0      THEN 1
    ...
    END

CASE has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

after upgrading my xampp from 7.2.0 to 7.3.0 i face this issue but after unistall composer.exe and install latest composer.exe from composer.org than issue resolved

Process.start: how to get the output?

How to launch a process (such as a bat file, perl script, console program) and have its standard output displayed on a windows form:

processCaller = new ProcessCaller(this);
//processCaller.FileName = @"..\..\hello.bat";
processCaller.FileName = @"commandline.exe";
processCaller.Arguments = "";
processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.Completed += new EventHandler(processCompletedOrCanceled);
processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
// processCaller.Failed += no event handler for this one, yet.

this.richTextBox1.Text = "Started function.  Please stand by.." + Environment.NewLine;

// the following function starts a process and returns immediately,
// thus allowing the form to stay responsive.
processCaller.Start();    

You can find ProcessCaller on this link: Launching a process and displaying its standard output

How to load images dynamically (or lazily) when users scrolls them into view

Some of the answers here are for infinite page. What Salman is asking is lazy loading of images.

Plugin

Demo

EDIT: How do these plugins work?

This is a simplified explanation:

  1. Find window size and find the position of all images and their sizes
  2. If the image is not within the window size, replace it with a placeholder of same size
  3. When user scrolls down, and position of image < scroll + window height, the image is loaded

Why is jquery's .ajax() method not sending my session cookie?

After trying out the other solutions and still not getting it to work, I found out what the problem was in my case. I changed contentType from "application/json" to "text/plain".

$.ajax(fullUrl, {
    type: "GET",
    contentType: "text/plain",
    xhrFields: {
         withCredentials: true
    },
    crossDomain: true
});

How to filter WooCommerce products by custom attribute

You can use WooCommerce AJAX Product Filter. You can also watch how the plugin is used for product filtering.

Here is a screenshot:

enter image description here

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

The latest version of the pipeline sh step allows you to do the following;

// Git committer email
GIT_COMMIT_EMAIL = sh (
    script: 'git --no-pager show -s --format=\'%ae\'',
    returnStdout: true
).trim()
echo "Git committer email: ${GIT_COMMIT_EMAIL}"

Another feature is the returnStatus option.

// Test commit message for flags
BUILD_FULL = sh (
    script: "git log -1 --pretty=%B | grep '\\[jenkins-full]'",
    returnStatus: true
) == 0
echo "Build full flag: ${BUILD_FULL}"

These options where added based on this issue.

See official documentation for the sh command.

For declarative pipelines (see comments), you need to wrap code into script step:

script {
   GIT_COMMIT_EMAIL = sh (
        script: 'git --no-pager show -s --format=\'%ae\'',
        returnStdout: true
    ).trim()
    echo "Git committer email: ${GIT_COMMIT_EMAIL}"
}

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

How do I use WPF bindings with RelativeSource?

I just posted another solution for accessing the DataContext of a parent element in Silverlight that works for me. It uses Binding ElementName.