Programs & Examples On #Notificationservices

How can I reload .emacs after changing it?

Others already answered your question as stated, but I find that I usually want to execute the lines that I just wrote. for that, CtrlAltx in the lisp works just fine.

Xcode Debugger: view value of variable

Try Run->Show->Expressions

Enter in the name of the array or whatever you're looking for.

String contains another two strings

That is because the if statements returns false since d doesn't contain b + a i.e "someonedamage"

Getting Keyboard Input

You can also make it with BufferedReader if you want to validate user input, like this:

import java.io.BufferedReader;
import java.io.InputStreamReader; 
class Areas {
    public static void main(String args[]){
        float PI = 3.1416f;
        int r=0;
        String rad; //We're going to read all user's text into a String and we try to convert it later
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
        System.out.println("Radius?");
        try{
            rad = br.readLine(); //We read from user's input
            r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
            System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
        }
        catch(Exception e){
            System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
            Areas a = new Areas(); //We call this class again, so user can try it again
           //You can also print exception in case you want to see it as follows:
           // e.printStackTrace();
        }
    }
}

Because Scanner class won't allow you to do it, or not that easy...

And to validate you use "try-catch" calls.

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

Google Maps API Multiple Markers with Infowindows

If you also want to bind closing of infowindow to some event, try something like this

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        infowindow.setContent(content);
        infowindow.open(map,marker);
        windows.push(infowindow)
        google.maps.event.addListener(map,'click', function(){ 
            infowindow.close();
        }); 
    };
})(marker,content,infowindow)); 

Shuffling a list of objects

'print func(foo)' will print the return value of 'func' when called with 'foo'. 'shuffle' however has None as its return type, as the list will be modified in place, hence it prints nothing. Workaround:

# shuffle the list in place 
random.shuffle(b)

# print it
print(b)

If you're more into functional programming style you might want to make the following wrapper function:

def myshuffle(ls):
    random.shuffle(ls)
    return ls

TypeError: no implicit conversion of Symbol into Integer

Ive come across this many times in my work, an easy work around that I found is to ask if the array element is a Hash by class.

if i.class == Hash

    notation like i[:label] will work in this block and not throw that error

end

How do I upgrade to Python 3.6 with conda?

I'm using a Mac OS Mojave

These 4 steps worked for me.

  1. conda update conda
  2. conda install python=3.6
  3. conda install anaconda-client
  4. conda update anaconda

iOS: Convert UTC NSDate to local Timezone

Swift 3+: UTC to Local and Local to UTC

extension Date {

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }
}

Appending to an existing string

Here's another way:

fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"

Insert node at a certain position in a linked list C++

For inserting at a particular position k, you need to traverse the list till the position k-1 and then do the insert.

[You need not create a new node to traverse to that position as you did in your code] You should traverse from the head node.

Execute specified function every X seconds

You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

How to write a cron that will run a script every day at midnight?

Sometimes you'll need to specify PATH and GEM_PATH using crontab with rvm.

Like this:

# top of crontab file
PATH=/home/user_name/.rvm/gems/ruby-2.2.0/bin:/home/user_name/.rvm/gems/ruby-2.2.0@global/bin:/home/user_name/.rvm/rubies/ruby-2.2.$
GEM_PATH=/home/user_name/.rvm/gems/ruby-2.2.0:/home/user_name/.rvm/gems/ruby-2.2.0@global

# jobs
00 00 * * * ruby path/to/your/script.rb
00 */4 * * * ruby path/to/your/script2.rb
00 8,12,22 * * * ruby path/to/your/script3.rb

HTML table: keep the same width for columns

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

How to auto adjust the div size for all mobile / tablet display formats?

Whilst I was looking for my answer for the same question, I found this:

<img src="img.png" style=max-
width:100%;overflow:hidden;border:none;padding:0;margin:0 auto;display:block;" marginheight="0" marginwidth="0">

You can use it inside a tag (iframe or img) the image will adjust based on it's device.

How to set enum to null

An enum is a "value" type in C# (means the the enum is stored as whatever value it is, not as a reference to a place in memory where the value itself is stored). You can't set value types to null (since null is used for reference types only).

That being said you can use the built in Nullable<T> class which wraps value types such that you can set them to null, check if it HasValue and get its actual Value. (Those are both methods on the Nullable<T> objects.

name = "";
Nullable<Color> color = null; //This will work.

There is also a shortcut you can use:

Color? color = null;

That is the same as Nullable<Color>;

How to merge a specific commit in Git

'git cherry-pick' should be your answer here.

Apply the change introduced by an existing commit.

Do not forget to read bdonlan's answer about the consequence of cherry-picking in this post:
"Pull all commits from a branch, push specified commits to another", where:

A-----B------C
 \
  \
   D

becomes:

A-----B------C
 \
  \
   D-----C'

The problem with this commit is that git considers commits to include all history before them

Where C' has a different SHA-1 ID.
Likewise, cherry picking a commit from one branch to another basically involves generating a patch, then applying it, thus losing history that way as well.

This changing of commit IDs breaks git's merging functionality among other things (though if used sparingly there are heuristics that will paper over this).
More importantly though, it ignores functional dependencies - if C actually used a function defined in B, you'll never know.

How do I catch a PHP fatal (`E_ERROR`) error?

PHP has catchable fatal errors. They are defined as E_RECOVERABLE_ERROR. The PHP manual describes an E_RECOVERABLE_ERROR as:

Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.

You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.

This question and answer provides a useful example: How can I catch a "catchable fatal error" on PHP type hinting?

E_ERROR errors, however, can be handled, but not recovered from as the engine is in an unstable state.

CSS text-transform capitalize on all caps

If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.

How can I run a directive after the dom has finished rendering?

Here is how I do it:

app.directive('example', function() {

    return function(scope, element, attrs) {
        angular.element(document).ready(function() {
                //MANIPULATE THE DOM
        });
    };

});

var functionName = function() {} vs function functionName() {}

First I want to correct Greg: function abc(){} is scoped too — the name abc is defined in the scope where this definition is encountered. Example:

function xyz(){
  function abc(){};
  // abc is defined here...
}
// ...but not here

Secondly, it is possible to combine both styles:

var xyz = function abc(){};

xyz is going to be defined as usual, abc is undefined in all browsers but Internet Explorer — do not rely on it being defined. But it will be defined inside its body:

var xyz = function abc(){
  // xyz is visible here
  // abc is visible here
}
// xyz is visible here
// abc is undefined here

If you want to alias functions on all browsers, use this kind of declaration:

function abc(){};
var xyz = abc;

In this case, both xyz and abc are aliases of the same object:

console.log(xyz === abc); // prints "true"

One compelling reason to use the combined style is the "name" attribute of function objects (not supported by Internet Explorer). Basically when you define a function like

function abc(){};
console.log(abc.name); // prints "abc"

its name is automatically assigned. But when you define it like

var abc = function(){};
console.log(abc.name); // prints ""

its name is empty — we created an anonymous function and assigned it to some variable.

Another good reason to use the combined style is to use a short internal name to refer to itself, while providing a long non-conflicting name for external users:

// Assume really.long.external.scoped is {}
really.long.external.scoped.name = function shortcut(n){
  // Let it call itself recursively:
  shortcut(n - 1);
  // ...
  // Let it pass itself as a callback:
  someFunction(shortcut);
  // ...
}

In the example above we can do the same with an external name, but it'll be too unwieldy (and slower).

(Another way to refer to itself is to use arguments.callee, which is still relatively long, and not supported in the strict mode.)

Deep down, JavaScript treats both statements differently. This is a function declaration:

function abc(){}

abc here is defined everywhere in the current scope:

// We can call it here
abc(); // Works

// Yet, it is defined down there.
function abc(){}

// We can call it again
abc(); // Works

Also, it hoisted through a return statement:

// We can call it here
abc(); // Works
return;
function abc(){}

This is a function expression:

var xyz = function(){};

xyz here is defined from the point of assignment:

// We can't call it here
xyz(); // UNDEFINED!!!

// Now it is defined
xyz = function(){}

// We can call it here
xyz(); // works

Function declaration vs. function expression is the real reason why there is a difference demonstrated by Greg.

Fun fact:

var xyz = function abc(){};
console.log(xyz.name); // Prints "abc"

Personally, I prefer the "function expression" declaration because this way I can control the visibility. When I define the function like

var abc = function(){};

I know that I defined the function locally. When I define the function like

abc = function(){};

I know that I defined it globally providing that I didn't define abc anywhere in the chain of scopes. This style of definition is resilient even when used inside eval(). While the definition

function abc(){};

depends on the context and may leave you guessing where it is actually defined, especially in the case of eval() — the answer is: It depends on the browser.

Is it possible to pull just one file in Git?

git checkout master -- myplugin.js

master = branch name

myplugin.js = file name

ImportError: No module named site on Windows

Install yaml from the PyYAML home pagee: http://www.pyyaml.org/wiki/PyYAML

Select the appropriate version for your OS and Python.

How to connect to a MS Access file (mdb) using C#?

Try this..

using System.Data.OleDb;

OleDbConnection dbConn;

dConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Registration.accdb;");

Multiline input form field using Bootstrap

The answer by Nick Mitchinson is for Bootstrap version 2.

If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:

<div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-6">
            <textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
        </div>
    </div>
</div>

Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.

Using AngularJS date filter with UTC date

An evolved version of ossek solution

Custom filter is more appropriate, then you can use it anywhere in the project

js file

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

myApp.filter('utcdate', ['$filter','$locale', function($filter, $locale){

    return function (input, format) {
        if (!angular.isDefined(format)) {
            format = $locale['DATETIME_FORMATS']['medium'];
        }

        var date = new Date(input);
        var d = new Date()
        var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
        return $filter('date')(_utc, format)
    };

 }]);

in template

<p>This will convert UTC time to local time<p>
<span>{{dateTimeInUTC | utcdate :'MMM d, y h:mm:ss a'}}</span>

Xcode project not showing list of simulators

Install iOS Simulator if you're missing one.

Click here to see how.

How to Convert Boolean to String

This works also for any kind of value:

$a = true;

echo $a                     // outputs:   1
echo value_To_String( $a )  // outputs:   true

code:

function valueToString( $value ){ 
    return ( !is_bool( $value ) ?  $value : ($value ? 'true' : 'false' )  ); 
}

How do I correctly use "Not Equal" in MS Access?

I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.

I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.

Thanks to all above though.

How to see the values of a table variable at debug time in T-SQL?

Why not just select the Table and view the variable that way?

SELECT * FROM @d

How to check if input file is empty in jQuery

I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:

if (!$('#videoUploadFile').val()) {
  alert('Please Upload File');
}

Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:

$(document).on("click", ":submit", function (e) {

  if (!$('#videoUploadFile').val()) {
  e.preventDefault();
  alert('Please Upload File');
  }

}

Creating SVG graphics using Javascript?

Currently all major browsers support svg. Create svg in JS is very simple (currently innerHTML=... is quite fast)

element.innerHTML = `
    <svg viewBox="0 0 400 100" >
      <circle id="circ" cx="50" cy="50" r="50" fill="red" />
    </svg>
`;

_x000D_
_x000D_
function createSVG() {
  box.innerHTML = `
    <svg viewBox="0 0 400 100" >
      <circle id="circ" cx="50" cy="50" r="50" fill="red" />
    </svg>
  `;
}

function decRadius() {
  r=circ.getAttribute('r');
  circ.setAttribute('r',r*0.5);
}
_x000D_
<button onclick="createSVG()">Create SVG</button>
<button onclick="decRadius()">Decrease radius</button>
<div id="box"></div>
_x000D_
_x000D_
_x000D_

How can I get dict from sqlite query?

Dictionaries in python provide arbitrary access to their elements. So any dictionary with "names" although it might be informative on one hand (a.k.a. what are the field names) "un-orders" the fields, which might be unwanted.

Best approach is to get the names in a separate list and then combine them with the results by yourself, if needed.

try:
         mycursor = self.memconn.cursor()
         mycursor.execute('''SELECT * FROM maintbl;''')
         #first get the names, because they will be lost after retrieval of rows
         names = list(map(lambda x: x[0], mycursor.description))
         manyrows = mycursor.fetchall()

         return manyrows, names

Also remember that the names, in all approaches, are the names you provided in the query, not the names in database. Exception is the SELECT * FROM

If your only concern is to get the results using a dictionary, then definitely use the conn.row_factory = sqlite3.Row (already stated in another answer).

Exit from app when click button in android phonegap?

navigator.app.exitApp();

add this line where you want you exit the application.

What is the purpose of flush() in Java streams?

In addition to other good answers here, this explanation made things crystal clear for me:

A buffer is a portion in memory that is used to store a stream of data (characters). These characters sometimes will only get sent to an output device (e.g. monitor) when the buffer is full or meets a certain number of characters. This can cause your system to lag if you just have a few characters to send to an output device. The flush() method will immediately flush the contents of the buffer to the output stream.

Source: https://www.youtube.com/watch?v=MjK3dZTc0Lg

websocket closing connection automatically

Just found the solution to this for myself. What you want to set is the maxIdleTime of WebSocketServlet, in millis. How to do that depends on how you config your servlet. With Guice ServletModule you can do something like this for timeout of 10 hours:

serve("ws").with(MyWSServlet.class, 
new HashMap<String, Sring>(){{ put("maxIdleTime", TimeUnit.HOURS.toMillis(10) + ""); }});

Anything <0 is infinite idle time I believe.

SQL Last 6 Months

select *
from tbl1
where
datetime_column >= 
DATEADD(m, -6, convert(date, convert(varchar(6), getdate(),112) + '01'))

bash: mkvirtualenv: command not found

Solution 1:

For some reason, virtualenvwrapper.sh installed in /usr/bin/virtualenvwrapper.sh, instead of under /usr/local/bin.

The following in my .bash_profile works...

source "/usr/bin/virtualenvwrapper.sh"
export WORKON_HOME="/opt/virtual_env/"

My install seems to work fine without sourcing virtualenvwrapper_bashrc

Solution 2:

Alternatively as mentioned below, you could leverage the chance that virtualenvwrapper.sh is already in your shell's PATH and just issue a source `which virtualenvwrapper.sh`

How can I keep Bootstrap popovers alive while being hovered?

Same thing for tooltips:

For me following solution works because it does not add event listeners on every 'mouseenter' and it is possible to hover back on the tooltip element which keeps the tooltip alive.

$ ->

  $('.element').tooltip({
    html: true,
    trigger: 'manual'
  }).
  on 'mouseenter', ->
    clearTimeout window.tooltipTimeout
    $(this).tooltip('show') unless $('.tooltip:visible').length > 0
  .
  on 'mouseleave', ->
    _this = this
    window.tooltipTimeout = setTimeout ->
      $(_this).tooltip('hide')
    , 100

$(document).on 'mouseenter', '.tooltip', ->
  clearTimeout window.tooltipTimeout

$(document).on 'mouseleave', '.tooltip', ->
  trigger = $($(this).siblings('.element')[0])
  window.tooltipTimeout = setTimeout ->
    trigger.tooltip('hide')
  , 100

Getting time span between two times in C#?

string startTime = "7:00 AM";
string endTime = "2:00 PM";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Will output: 07:00:00.

It also works if the user input military time:

string startTime = "7:00";
string endTime = "14:00";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Outputs: 07:00:00.

To change the format: duration.ToString(@"hh\:mm")

More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

Addendum:

Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".

how to modify an existing check constraint?

NO, you can't do it other way than so.

When to use extern in C++

This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.

Is there a link to the "latest" jQuery library on Google APIs?

No. There isn't..

But, for development there is such a link on the jQuery code site.

How do I use two submit buttons, and differentiate between which one was used to submit the form?

You can use it as follows,

<td>

<input type="submit" name="save" class="noborder" id="save" value="Save" alt="Save" 
tabindex="4" />

</td>

<td>

<input type="submit" name="publish" class="noborder" id="publish" value="Publish" 
alt="Publish" tabindex="5" />

</td>

And in PHP,

<?php
if($_POST['save'])
{
   //Save Code
}
else if($_POST['publish'])
{
   //Publish Code
}
?>

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

How to search for string in an array

You could use the following without the wrapper function, but it provides a nicer API:

Function IsInArray(ByVal findString as String, ByVal arrayToSearch as Variant) as Boolean
  IsInArray = UBound(Filter(arrayToSearch,findString)) >= 0
End Function

The Filter function has the following signature:

Filter(sourceArray, stringToMatch, [Include As Boolean = True], [Compare as VbCompareMethod = vbBinaryCompare])

how to check if item is selected from a comboBox in C#

if (comboBox1.SelectedIndex == -1)
{
    //Done
}

It Works,, Try it

"Could not find acceptable representation" using spring-boot-starter-web

I had to explicitly call out the dependency for my json library in my POM.

Once I added the below dependency, it all worked.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

How do you add swap to an EC2 instance?

You can add a 1 GB swap to your instance with these commands:

sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
sudo mkswap /swapfile
sudo swapon /swapfile

To enable it by default after reboot, add this line to /etc/fstab:

/swapfile swap swap defaults 0 0

How can I access my localhost from my Android device?

With the simple solution (just access laptop_ip_addr:port from mobile device, when mobile and laptop are on the same WiFi), I get a ERR_CONNECTION_REFUSED error. That is, my MacBook seems to refuse the connection attempt from my mobile.


ADB Reverse Socket (Android only)

This solution works for me (tested with a MacBook):

  1. Connect Android mobile device with USB cable to laptop
  2. Enable USB Debugging on mobile device
  3. On laptop, run adb reverse tcp:4000 tcp:4000
    • Use your custom port number instead of 4000
  4. Now, on the mobile device, you can navigate to http://localhost:4000/, and it will actually connect to the laptop, not the mobile device

See instructions here.

The downside is that this works only with a single mobile device at a time. If you want access with another mobile device, you have to first disconnect the first one (disable USB Debugging), connect the new one (enable USB Debugging), and run adb reverse tcp:4000 tcp:4000 again.


ngrok (works with all devices)

Another solution that should always work is ngrok (as mentioned in other answers). It works over the Internet, and not the local network.

It's extremely easy to use:

brew cask install ngrok
ngrok http 4000

This outputs, among some other information, a line like

Forwarding                    http://4cc5ac02.ngrok.io -> localhost:4000

Now, you can navigate to http://4cc5ac02.ngrok.io on any device that is connected to the Internet, and this URL redirects to localhost:4000 of your laptop.

Note that as long as the ngrok command is running (until you hit Ctrl-C), your project is publicly served. Everybody who has the URL can see it.

Printing hexadecimal characters in C

You can use hh to tell printf that the argument is an unsigned char. Use 0 to get zero padding and 2 to set the width to 2. x or X for lower/uppercase hex characters.

uint8_t a = 0x0a;
printf("%02hhX", a); // Prints "0A"
printf("0x%02hhx", a); // Prints "0x0a"

Edit: If readers are concerned about 2501's assertion that this is somehow not the 'correct' format specifiers I suggest they read the printf link again. Specifically:

Even though %c expects int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called.

The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header <cinttypes>(C++) or <inttypes.h> (C) (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).

As for his point about signed vs unsigned, in this case it does not matter since the values must always be positive and easily fit in a signed int. There is no signed hexideximal format specifier anyway.

Edit 2: ("when-to-admit-you're-wrong" edition):

If you read the actual C11 standard on page 311 (329 of the PDF) you find:

hh: Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.

Where Is Machine.Config?

In your asp.net app use this

using System.Configuration;
Response.Write(ConfigurationManager.OpenMachineConfiguration().FilePath);

How to list all `env` properties within jenkins pipeline job?

Here's a quick script you can add as a pipeline job to list all environment variables:

node {
    echo(env.getEnvironment().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
    echo(System.getenv().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
}

This will list both system and Jenkins variables.

Are (non-void) self-closing tags valid in HTML5?

  • In HTML 4, <foo / (yes, with no > at all) means <foo> (which leads to <br /> meaning <br>> (i.e. <br>&gt;) and <title/hello/ meaning <title>hello</title>). This is an SGML rule that browsers did a very poor job of supporting, and the spec advises authors to avoid the syntax.

  • In XHTML, <foo /> means <foo></foo>. This is an XML rule that applies to all XML documents. That said, XHTML is often served as text/html which (historically at least) gets processed by browsers using a different parser than documents served as application/xhtml+xml. The W3C provides compatibility guidelines to follow for XHTML as text/html. (Essentially: Only use self-closing tag syntax when the element is defined as EMPTY (and the end tag was forbidden in the HTML spec)).

  • In HTML5, the meaning of <foo /> depends on the type of element.

    • On HTML elements that are designated as void elements (essentially "An element that existed before HTML5 and which was forbidden to have any content"), end tags are simply forbidden. The slash at the end of the start tag is allowed, but has no meaning. It is just syntactic sugar for people (and syntax highlighters) that are addicted to XML.
    • On other HTML elements, the slash is an error, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings.
    • Foreign elements (imported from XML applications such as SVG) treat it as self-closing syntax.

Adding Only Untracked Files

If you have thousands of untracked files (ugh, don't ask) then git add -i will not work when adding *. You will get an error stating Argument list too long.

If you then also are on Windows (don't ask #2 :-) and need to use PowerShell for adding all untracked files, you can use this command:

git ls-files -o --exclude-standard | select | foreach { git add $_ }

In C - check if a char exists in a char array

The less well-known but extremely useful (and standard since C89 — meaning 'forever') functions in the C library provide the information in a single call. Actually, there are multiple functions — an embarrassment of riches. The relevant ones for this are:

7.21.5.3 The strcspn function

Synopsis

#include <string.h>
size_t strcspn(const char *s1, const char *s2);

Description

The strcspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2.

Returns

The strcspn function returns the length of the segment.

7.21.5.4 The strpbrk function

Synopsis

#include <string.h>
char *strpbrk(const char *s1, const char *s2);

Description

The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.

Returns

The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.

The question asks about 'for each char in string ... if it is in list of invalid chars'.

With these functions, you can write:

size_t len = strlen(test);
size_t spn = strcspn(test, "invald");

if (spn != len) { ...there's a problem... }

Or:

if (strpbrk(test, "invald") != 0) { ...there's a problem... }

Which is better depends on what else you want to do. There is also the related strspn() function which is sometimes useful (whitelist instead of blacklist).

Make a phone call programmatically

To go back to original app you can use telprompt:// instead of tel:// - The tell prompt will prompt the user first, but when the call is finished it will go back to your app:

NSString *phoneNumber = [@"telprompt://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];

Using regular expression in css?

An ID is meant to identify the element uniquely. Any styles applied to it should also be unique to that element. If you have styles you want to apply to many elements, you should add a class to them all, rather than relying on ID selectors...

<div id="sections">
   <div id="s1" class="sec">...</div>
   <div id="s2" class="sec">...</div>
   ...
</div>

and

.sec {
    ...
}

Or in your specific case you could select all divisions inside your parent container, if nothing else is inside it, like so:

#sections > div {
    ...
}

Disabled form fields not submitting data

We can also use the readonly only with below attributes -

readonly onclick='return false;'

This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.

How to select all instances of selected region in Sublime Text

Note: You should not edit the default settings, because they get reset on updates/upgrades. For customization, you should override any setting by using the user bindings.

On Mac:

  • Sublime Text 2 > Preferences > Key Bindings-Default
  • Sublime Text 3 > Preferences > Key Bindings

This opens a document that you can edit the keybindings for Sublime.

If you search "ctrl+super+g" you find this:

{ "keys": ["ctrl+super+g"], "command": "find_all_under" },

If isset $_POST

Use !empty() instead of isset(). Because isset() will always return true in your case.

if (!empty($_POST["mail"])) {
    echo "Yes, mail is entered";    
} else {  
    echo "No, mail is not entered";
}

Youtube - How to force 480p video quality in embed link / <iframe>

You can use the YouTube JavaScript player API, which has a feature on its own to set playback quality.

player.setPlaybackQuality(suggestedQuality:String):Void

This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played. Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change, the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function. [source]

Sum of two input value by jquery

if in multiple class you want to change additional operation in perticular class that show in below example

$('.like').click(function(){    
var like= $(this).text();
$(this).text(+like + +1);
});

How to convert array to SimpleXML

Another improvement:

/**
* Converts an array to XML
*
* @param array $array
* @param SimpleXMLElement $xml
* @param string $child_name
*
* @return SimpleXMLElement $xml
*/
public function arrayToXML($array, SimpleXMLElement $xml, $child_name)
{
    foreach ($array as $k => $v) {
        if(is_array($v)) {
            (is_int($k)) ? $this->arrayToXML($v, $xml->addChild($child_name), $v) : $this->arrayToXML($v, $xml->addChild(strtolower($k)), $child_name);
        } else {
            (is_int($k)) ? $xml->addChild($child_name, $v) : $xml->addChild(strtolower($k), $v);
        }
    }

    return $xml->asXML();
}

Usage:

$this->arrayToXML($array, new SimpleXMLElement('<root/>'), 'child_name_to_replace_numeric_integers');

how to set radio option checked onload with jQuery

This one will cause form.reset() failure:

$('input:radio[name=gender][value=Male]').attr('checked', true);

But this one works:

$('input:radio[name=gender][value=Male]').click();

Objective-C and Swift URL encoding

int strLength = 0;
NSString *urlStr = @"http://www";
NSLog(@" urlStr : %@", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@":" withString:@"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );

What characters are forbidden in Windows and Linux directory names?

Under Linux and other Unix-related systems, there are only two characters that cannot appear in the name of a file or directory, and those are NUL '\0' and slash '/'. The slash, of course, can appear in a path name, separating directory components.

Rumour1 has it that Steven Bourne (of 'shell' fame) had a directory containing 254 files, one for every single letter (character code) that can appear in a file name (excluding /, '\0'; the name . was the current directory, of course). It was used to test the Bourne shell and routinely wrought havoc on unwary programs such as backup programs.

Other people have covered the Windows rules.

Note that MacOS X has a case-insensitive file system.


1 It was Kernighan & Pike in The Practice of Programming who said as much in Chapter 6, Testing, §6.5 Stress Tests:

When Steve Bourne was writing his Unix shell (which came to be known as the Bourne shell), he made a directory of 254 files with one-character names, one for each byte value except '\0' and slash, the two characters that cannot appear in Unix file names. He used that directory for all manner of tests of pattern-matching and tokenization. (The test directory was of course created by a program.) For years afterwards, that directory was the bane of file-tree-walking programs; it tested them to destruction.

Note that the directory must have contained entries . and .., so it was arguably 253 files (and 2 directories), or 255 name entries, rather than 254 files. This doesn't affect the effectiveness of the anecdote, or the careful testing it describes.

Where to find Java JDK Source Code?

The JDK 1.6 I'm currently using on OSX Mountain Lion did not come with a src.zip either, and as far as i can tell there is no supported OSX JDK for 1.6 available anymore.

So I downloaded the OpenJDK source (using the links from the accepted answer (+1)) then ran:

cd ~/Downloads
mkdir jdk6src
cd jdk6src
tar xf ../openjdk-6-src-b27-26_oct_2012.tar.gz
cd jdk/src/share/classes
jar cf /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/src.jar *

(your file names and paths may vary...)

Associate that src.jar with the appropriate Java platform in your IDE and you should be good to go.

There are some discrepancies between the OpenJDK source and the JDK I'm currently running (line numbers don't match up in the debugger, for one), but if all you want is a zip/jar to point your IDE to for the relatively few cases you need to peek at some code to understand how something works, then this should do the trick.

How can I read numeric strings in Excel cells as string (not numbers)?

There is a ready-to-use wrapper (some additional optimizations can be applied)

  • it supports numeric and String cells

  • formulas are recognized and handled automatically

  • avoid some boilerplate

     public final class Cell {
    
     private final static DataFormatter FORMATTER = new DataFormatter();
    
     private XSSFCell mCell;
    
     public Cell(@NotNull XSSFCell cell) {
         mCell = cell;
    
         if (isFormula()) {
             XSSFWorkbook book = mCell.getSheet().getWorkbook();
             FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();
             mCell = (XSSFCell) evaluator.evaluateInCell(mCell);
         }
     }
    
     /**
      * Get content
      */
     public final int getInt() {
         return (int) getLong();
     }
    
     public final long getLong() {
         return Math.round(getDouble());
     }
    
     public final double getDouble() {
         return mCell.getNumericCellValue();
     }
    
     public final String getString() {
         if (!isString()) {
             return FORMATTER.formatCellValue(mCell);
         }
         return mCell.getStringCellValue();
     }
    
     /**
      * Get properties
      */
     public final boolean isNumber() {
         if (isFormula()) {
             return mCell.getCachedFormulaResultType().equals(CellType.NUMERIC);
         }
         return mCell.getCellType().equals(CellType.NUMERIC);
     }
    
     public final boolean isString() {
         if (isFormula()) {
             return mCell.getCachedFormulaResultType().equals(CellType.STRING);
         }
         return mCell.getCellType().equals(CellType.STRING);
     }
    
     public final boolean isFormula() {
         return mCell.getCellType().equals(CellType.FORMULA);
     }
    
     /**
      * Debug info
      */
     @Override
     public String toString() {
         return getString();
     }
     }
    

Understanding typedefs for function pointers in C

This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.

    typedef double (*pf)(double x);  /*this defines a type pf */

    double f1(double x) { return(x+x);}
    double f2(double x) { return(x*x);}

    pf pa[] = {f1, f2};


    main()
    {
        pf p;

        p = pa[0];
        printf("%f\n", p(3.0));
        p = pa[1];
        printf("%f\n", p(3.0));
    }

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

To solve this problem just call jQuery file before the bootstrap file

How to enter special characters like "&" in oracle database?

Also you can use concat like this :D

Insert into Table Value(CONCAT('JAVA ',CONCAT('& ', 'Oracle'));

Difference between ProcessBuilder and Runtime.exec()

Yes there is a difference.

  • The Runtime.exec(String) method takes a single command string that it splits into a command and a sequence of arguments.

  • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)

So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.

What is __gxx_personality_v0 for?

It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.

The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.

Of course, if nothing is using exceptions, you can disable them with -fno-exceptions (and if nothing is using RTTI, you can also add -fno-rtti). If you are using them, you have to (as other answers already noted) link with g++ instead of gcc, which will add -lstdc++ for you.

Creating default object from empty value in PHP?

Simply,

    $res = (object)array("success"=>false); // $res->success = bool(false);

Or you could instantiate classes with:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new \stdClass(); // object(stdClass) -> old method

and fill values with:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

More infos: https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

Java LinkedHashMap get first or last entry

The semantics of LinkedHashMap are still those of a Map, rather than that of a LinkedList. It retains insertion order, yes, but that's an implementation detail, rather than an aspect of its interface.

The quickest way to get the "first" entry is still entrySet().iterator().next(). Getting the "last" entry is possible, but will entail iterating over the whole entry set by calling .next() until you reach the last. while (iterator.hasNext()) { lastElement = iterator.next() }

edit: However, if you're willing to go beyond the JavaSE API, Apache Commons Collections has its own LinkedMap implementation, which has methods like firstKey and lastKey, which do what you're looking for. The interface is considerably richer.

Can I have multiple :before pseudo-elements for the same element?

If your main element has some child elements or text, you could make use of it.

Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).

Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.

This element will start acting like his owner is your main element.

HTML

<div class="circle">
    <span>Some text</span>
</div>

CSS

.circle {
    position: relative; /* or absolute/fixed */
}

.circle:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle:after {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle span {
    /* not relative/absolute/fixed */
}

.circle span:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

Checking if output of a command contains a certain string in a shell script

A clean if/else conditional shell script:

if ./somecommand | grep -q 'some_string'; then
  echo "exists"
else
  echo "doesn't exist"
fi

document.getElementById().value doesn't set the value

Refer below Code Snip

In HTML Page

<input id="test" type="number" value="0"/>

In Java Script

document.getElementById("test").value=request.responseText;// in case of String 
document.getElementById("test").value=new Number(responseText);// in case of Number

jQuery Datepicker localization

If you want to include some options besides regional localization, you have to use $.extend, like this:

$(function() {
   $('#Date').datepicker($.extend({
      showMonthAfterYear: false,
      dateFormat:'d MM, y'
    },
    $.datepicker.regional['fr']
  ));
});

How do I get a file extension in PHP?

I found that the pathinfo() and SplFileInfo solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a # (fragment identifiers) and/or ? (query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.

I found this was a reliable way to use pathinfo() on a URL after first parsing it to strip out the unnecessary clutter after the file extension:

$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()

display Java.util.Date in a specific format

This will help you. DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); print (df.format(new Date());

Android Studio SDK location

Consider Using windows 7 64bits

C:\Users\Administrador\AppData\Local\Android\sdk

Toggle input disabled attribute using jQuery

Another simple option that updates on a click of the checkbox.

HTML:

<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>

jQuery:

$('#checkbox').click(function() {
    if (this.checked) {
        $('#item').prop('disabled', false); // If checked enable item       
    } else {
        $('#item').prop('disabled', true); // If checked disable item                   
    }
});

In action: link

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

How to pipe list of files returned by find command to cat to view all the files

I use something like this:

find . -name <filename> -print0 | xargs -0 cat | grep <word2search4>

"-print0" argument for "find" and "-0" argument for "xargs" are needed to handle whitespace in file paths/names correctly.

Inline SVG in CSS

I've forked a CodePen demo that had the same problem with embedding inline SVG into CSS. A solution that works with SCSS is to build a simple url-encoding function.

A string replacement function can be created from the built-in str-slice, str-index functions (see css-tricks, thanks to Hugo Giraudel).

Then, just replace %,<,>,",', with the %xxcodes:

@function svg-inline($string){
  $result: str-replace($string, "<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  $result: str-replace($result, '%', '%25');
  $result: str-replace($result, '"', '%22');
  $result: str-replace($result, "'", '%27');
  $result: str-replace($result, ' ', '%20');
  $result: str-replace($result, '<', '%3C');
  $result: str-replace($result, '>', '%3E');
  @return "data:image/svg+xml;utf8," + $result;
}

$mySVG: svg-inline("<svg>...</svg>");

html {
  height: 100vh;
  background: url($mySVG) 50% no-repeat;
}

There is also a image-inline helper function available in Compass, but since it is not supported in CodePen, this solution might probably be useful.

Demo on CodePen: http://codepen.io/terabaud/details/PZdaJo/

Regular expression to allow spaces between words

Just add a space to end of your regex pattern as follows:

[a-zA-Z0-9_ ]

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Here is my tip. Tested with vscode 1.21.1 (on MAC)

Put below config to tsconfig.json

"lib": [
"es2016",
"dom"
]

into compilerOptions

Restart IDE (this action is required :D )

HTML select dropdown list

    <select>
         <option value="" disabled="disabled" selected="selected">Please select a 
              developer position</option>
          <option value="1">Beginner</option>
          <option value="2">Expert</option>
     </select>

How to get 0-padded binary representation of an integer in java?

I think this is a suboptimal solution, but you could do

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')

Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

Not sure if this is what you're referring to, but this is the list of HTML entities you can use:

List of XML and HTML character entity references

Using the content within the 'Name' column you can just wrap these in an & and ;

E.g. &nbsp;, &emsp;, etc.

What does {0} mean when found in a string in C#?

You are printing a formatted string. The {0} means to insert the first parameter following the format string; in this case the value associated with the key "rtf".

For String.Format, which is similar, if you had something like

//            Format string                    {0}           {1}
String.Format("This {0}.  The value is {1}.",  "is a test",  42 ) 

you'd create a string "This is a test. The value is 42".

You can also use expressions, and print values out multiple times:

//            Format string              {0} {1}  {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1,  1+1, 1+2) 

yielding "Fib: 1, 1, 2, 3"

See more at http://msdn.microsoft.com/en-us/library/txafckwd.aspx, which talks about composite formatting.

Saving a text file on server using JavaScript

You must have a server-side script to handle your request, it can't be done using javascript.

To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:

JS:

var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

PHP:

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name

$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}

Edit:

As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:

var xhr = new XMLHttpRequest();

Also please note that this works only for browsers that support FormData such as IE +10.

How to configure robots.txt to allow everything?

That file will allow all crawlers access

User-agent: *
Allow: /

This basically allows all user agents (the *) to all parts of the site (the /).

Center Div inside another (100% width) div

.outerdiv {
    margin-left: auto;
    margin-right: auto;
    display: table;
}

Doesn't work in internet explorer 7... but who cares ?

CSS Inset Borders

So I was trying to have a border appear on hover but it moved the entire bottom bar of the main menu which didn't look all that good I fixed it with the following:

#top-menu .menu-item a:hover {
    border-bottom:4px solid #ec1c24;
    padding-bottom:14px !important;
}
#top-menu .menu-item a {
    padding-bottom:18px !important;
}

I hope this will help someone out there.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

This worked for me:

Instead of:

sut.myPrivateMethod();

This:

sut['myPrivateMethod']();

Convert list of ASCII codes to string (byte array) in Python

I much prefer the array module to the struct module for this kind of tasks (ones involving sequences of homogeneous values):

>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'

no len call, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!

Array slices in C#

You could use the arrays CopyTo() method.

Or with LINQ you can use Skip() and Take()...

byte[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
var subset = arr.Skip(2).Take(2);

How can I create directory tree in C++/Linux?

bool mkpath( std::string path )
{
    bool bSuccess = false;
    int nRC = ::mkdir( path.c_str(), 0775 );
    if( nRC == -1 )
    {
        switch( errno )
        {
            case ENOENT:
                //parent didn't exist, try to create it
                if( mkpath( path.substr(0, path.find_last_of('/')) ) )
                    //Now, try to create again.
                    bSuccess = 0 == ::mkdir( path.c_str(), 0775 );
                else
                    bSuccess = false;
                break;
            case EEXIST:
                //Done!
                bSuccess = true;
                break;
            default:
                bSuccess = false;
                break;
        }
    }
    else
        bSuccess = true;
    return bSuccess;
}

How can you tell if a value is not numeric in Oracle?

CREATE OR REPLACE FUNCTION IS_NUMERIC(P_INPUT IN VARCHAR2) RETURN INTEGER IS
  RESULT INTEGER;
  NUM NUMBER ;
BEGIN
  NUM:=TO_NUMBER(P_INPUT);
  RETURN 1;
EXCEPTION WHEN OTHERS THEN
  RETURN 0;
END IS_NUMERIC;
/

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

Perhaps your code is behind Sheet1, so when you change the focus to Sheet2 the objects cannot be found? If that's the case, simply specifying your target worksheet might help:

Sheets("Sheet1").Range("C21").Select

I'm not very familiar with how Select works because I try to avoid it as much as possible :-). You can define and manipulate ranges without selecting them. Also it's a good idea to be explicit about everything you reference. That way, you don't lose track if you go from one sheet or workbook to another. Try this:

Option Explicit

Sub CopySheet1_to_PasteSheet2()

    Dim CLastFundRow As Integer
    Dim CFirstBlankRow As Integer
    Dim wksSource As Worksheet, wksDest As Worksheet
    Dim rngStart As Range, rngSource As Range, rngDest As Range

    Set wksSource = ActiveWorkbook.Sheets("Sheet1")
    Set wksDest = ActiveWorkbook.Sheets("Sheet2")

    'Finds last row of content
    CLastFundRow = wksSource.Range("C21").End(xlDown).Row
    'Finds first row without content
    CFirstBlankRow = CLastFundRow + 1

    'Copy Data
    Set rngSource = wksSource.Range("A2:C" & CLastFundRow)

    'Paste Data Values
    Set rngDest = wksDest.Range("A21")
    rngSource.Copy
    rngDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    'Bring back to top of sheet for consistancy
    wksDest.Range("A1").Select

End Sub

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Found this on a different forum

If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.

What you are doing is passing 664 which in octal is 1230

In your case you would need

os.chmod("/tmp/test_file", 436)

[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666

jQuery event to trigger action when a div is made visible

The following code (pulled from http://maximeparmentier.com/2012/11/06/bind-show-hide-events-with-jquery/) will enable you to use $('#someDiv').on('show', someFunc);.

(function ($) {
  $.each(['show', 'hide'], function (i, ev) {
    var el = $.fn[ev];
    $.fn[ev] = function () {
      this.trigger(ev);
      return el.apply(this, arguments);
    };
  });
})(jQuery);

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

Well .. That seems very odd to me, but it suddenly worked!!

What I did exactly was:

  1. Navigated to phpMyAdmin folder, and edited the file "config.inc.php"
  2. Looked for the line: $cfg['Servers'][$i]['password'] = '';
  3. Added any password between '', let's say '1234'
  4. Reloaded localhost/phpmyadmin & 127.0.0.1/phpmyadmin (both showed the same error)
  5. Reverted "config.inc.php" to the old state (removed the password)
  6. Re-did step 4

And suddenly it worked!

ssh "permissions are too open" error

I was getting this issue on WSL on Windows while connecting to AWS instance. My issue got resolved by witching to classic Command prompt. You can try switching to a different terminal interface and see if that helps.

How to enable zoom controls and pinch zoom in a WebView?

Check if you don't have a ScrollView wrapping your Webview.

In my case that was the problem. It seems ScrollView gets in the way of the pinch gesture.

To fix it, just take your Webview outside the ScrollView.

JavaScript URL Decode function

Here's what I used:

In JavaScript:

var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);

var decoded_url = decodeURIComponent(encoded_url);

In PHP:

$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);

$decoded_url = url_decode($encoded_url);

You can also try it online here: http://www.mynewsfeed.x10.mx/articles/index.php?id=17

How to disable mouse right click on a web page?

You can use the oncontextmenu event for doing this.

But if the user turns off javascript then you won't be able to handle this.

window.oncontextmenu = function () {
   return false;
}

will disable right click menu.

How to instantiate a File object in JavaScript?

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

I like the idea of seting tomcat6 memory based on available server memory (it is cool because I don't have to change the setup after hardware upgrade). Here is my (a bit extended memory setup):

export CATALINA_OPTS="-Xmx`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k -Xms`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k -XX:NewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k -XX:MaxNewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k -XX:PermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k -XX:MaxPermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k"

Put it to: "{tomcat}/bin/startup.sh" (e.g. "/usr/share/tomcat6/bin" for Ubuntu 10.10)

Getting a slice of keys from a map

A nicer way to do this would be to use append:

keys = []int{}
for k := range mymap {
    keys = append(keys, k)
}

Other than that, you’re out of luck—Go isn’t a very expressive language.

How do I "decompile" Java class files?

All of the JAD links listed so far far seem to be broken, so I found this site. Works great (for Linux, at least)! On Ubuntu 11.10 I had to download the static one for whatever reason.

http://www.varaneckas.com/jad

Can I catch multiple Java exceptions in the same catch clause?

Not exactly before Java 7 but, I would do something like this:

Java 6 and before

try {
  //.....
} catch (Exception exc) {
  if (exc instanceof IllegalArgumentException || exc instanceof SecurityException || 
     exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {

     someCode();

  } else if (exc instanceof RuntimeException) {
     throw (RuntimeException) exc;     

  } else {
    throw new RuntimeException(exc);
  }

}



Java 7

try {
  //.....
} catch ( IllegalArgumentException | SecurityException |
         IllegalAccessException |NoSuchFieldException exc) {
  someCode();
}

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

Seems like your view is typed dynamic. Set the right type on the view and you'll see the error go away.

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

Maven Java EE Configuration Marker with Java Server Faces 1.2

This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

s = "I     am having  a   very  nice  23!@$      day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])

The statement above will go through each chunk of text and remove punctuations before verifying if the chunk is really string of alphabets.

What's the difference between a proxy server and a reverse proxy server?

A forward proxy serves users: it helps users access the server.

A reverse proxy serves the server: it protects the server from users.

How do I obtain a list of all schemas in a Sql Server database

If you are using Sql Server Management Studio, you can obtain a list of all schemas, create your own schema or remove an existing one by browsing to:

Databases - [Your Database] - Security - Schemas

[

How to make Apache serve index.php instead of index.html?

As of today (2015, Aug., 1st), Apache2 in Debian Jessie, you need to edit:

root@host:/etc/apache2/mods-enabled$ vi dir.conf 

And change the order of that line, bringing index.php to the first position:

DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

cast or convert a float to nvarchar?

Do not use floats to store fixed-point, accuracy-required data. This example shows how to convert a float to NVARCHAR(50) properly, while also showing why it is a bad idea to use floats for precision data.

create table #f ([Column_Name] float)
insert #f select 9072351234
insert #f select 907235123400000000000

select
    cast([Column_Name] as nvarchar(50)),
    --cast([Column_Name] as int), Arithmetic overflow
    --cast([Column_Name] as bigint), Arithmetic overflow
    CAST(LTRIM(STR([Column_Name],50)) AS NVARCHAR(50))
from #f

Output

9.07235e+009    9072351234
9.07235e+020    907235123400000010000

You may notice that the 2nd output ends with '10000' even though the data we tried to store in the table ends with '00000'. It is because float datatype has a fixed number of significant figures supported, which doesn't extend that far.

What characters are allowed in an email address?

The answer is (almost) ALL (7-bit ASCII).
If the inclusion rules is "...allowed under some/any/none conditions..."

Just by looking at one of several possible inclusion rules for allowed text in the "domain text" part in RFC 5322 at the top of page 17 we find:

dtext          =   %d33-90 /          ; Printable US-ASCII
                   %d94-126 /         ;  characters not including
                   obs-dtext          ;  "[", "]", or "\"

the only three missing chars in this description are used in domain-literal [], to form a quoted-pair \, and the white space character (%d32). With that the whole range 32-126 (decimal) is used. A similar requirement appear as "qtext" and "ctext". Many control characters are also allowed/used. One list of such control chars appears in page 31 section 4.1 of RFC 5322 as obs-NO-WS-CTL.

obs-NO-WS-CTL  =   %d1-8 /            ; US-ASCII control
                   %d11 /             ;  characters that do not
                   %d12 /             ;  include the carriage
                   %d14-31 /          ;  return, line feed, and
                   %d127              ;  white space characters

All this control characters are allowed as stated at the start of section 3.5:

.... MAY be used, the use of US-ASCII control characters (values
     1 through 8, 11, 12, and 14 through 31) is discouraged ....

And such an inclusion rule is therefore "just too wide". Or, in other sense, the expected rule is "too simplistic".

Change the background color of CardView programmatically

I was having a similar issue with formatting CardViews in a recylerView.

I got this simple solution working, not sure if it's the best solution, but it worked for me.

mv_cardView.getBackground().setTint(Color.BLUE)

It gets the background Drawable of the cardView and tints it.

Does a foreign key automatically create an index?

Say you have a big table called orders, and a small table called customers. There is a foreign key from an order to a customer. Now if you delete a customer, Sql Server must check that there are no orphan orders; if there are, it raises an error.

To check if there are any orders, Sql Server has to search the big orders table. Now if there is an index, the search will be fast; if there is not, the search will be slow.

So in this case, the slow delete could be explained by the absence of an index. Especially if Sql Server would have to search 15 big tables without an index.

P.S. If the foreign key has ON DELETE CASCADE, Sql Server still has to search the order table, but then to remove any orders that reference the deleted customer.

Best way to change the background color for an NSView

In swift you can subclass NSView and do this

class MyView:NSView {
    required init?(coder: NSCoder) {
        super.init(coder: coder);

        self.wantsLayer = true;
        self.layer?.backgroundColor = NSColor.redColor().CGColor;
    }
}

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

no its a string with yyyy/mm/dd and i need it in yyyyMMdd format

If you only need to remove the slashes from a string don't you just replace them?

Example:

myDateString = "2013/03/28";
myDateString = myDateString.Replace("/", "");

myDateString should now be "20130328".

Less of an overkill :)

Compilation error - missing zlib.h

In openSUSE 19.2 installing the patterns-hpc-development_node package fixed this issue for me.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

What's the best three-way merge tool?

KDiff3 open source, cross platform

Same interface for Linux and Windows, very smart algorithm for solving conflicts, regular expressions for automatically solving conflicts, integrate with ClearCase, SVN, Git, MS Visual Studio, editable merged file, compare directories

Its keyboard-navigation is great: ctrl-arrows to navigate the diffs, ctrl-1, 2, 3 to do the merging.

Also, see https://stackoverflow.com/a/2434482/42473

enter image description here

Kotlin - Property initialization using "by lazy" vs. "lateinit"

If you use an unchangable variable, then it is better to initialize with by lazy { ... } or val. In this case you can be sure that it will always be initialized when needed and at most 1 time.

If you want a non-null variable, that can change it's value, use lateinit var. In Android development you can later initialize it in such events like onCreate, onResume. Be aware, that if you call REST request and access this variable, it may lead to an exception UninitializedPropertyAccessException: lateinit property yourVariable has not been initialized, because the request can execute faster than that variable could initialize.

Why doesn't TFS get latest get the latest?

just want to add TFS MSBuild does not support special characters on folders i.e. "@"

i had experienced in the past where one of our project folders named as External@Project1

we created a TFS Build definition to run a custom msbuild file then the workspace folder is not getting any contents at the External@Project1 folder during workspace get latest. It seems that tfs get is failing but does not show any error.

after some trial and error and renaming the folder to _Project1. voila we got files on the the folder (_Project1).

Plotting 4 curves in a single plot, with 3 y-axes

Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.

Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!

close all
clear all 

display('Generating data');

x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);

display('Plotting');

figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
    'YColor','b',...
    'YLim',[0,1],...
    'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)

ax2 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','left',...
           'Color','none',...
           'XColor','k',...
           'YColor','r',...
           'YLim',[0,10],...
           'YTick',[1, 3, 5, 7, 9],...
           'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)

ax3 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','g',...
           'YLim',[0,100],...
           'YTick',[0, 20, 40, 60, 80, 100],...
           'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)

ax4 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','c',...
           'YLim',[0,100],...
           'YTick',[10, 30, 50, 70, 90],...
           'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)

alt text
(source: pablorodriguez.info)

How to restore PostgreSQL dump file into Postgres databases?

1.open the terminal.

2.backup your database with following command

your postgres bin - /opt/PostgreSQL/9.1/bin/

your source database server - 192.168.1.111

your backup file location and name - /home/dinesh/db/mydb.backup

your source db name - mydatabase

/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"

3.restore mydb.backup file into destination.

your destination server - localhost

your destination database name - mydatabase

create database for restore the backup.

/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"

restore the backup.

/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"

How to log Apache CXF Soap Request and Soap Response using Log4j?

Simplest way to achieve pretty logging in Preethi Jain szenario:

LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
loggingInInterceptor.setPrettyLogging(true);
LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
loggingOutInterceptor.setPrettyLogging(true);
factory.getInInterceptors().add(loggingInInterceptor);
factory.getOutInterceptors().add(loggingOutInterceptor);

how to use XPath with XDocument?

XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);

How to semantically add heading to a list

In this case I would use a definition list as so:

<dl>
  <dt>Fruits I like:</dt>
  <dd>Apples</dd>
  <dd>Bananas</dd>
  <dd>Oranges</dd>
</dl>

Execute curl command within a Python script

Try with subprocess

CurlUrl="curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache- 
          Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding: 
          gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' -- 
          compressed"

Use getstatusoutput to store the results

status, output = subprocess.getstatusoutput(CurlUrl)

Appending a vector to a vector

a.insert(a.end(), b.begin(), b.end());

or

a.insert(std::end(a), std::begin(b), std::end(b));

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end;
a.insert(end(a), begin(b), end(b));

How to make <input type="date"> supported on all browsers? Any alternatives?

Chrome Version 50.0.2661.87 m does not support the mm-dd-yy format when assigned to a variable. It uses yy-mm-dd. IE and Firefox work as expected.

How to reduce the space between <p> tags?

Setting both margin-bottom and margin-top to 0em will remove a space between paragraphs:

<style type="text/css">
p {margin-bottom: 0em; margin-top: 0em;}
</style>

Adding extra zeros in front of a number using jQuery?

Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.

var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);

Get min and max value in PHP Array

For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.

How to get a max value:

$highest_weight = max(array_column($details, 'Weight'));

How to get the min value

$lowest_weight = min(array_column($details, 'Weight'));

jquery $('.class').each() how many items?

If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.

However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.

How to change time in DateTime?

When you construct your DateTime object, use a constructor that allows you to specify time:

var myDateTime = new DateTime(2000, 01, 01, 13, 37, 42);  // 2000-01-01 13:37:42

If you already have a DateTime object and wish to change the time, uou can add minutes, hours or seconds to your DateTime using simple methods:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime = myDateTime.AddHours(13);                     // 2000-01-01 13:00:00
myDateTime = myDateTime.AddMinutes(37);                   // 2000-01-01 13:37:00
myDateTime = myDateTime.AddSecounds(42);                  // 2000-01-01 13:37:42

Notice how we have to "save" the result from each method call to the myDateTime variable. This is because the DateTime is immutable, and its methods simply create new instances with the extra hours/minutes/seconds added.

If you need to add both hours and minutes (and/or seconds) and the same time, you can simplify the code by adding a TimeSpan to the original DateTime instead:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime += new TimeSpan(13, 37, 42);                   // 2000-01-01 13:37:42

If you want to set absolute hours/minues/seconds, rather than adding to the existing values, you can use the aforementioned DateTime constructor, and reuse values for year/month/day from earlier:

myDateTime = new DateTime(myDateTime.Year, myDateTime.Month, myDateTime.Day,
                          20, 33, 19)                     // 2000-01-01 20:33:19

mysqli::query(): Couldn't fetch mysqli

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");

Hope it helps.

SQL Server : export query as a .txt file

You can use bcp utility.

To copy the result set from a Transact-SQL statement to a data file, use the queryout option. The following example copies the result of a query into the Contacts.txt data file. The example assumes that you are using Windows Authentication and have a trusted connection to the server instance on which you are running the bcp command. At the Windows command prompt, enter:

bcp "<your query here>" queryout Contacts.txt -c -T

You can use BCP by directly calling as operating sytstem command in SQL Agent job.

Testing javascript with Mocha - how can I use console.log to debug a test?

What Mocha options are you using?

Maybe it is something to do with reporter (-R) or ui (-ui) being used?

console.log(msg);

works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.

Here are the options (mocha.opts) I'm using:

--require should
-R spec
--ui bdd

Hmm..just tested without any mocha.opts and console.log still works.

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

TextFX menu is missing in Notepad++

For 32 bit Notepad++ only

Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install.

It was removed from the default installation as it caused issues with certain configurations, and there's no maintainer.

‘ant’ is not recognized as an internal or external command

Had the same problem. The solution is to add a \ at the end of %ANT_HOME%\bin so it became %ANT_HOME%\bin\

Worked for me. (Should be system var)

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

UnicodeDecodeError, invalid continuation byte

Because UTF-8 is multibyte and there is no char corresponding to your combination of \xe9 plus following space.

Why should it succeed in both utf-8 and latin-1?

Here how the same sentence should be in utf-8:

>>> o.decode('latin-1').encode("utf-8")
'a test of \xc3\xa9 char'

Run on server option not appearing in Eclipse

Perhaps you lost some configuration, check jar dependencies in properties -> Deployment Assembly. If you miss something, try to add dependencies again.

in my case, fixing this, Run on Server appear again.

Using Spring MVC Test to unit test multipart POST request

Have a look at this example taken from the spring MVC showcase, this is the link to the source code:

@RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {

    @Test
    public void readString() throws Exception {

        MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());

        webAppContextSetup(this.wac).build()
            .perform(fileUpload("/fileupload").file(file))
            .andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
    }

}

How to set a default row for a query that returns no rows?

I figured it out, and it should also work for other systems too. It's a variation of WW's answer.

select rate 
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18
union
select 0 as rate 
from d_payment_index 
where not exists( select rate 
                  from d_payment_index
                  where fy = 2007
                    and payment_year = 2008
                    and program_id = 18 )

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

If you are using Visual Studio 2017 Community, the location is:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\ReferenceAssemblies\v2.0

The DLL you want is there: Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

Apparently it is located in the C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\ directory for Visual Studio 2010 Professional version, but take note that the 10.0 will change to correspond with the release year, i.e. VS 2013 was version 12.0, VS 2015 was version 14.0, VS 2017 is 15.0. (VS Express is not supported and would require installing the NUnit NuGet package, through the NuGet Package Manager, instead.)

You go to References, right-click, select Add Reference, Browse. Navigate to the path, then double-click the file.

Then, you need a using statement at the top of your Unit Test class:

using Microsoft.VisualStudio.TestTools.UnitTesting;

Generating random numbers in C

int *generate_randomnumbers(int start, int end){
    int *res = malloc(sizeof(int)*(end-start));
    srand(time(NULL));
    for (int i= 0; i < (end -start)+1; i++){
        int r = rand()%end + start;
        int dup = 0;
        for (int j = 0; j < (end -start)+1; j++){
            if (res[j] == r){
                i--;
                dup = 1;
                break;
            }
        }
        if (!dup)
            res[i] = r;
    }
    return res;
}

How can I clear the SQL Server query cache?

Here is some good explaination. check out it.

http://www.mssqltips.com/tip.asp?tip=1360

CHECKPOINT; 
GO 
DBCC DROPCLEANBUFFERS; 
GO

From the linked article:

If all of the performance testing is conducted in SQL Server the best approach may be to issue a CHECKPOINT and then issue the DBCC DROPCLEANBUFFERS command. Although the CHECKPOINT process is an automatic internal system process in SQL Server and occurs on a regular basis, it is important to issue this command to write all of the dirty pages for the current database to disk and clean the buffers. Then the DBCC DROPCLEANBUFFERS command can be executed to remove all buffers from the buffer pool.

How to safely open/close files in python 2.4

See docs.python.org:

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

Hence use close() elegantly with try/finally:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
    f.close()

This ensures that even if # do stuff with f raises an exception, f will still be closed properly.

Note that open should appear outside of the try. If open itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open raises an exception its result is not assigned to f and it is an error to call f.close().

Howto? Parameters and LIKE statement SQL

Your visual basic code would look something like this:

Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")

cmd.Parameters.Add("@query", searchString)

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

If the problem is with the index as the staging area for commits (i.e. .git/index), you can simply remove the index (make a backup copy if you want), and then restore index to version in the last commit:

On OSX/Linux:

rm -f .git/index
git reset

On Windows:

del .git\index
git reset

(The reset command above is the same as git reset --mixed HEAD)

You can alternatively use lower level plumbing git read-tree instead of git reset.


If the problem is with index for packfile, you can recover it using git index-pack.

Android EditText Hint

I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

This may not be exactly what you have to do, but it may be something like this-

myEditText.setOnFocusListener(new OnFocusListener(){
  public void onFocus(){
    myEditText.setHint("");
  }
});

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

How can I change IIS Express port for a site

If we are talking about a WebSite, not web app, my issue was that the actual .sln folder was somewhere else than the website, and I had not noticed. Look for the .sln path and then for the .vs (hidden) folder there.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

OSX solution:

install latest rvm stable version

rvm get stable

use rvm command to solve the certificates automatically

rvm osx-ssl-certs update all

changing kafka retention period during runtime

I tested and used this command in kafka confluent V4.0.0 and apache kafka V 1.0.0 and 1.0.1

/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config  retention.ms=55000

test is the topic name.

I think it works well in other versions too

Git reset --hard and push to remote repository

Instead of fixing your "master" branch, it's way easier to swap it with your "desired-master" by renaming the branches. See https://stackoverflow.com/a/2862606/2321594. This way you wouldn't even leave any trace of multiple revert logs.

Free tool to Create/Edit PNG Images?

ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

Check out Hex.encodeHexString from Apache Commons Codec.

import org.apache.commons.codec.binary.Hex;

String hex = Hex.encodeHexString(bytes);

Include files from parent or other directory

In laymans terms, and practicality, I see this as an old DOS trick/thing. Whoa! What was that? DOS? Never heard of it!

".." backs you out of the current sub-directory one time to a higher folder/directory, and .. enter typed twice backs you out too 2 higher parent folders. Keep adding the ".. enter" back to back and you will soon find yourself at the top level of the directory.

As for Newbies to understand this better, consider this (in terms of the home PC or "C:\ drive" if you know what that means, rather than the web-servers/host "root directory" ). While your at it, Consider your website existing somewhere on your home PC's hard drive, buried in some folder under the C:\ drive. Lastly, you can think of it as ".." is back one directory and "/" is forward one directory/folder.

Now! If you are using the command prompt and are within the "myDocuments" folder of your PC you must back out of that folder to get closer to the higher directory "C:\" by typing the "../". If you wanted to access a file that is located in the widows directory while you are still in the myDocuments folder you would theoretically type ../windows; in reality of DOS command prompt you would simply type .., but I am setting you up for the web. The / redirects forward to another directory naturally.

Using "myDocuments" lets pretend that you created 2 folders within it called "PHP1" and "PHP2", in such we now have the folders:

  • C:\myDocuments\PHP1
  • C:\myDocuments\PHP2

In PHP1 you place a file called index.php. and in PHP2 folder you placed a file called Found.php. it now becomes:

  • C:\myDocuments\PHP1\index.php
  • C:\myDocuments\PHP2\found.php

Inside the C:\myDocuments\PHP1\index.php file you would need to edit and type something like:

<?php include ('../php2/found.php')?>

The ../ is positional thus it considers your current file location "C:\myDocuments\PHP1\index.php" and is a directive telling it to back out of PHP1 directory and enter or move forward into PHP2 directory to look for the Found.php file. But does it read it? See my thoughts on trouble shooting below.

Now! suppose you have 1 folder PHP1 and a sub-folder PHP2:

  • C:\myDocuments\PHP1\PHP2

you would simply reference/code

<?php include('/PHP2/found.php') ?>

as PHP2 exist as a sub-directory, below or within PHP1 directory.

If the above does not work it may have something to do with access/htaccess or permission to the directory or a typo. To enhance this...getting into trouble shooting...If the "found.php" file has errors/typo's within it, it will crash upon rendering at the error, such could be the reason (require/require_once) that you are experiencing the illusion that it is not changing directories or accessing the file. At last thought on the matter, you may need to instantiate your functions or references in order to use the included/require "whatever" by creating a new variable or object such as

$newObject = new nameobject("origianlThingy");

Remember, just because you are including/requiring something, sometimes means just that, it is included/required to run, but it might need to be recreated to make it active or access it. New will surely re-create an instance of it "if it is readable" and make it available within the current document while preserving the original. However you should reference the newly created variable $newObject in all instances....if its global.

To put this in perspective of some web host account; the web host is some whopping over sized hard-drive (like that on your PC) and your domain is nothing more than a folder they have assigned to you. Your folder is called the root. Inside that folder you can do anything you are allowed to do. your "one of many ways" to move between directories/folders is to use the ../ however many times to back out of your current in reference to folder position you want to find.

In my drunken state I realize that I know too much to be sane, and not enough to be insane!"

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

Can't use method return value in write context

I usually create a global function called is_empty() just to get around this issue

function is_empty($var)
{ 
 return empty($var);
}

Then anywhere I would normally have used empty() I just use is_empty()

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

Inserting created_at data with Laravel

Currently (Laravel 5.4) the way to achieve this is:

$model = new Model();
$model->created_at = Carbon::now();
$model->save(['timestamps' => false]);

Converting string to title case

Try this:

using System.Globalization;
using System.Threading;
public void ToTitleCase(TextBox TextBoxName)
        {
            int TextLength = TextBoxName.Text.Length;
            if (TextLength == 1)
            {
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = 1;
            }
            else if (TextLength > 1 && TextBoxName.SelectionStart < TextLength)
            {
                int x = TextBoxName.SelectionStart;
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = x;
            }
            else if (TextLength > 1 && TextBoxName.SelectionStart >= TextLength)
            {
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = TextLength;
            }
        }


Call this method in the TextChanged event of the TextBox.

Remove ':hover' CSS behavior from element

You want to keep the selector, so adding/removing it won't work. Instead of writing a hard and fast CSS selectors (or two), perhaps you can just use the original selector to apply new CSS rule to that element based on some criterion:

$(".test").hover(
  if(some evaluation) {
    $(this).css('border':0);
  }
);

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

In WAMP, right click on WAMP tray icon then change the port from 3308 to 3306 like this:

enter image description here

What does collation mean?

Reference is taken from this Article: A collation is a set of rules for comparing characters in a character set. It has also ruled for sorting of characters and proper order of two characters varies from language to language. A Collation compared two strings like, if a word is greater than another one, and sort accordingly.

If you are using “latin1” Character set, you can use “latin1_swedish_ci” Collation.

You have to choose right collation because wrong collation may affect your database performance.

How to install libusb in Ubuntu

This should work:

# apt-get install libusb-1.0-0-dev

How to do tag wrapping in VS code?

Embedded Emmet could do the trick:

  1. Select text (optional)
  2. Open command palette (usually Ctrl+Shift+P)
  3. Execute Emmet: Wrap with Abbreviation
  4. Enter a tag div (or an abbreviation .wrapper>p)
  5. Hit Enter

Command can be assigned to a keybinding.

enter image description here


This thing even supports passing arguments:

{
    "key": "ctrl+shift+9",
    "command": "editor.emmet.action.wrapWithAbbreviation",
    "when": "editorHasSelection",
    "args": {
        "abbreviation": "span"
    }
},

Use it like this:

  • span.myCssClass
  • span#myCssId
  • b
  • b.myCssClass

Git Clone: Just the files, please?

git archive --format=tar --remote=<repository URL> HEAD | tar xf -

taken from here

Configuring diff tool with .gitconfig

Others have done a 99% answer on this, but there is one step left out. (My answer will be coming from OS X so you will have to change file paths accordingly.)

You make these changes to your ~/.gitconfig:

[diff]
    tool = diffmerge
[difftool "diffmerge"]
    cmd = /Applications/Diffmerge.app/Contents/MacOS/diffmerge $LOCAL $REMOTE

This will fix the diff tool. You can also fix this without editing the ~/.gitconfig directly by entering these commands from the terminal:

git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd "/Applications/DiffMerge.appContents/MacOS/diffmerge \$LOCAL \$REMOTE"

The 1% that everyone else failed to mention is when using this you can't just run git diff myfile.txt; you need to run git difftool myfile.txt.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

I got this error when I was using the app icon image which was resized to 120x120 from 180x180 sized icon using the preview app on MAC. The error is gone When I removed the 120x120 icon from the project. Resizing icons can mess-up with the format required by Apple.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Carriage return and Line feed... Are both required in C#?

I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.

The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.

Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).

This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.

Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications

Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)

How to print strings with line breaks in java

private static final String mText = "SHOP MA" + "\n" +
        + "----------------------------" + "\n" +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + "\n" +
        + "No  Item  Qty  Price  Amount" + "\n" +
        + "1 Bread 1 50.00  50.00" + "\n" +
        + "____________________________" + "\n";

This should work.

Setting a max height on a table

Add display:block; to the table's css. (in other words.. tell the table to act like a block element rather than a table.)

fiddle here

Get GPS location from the web browser

Let's use the latest fat arrow functions:

navigator.geolocation.getCurrentPosition((loc) => {
  console.log('The location in lat lon format is: [', loc.coords.latitude, ',', loc.coords.longitude, ']');
})

How to run DOS/CMD/Command Prompt commands from VB.NET?

Imports System.IO
Public Class Form1
    Public line, counter As String
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        counter += 1
        If TextBox1.Text = "" Then
            MsgBox("Enter a DNS address to ping")
        Else
            'line = ":start" + vbNewLine
            'line += "ping " + TextBox1.Text
            'MsgBox(line)
            Dim StreamToWrite As StreamWriter
            StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
            StreamToWrite.Write(":start" + vbNewLine + _
                                "Ping -t " + TextBox1.Text)
            StreamToWrite.Close()
            Dim p As New System.Diagnostics.Process()
            p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
            p.Start()
        End If
    End Sub
End Class

This works as well

What characters are valid for JavaScript variable names?

Before JavaScript 1.5: ^[a-zA-Z_$][0-9a-zA-Z_$]*$

In English: It must start with a dollar sign, underscore or one of letters in the 26-character alphabet, upper or lower case. Subsequent characters (if any) can be one of any of those or a decimal digit.

JavaScript 1.5 and later * : ^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$

This is more difficult to express in English, but it is conceptually similar to the older syntax with the addition that the letters and digits can be from any language. After the first character, there are also allowed additional underscore-like characters (collectively called “connectors”) and additional character combining marks (“modifiers”). (Other currency symbols are not included in this extended set.)

JavaScript 1.5 and later also allows Unicode escape sequences, provided that the result is a character that would be allowed in the above regular expression.

Identifiers also must not be a current reserved word or one that is considered for future use.

There is no practical limit to the length of an identifier. (Browsers vary, but you’ll safely have 1000 characters and probably several more orders of magnitude than that.)

Links to the character categories:

  • Letters: Lu, Ll, Lt, Lm, Lo, Nl
    (combined in the regex above as “L”)
  • Combining marks (“modifiers”): Mn, Mc
  • Digits: Nd
  • Connectors: Pc

*n.b. This Perl regex is intended to describe the syntax only — it won’t work in JavaScript, which doesn’t (yet) include support for Unicode Properties. (There are some third-party packages that claim to add such support.)

Choice between vector::resize() and vector::reserve()

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

Take note that resize initialize the newly allocated vector where reserve just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'

You can refer to the documentation regarding the difference of resize and reserve

VBA - If a cell in column A is not blank the column B equals

Another way (Using Formulas in VBA). I guess this is the shortest VBA code as well?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
        .Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
    End With
End Sub

Query error with ambiguous column name in SQL

This happens because there are fields with the same name in more than one table, in the query, because of the joins, so you should reference the fields differently, giving names (aliases) to the tables.