Programs & Examples On #Yuv

YUV is a color space typically used as part of a color image pipeline.

Using ffmpeg to change framerate

With re-encoding:

ffmpeg -y -i seeing_noaudio.mp4 -vf "setpts=1.25*PTS" -r 24 seeing.mp4

Without re-encoding:

First step - extract video to raw bitstream

ffmpeg -y -i seeing_noaudio.mp4 -c copy -f h264 seeing_noaudio.h264

Remux with new framerate

ffmpeg -y -r 24 -i seeing_noaudio.h264 -c copy seeing.mp4

How to create a video from images with FFmpeg?

To create frames from video:

ffmpeg\ffmpeg -i %video% test\thumb%04d.jpg -hide_banner

Optional: remove frames you don't want in output video
(more accurate than trimming video with -ss & -t)

Then create video from image/frames eg.:

ffmpeg\ffmpeg -framerate 30 -start_number 56 -i test\thumb%04d.jpg -vf format=yuv420p test/output.mp4

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

ffmpeg usage to encode a video to H264 codec format

I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it. I tried compiling ffmpeg with the option --enable-encoders=libx264 and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).

Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:

  wget ftp://ftp.videolan.org/pub/x264/snapshots/last_x264.tar.bz2
  tar --bzip2 -xvf last_x264.tar.bz2
  cd x264-snapshot-XXXXXXXX-XXXX/
  ./configure
  make
  sudo make install

And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":

wget http://ffmpeg.org/releases/ffmpeg-0.11.2.tar.bz2
tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
make
sudo install

Now finally you have the libx264 codec to encode, to check it you may run

ffmpeg -codecs | grep h264

and you'll see the options you have were the first D means decoding and the first E means encoding

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

Convert a video to MP4 (H.264/AAC) with ffmpeg

You're trying to convert a (rather rare) .flv file that (already) contains H.264 video and AAC audio.

Formatting your console's output as FFmpeg brings out these details.

 Input #0, flv, from 'video.flv':
   Duration: 00:05:01.20, start: 0.000000, bitrate: 66 kb/s
    Stream #0.0: Video: h264, yuv420p, 320x240 [PAR 1:1 DAR 4:3], 66 kb/s, 29.92 tbr, 1k tbn, 2k tbc 
    Stream #0.1: Audio: aac, 22050 Hz, stereo, s16

The original flv is converted to an .mp4 file with H.264 video and AAC audio (just like the original .flv):

Output #0, mp4, to 'video.mp4': 
    Stream #0.0: Video: mpeg4, yuv420p, 320x240 [PAR 1:1 DAR 4:3], q=2-31, 200 kb/s, 90k tbn, 29.92 tbc 
    Stream #0.1: Audio: 0x0000, 22050 Hz, stereo, s16, 64 kb/s

Because the audio and video data in the .flv are already in the format/codecs you need for the .mp4, you can just copy everything to the new .mp4 container. This process will be massively faster than decoding and reencoding everything:

ffmpeg -i video.flv -vcodec copy -acodec copy video.mp4

or more simply:

ffmpeg -i video.flv -codec copy video.mp4

The real error you're getting is:

Unsupported codec for output stream #0.1

Which means FFmpeg can't convert audio (stream #0.1) to AAC.

You can skip the error by:

  • copying the audio data since it's already AAC encoded (use the copy command above)

or you can solve the error by:

For more details you should also read Converting FLV to MP4 With FFmpeg The Ultimate Guide

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

Connect to SQL Server database from Node.js

msnodesql is working out great for me. Here is a sample:

var mssql = require('msnodesql'), 
    express = require('express'),
    app = express(),
    nconf = require('nconf')

nconf.env()
     .file({ file: 'config.json' });

var conn = nconf.get("SQL_CONN");   
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";

app.get('/api/brands', function(req, res){
    var data = [];
    var jsonObject = {};    

    mssql.open(conn_str, function (err, conn) {
        if (err) {
            console.log("Error opening the connection!");
            return;
        }
        conn.queryRaw("dbo.storedproc", function (err, results) {
        if(err) {
                   console.log(err);
                   res.send(500, "Cannot retrieve records.");
                }
       else {
             //res.json(results);

             for (var i = 0; i < results.rows.length; i++) {
                 var jsonObject = new Object()
                 for (var j = 0; j < results.meta.length; j++) { 

                    paramName = results.meta[j].name;
                    paramValue = results.rows[i][j]; 
                    jsonObject[paramName] = paramValue;

                    }
                    data.push(jsonObject);  //This is a js object we are jsonizing not real json until res.send             
            } 

                res.send(data);

            }       
        });
    });
});

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Add x and y labels to a pandas plot

what about ...

import pandas as pd
import matplotlib.pyplot as plt

values = [[1,2], [2,5]]

df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])

(df2.plot(lw=2,
          colormap='jet',
          marker='.',
          markersize=10,
          title='Video streaming dropout by category')
    .set(xlabel='x axis',
         ylabel='y axis'))

plt.show()

Creating a Custom Event

Yes, provided you have access to the object definition and can modify it to declare the custom event

public event EventHandler<EventArgs> ModelChanged;

And normally you'd back this up with a private method used internally to invoke the event:

private void OnModelChanged(EventArgs e)
{
    if (ModelChanged != null)
        ModelChanged(this, e);
}

Your code simply declares a handler for the declared myMethod event (you can also remove the constructor), which would get invoked every time the object triggers the event.

myObject.myMethod += myNameEvent;

Similarly, you can detach a handler using

myObject.myMethod -= myNameEvent;

Also, you can write your own subclass of EventArgs to provide specific data when your event fires.

TypeError: Object of type 'bytes' is not JSON serializable

You are creating those bytes objects yourself:

item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)

Each of those t.encode(), l.encode() and d.encode() calls creates a bytes string. Do not do this, leave it to the JSON format to serialise these.

Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json module and the standard file object returned by the open() call to handle encoding.

You also don't need to convert your items list to a dictionary; it'll already be an object that can be JSON encoded directly:

class W3SchoolPipeline(object):    
    def __init__(self):
        self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(item) + '\n'
        self.file.write(line)
        return item

I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape') it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Basically, you need to redirect out of that page but it still can make a problem while your internet slow (Redirect header from serverside)

Example of basic scenario :

Click on submit button twice

Way to solve

  • Client side

  • Server side

    • Using differentiate based hashing timestamp / timestamp when request was sent.
    • Userequest tokens. When the main loads up assign a temporary request tocken which if repeated is ignored.

How to view user privileges using windows cmd?

You can use the following commands:

whoami /priv
whoami /all

For more information, check whoami @ technet.

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

Disable arrow key scrolling in users browser

For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).

theCanvas.onkeydown = function (e) {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
        e.view.event.preventDefault();
    }
}

Why not simply do window.event.preventDefault()? MDN states:

window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.

Further readings:

HTML colspan in CSS

I've had some success, although it relies on a few properties to work:

table-layout: fixed border-collapse: separate

and cell 'widths' that divide/span easily, i.e. 4 x cells of 25% width:

_x000D_
_x000D_
.div-table-cell,_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.div-table {_x000D_
  display: table;_x000D_
  border: solid 1px #ccc;_x000D_
  border-left: none;_x000D_
  border-bottom: none;_x000D_
  table-layout: fixed;_x000D_
  margin: 10px auto;_x000D_
  width: 50%;_x000D_
  border-collapse: separate;_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.div-table-row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.div-table-cell {_x000D_
  display: table-cell;_x000D_
  padding: 15px;_x000D_
  border-left: solid 1px #ccc;_x000D_
  border-bottom: solid 1px #ccc;_x000D_
  text-align: center;_x000D_
  background: #ddd;_x000D_
}_x000D_
_x000D_
.colspan-3 {_x000D_
  width: 300%;_x000D_
  display: table;_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.row-1 .div-table-cell:before {_x000D_
  content: "row 1: ";_x000D_
}_x000D_
_x000D_
.row-2 .div-table-cell:before {_x000D_
  content: "row 2: ";_x000D_
}_x000D_
_x000D_
.row-3 .div-table-cell:before {_x000D_
  content: "row 3: ";_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.div-table-row-at-the-top {_x000D_
  display: table-header-group;_x000D_
}
_x000D_
<div class="div-table">_x000D_
_x000D_
  <div class="div-table-row row-1">_x000D_
_x000D_
    <div class="div-table-cell">Cell 1</div>_x000D_
    <div class="div-table-cell">Cell 2</div>_x000D_
    <div class="div-table-cell">Cell 3</div>_x000D_
_x000D_
  </div>_x000D_
_x000D_
  <div class="div-table-row row-2">_x000D_
_x000D_
    <div class="div-table-cell colspan-3">_x000D_
      Cor blimey he's only gone and done it._x000D_
    </div>_x000D_
_x000D_
  </div>_x000D_
_x000D_
  <div class="div-table-row row-3">_x000D_
_x000D_
    <div class="div-table-cell">Cell 1</div>_x000D_
    <div class="div-table-cell">Cell 2</div>_x000D_
    <div class="div-table-cell">Cell 3</div>_x000D_
_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/sfjw26rb/2/

Also, applying display:table-header-group or table-footer-group is a handy way of jumping 'row' elements to the top/bottom of the 'table'.

How to implement a binary search tree in Python?

its easy to implement a BST using two classes, 1. Node and 2. Tree Tree class will be just for user interface, and actual methods will be implemented in Node class.

class Node():

    def __init__(self,val):
        self.value = val
        self.left = None
        self.right = None


    def _insert(self,data):
        if data == self.value:
            return False
        elif data < self.value:
            if self.left:
                return self.left._insert(data)
            else:
                self.left = Node(data)
                return True
        else:
            if self.right:
                return self.right._insert(data)
            else:
                self.right = Node(data)
                return True

    def _inorder(self):
        if self:
            if self.left:
                self.left._inorder()
            print(self.value)
            if self.right:
                self.right._inorder()



class Tree():

    def __init__(self):
        self.root = None

    def insert(self,data):
        if self.root:
            return self.root._insert(data)
        else:
            self.root = Node(data)
            return True
    def inorder(self):
        if self.root is not None:
            return self.root._inorder()
        else:
            return False




if __name__=="__main__":
    a = Tree()
    a.insert(16)
    a.insert(8)
    a.insert(24)
    a.insert(6)
    a.insert(12)
    a.insert(19)
    a.insert(29)
    a.inorder()

Inorder function for checking whether BST is properly implemented.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to use particular CSS styles based on screen size / device

Detection is automatic. You must specify what css can be used for each screen resolution:

/* for all screens, use 14px font size */
body {  
    font-size: 14px;    
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
    body {
        font-size: 13px;
    }
}

Trim Whitespaces (New Line and Tab space) in a String in Oracle

You could use both LTRIM and RTRIM.

select rtrim(ltrim('abcdab','ab'),'ab') from dual;

If you want to trim CHR(13) only when it comes with a CHR(10) it gets more complicated. Firstly, translated the combined string to a single character. Then LTRIM/RTRIM that character, then replace the single character back to the combined string.

select replace(rtrim(ltrim(replace('abccccabcccaab','ab','#'),'#'),'#'),'#','ab') from dual;

Cannot install signed apk to device manually, got error "App not installed"

In my case I was trying to test installing a signed APK and the current installed version on my device was unsigned (building a debug version directly from Android studio)

How to merge remote changes at GitHub?

You probably have changes on github that you never merged. Try git pull to fetch and merge the changes, then you should be able to push. Sorry if I misunderstood your question.

How to hash some string with sha256 in Java?

import java.security.MessageDigest;

public class CodeSnippets {

 public static String getSha256(String value) {
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(value.getBytes());
        return bytesToHex(md.digest());
    } catch(Exception ex){
        throw new RuntimeException(ex);
    }
 }
 private static String bytesToHex(byte[] bytes) {
    StringBuffer result = new StringBuffer();
    for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
    return result.toString();
 }
}

Run a task every x-minutes with Windows Task Scheduler

On XP, I clicked the Advanced button on the Schedule tab. There is a checkbox for Repeat task. The default is every 10 minutes.

Additionally, you can create scheduled task via the command line. I haven't tried this myself, but it looks like you'd want something along the lines of (not tested):

schtasks /create /tn "Some task name" /tr "app.exe" /sc HOURLY 

Delete file from internal storage

String dir = getFilesDir().getAbsolutePath();
File f0 = new File(dir, "myFile");
boolean d0 = f0.delete(); 
Log.w("Delete Check", "File deleted: " + dir + "/myFile " + d0);

The code File dir = getFilesDir(); doesn't work because this is a request for a File object. You're trying to retrieve the String that declares the path to your directory, so you need to declare 'dir' as a String, and then request that the directory's absolute path in String form be returned by the constructor that has access to that information.

Homebrew: Could not symlink, /usr/local/bin is not writable

If you already have a directory in /usr/local for the package you're installing, you can try deleting this directory.

In my case I had previously installed the package I was trying to install without using brew, and had then uninstalled it. There was a directory /usr/local/<my_package>/ left over from that previous install. I deleted this folder (sudo rm -rf /usr/local/<my_package>/) and after that the brew link step was successful.

When & why to use delegates?

I consider delegates to be Anonymous Interfaces. In many cases you can use them whenever you need an interface with a single method, but you don't want the overhead of defining that interface.

How to POST raw whole JSON in the body of a Retrofit request?

Using JsonObject is the way it is:

  1. Create your interface like this:

    public interface laInterfaz{ 
        @POST("/bleh/blah/org")
        void registerPayer(@Body JsonObject bean, Callback<JsonObject> callback);
    }
    
  2. Make the JsonObject acording to the jsons structure.

    JsonObject obj = new JsonObject();
    JsonObject payerReg = new JsonObject();
    payerReg.addProperty("crc","aas22");
    payerReg.addProperty("payerDevManufacturer","Samsung");
    obj.add("payerReg",payerReg);
    /*json/*
        {"payerReg":{"crc":"aas22","payerDevManufacturer":"Samsung"}}
    /*json*/
    
  3. Call the service:

    service.registerPayer(obj, callBackRegistraPagador);
    
    Callback<JsonObject> callBackRegistraPagador = new Callback<JsonObject>(){
        public void success(JsonObject object, Response response){
            System.out.println(object.toString());
        }
    
        public void failure(RetrofitError retrofitError){
            System.out.println(retrofitError.toString());
        }
    };
    

And that its! In my personal opinion, its a lot better than making pojos and working with the class mess. This is a lot more cleaner.

How to set the opacity/alpha of a UIImage?

Based on Alexey Ishkov's answer, but in Swift

I used an extension of the UIImage class.

Swift 2:

UIImage Extension:

extension UIImage {
    func imageWithAlpha(alpha: CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

To use:

let image = UIImage(named: "my_image")
let transparentImage = image.imageWithAlpha(0.5)

Swift 3/4/5:

Note that this implementation returns an optional UIImage. This is because in Swift 3 UIGraphicsGetImageFromCurrentImageContext now returns an optional. This value could be nil if the context is nil or what not created with UIGraphicsBeginImageContext.

UIImage Extension:

extension UIImage {
    func image(alpha: CGFloat) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: .zero, blendMode: .normal, alpha: alpha)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

To use:

let image = UIImage(named: "my_image")
let transparentImage = image?.image(alpha: 0.5)

Java Synchronized list

synchronized(list) {
    for (Object o : list) {}
}

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

DateTime.Compare how to check if a date is less than 30 days old?

No, the Compare function will return either 1, 0, or -1. 0 when the two values are equal, -1 and 1 mean less than and greater than, I believe in that order, but I often mix them up.

Centering Bootstrap input fields

Ok, this is best solution for me. Bootstrap includes mobile-first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. So this worked perfectly on every browser and device:

        <div class="row">
            <div class="col-lg-4"></div>
            <div class="col-lg-4">
                <div class="input-group">
                    <input type="text" class="form-control" /> 
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="button">Go!</button>
                    </span>
                </div><!-- /input-group -->
            </div><!-- /.col-lg-4 -->
            <div class="col-lg-4"></div>
        </div><!-- /.row -->

It means 4 + 4 + 4 =12... so second div will be in the middle that way.

Example: http://jsfiddle.net/jpGwm/embedded/result/

How to Auto-start an Android Application?

If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETED Intent. Android systems broadcasts that intent once boot is completed.

Once you receive that intent you can launch a Service that can do whatever you want to do.

Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.

Is jQuery $.browser Deprecated?

Updated! 3/24/2015 (scroll below hr)

lonesomeday's answer is absolutely correct, I just thought I would add this tidbit. I had made a method a while back for getting browser in Vanilla JS and eventually curved it to replace jQuery.browser in later versions of jQuery. It does not interfere with any part of the new jQuery lib, but provides the same functionality of the traditional jQuery.browser object, as well as some other little features.


New Extended Version!

Is much more thorough for newer browser. Also, 90+% accuracy on mobile testing! I won't say 100%, as I haven't tested on every mobile browser, but new feature adds $.browser.mobile boolean/string. It's false if not mobile, else it will be a String name for the mobile device or browser (Best Guesss like: Android, RIM Tablet, iPod, etc...).

One possible caveat, may not work with some older (unsupported) browsers as it is completely reliant on userAgent string.

JS Minified

/* quick & easy cut & paste */
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);
/* quick & easy cut & paste */

jsFiddle "jQuery Plugin: Get Browser (Extended Alt Edition)"

_x000D_
_x000D_
/** jQuery.browser_x000D_
 * @author J.D. McKinstry (2014)_x000D_
 * @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
 * @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
 *_x000D_
 * @extends jQuery_x000D_
 * @namespace jQuery.browser_x000D_
 * @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
 * @example jQuery.browser.version_x000D_
 * @example jQuery.browser.mobile @returns BOOLEAN_x000D_
 * @example jQuery.browser['browserNameInLowerCase']_x000D_
 * @example jQuery.browser.chrome @returns BOOLEAN_x000D_
 * @example jQuery.browser.safari @returns BOOLEAN_x000D_
 * @example jQuery.browser.opera @returns BOOLEAN_x000D_
 * @example jQuery.browser.msie @returns BOOLEAN_x000D_
 * @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
 * @example jQuery.browser.webkit @returns BOOLEAN_x000D_
 * @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
 */_x000D_
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser);    //    see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
    if (x != 'init')_x000D_
        $('<tr />').append(_x000D_
            $('<th />', { text: x }),_x000D_
            $('<td />', { text: b[x] })_x000D_
        ).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
_x000D_
_x000D_

Git - Ignore files during merge

Example:

  1. You have two branches: master, develop
  2. You created file in develop branch and want to ignore it while merging

Code:

git config --global merge.ours.driver true
git checkout master
echo "path/file_to_ignore merge=ours" >> .gitattributes
git merge develop

You can also ignore files with same extension

for example all files with .txt extension:

echo "*.txt merge=ours" >> .gitattributes

Can a CSV file have a comment?

If you're parsing the file with a FOR command in a batch file a semicolon works (;)

REM test.bat contents

for /F "tokens=1-3 delims=," %%a in (test.csv) do @Echo %%a, %%b, %%c

;test.csv contents (this line is a comment)

;1,ignore this line,no it shouldn't

2,parse this line,yes it should!

;3,ignore this line,no it shouldn't

4,parse this line,yes it should!

OUTPUT:

2, parse this line, yes it should!

4, parse this line, yes it should!

Numbering rows within groups in a data frame

Here is an option using a for loop by groups rather by rows (like OP did)

for (i in unique(df$cat)) df$num[df$cat == i] <- seq_len(sum(df$cat == i))

How to set radio button checked as default in radiogroup?

    RadioGroup radioGroup = new RadioGroup(WvActivity.this);
    RadioButton radioBtn1 = new RadioButton(this);
    RadioButton radioBtn2 = new RadioButton(this);
    RadioButton radioBtn3 = new RadioButton(this);

    radioBtn1.setText("Less");
    radioBtn2.setText("Normal");
    radioBtn3.setText("More");


    radioGroup.addView(radioBtn1);
    radioGroup.addView(radioBtn2);
    radioGroup.addView(radioBtn3);

    radioGroup.check(radioBtn2.getId());

How to check if a variable is empty in python?

See section 5.1:

http://docs.python.org/library/stdtypes.html

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

None

False

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

any empty sequence, for example, '', (), [].

any empty mapping, for example, {}.

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

How to use radio on change event?

<input type="radio" name="radio"  value="upi">upi
<input type="radio" name="radio"  value="bankAcc">Bank

<script type="text/javascript">
$(document).ready(function() {
 $('input[type=radio][name=radio]').change(function() {
   if (this.value == 'upi') {
    //write your logic here

    }
  else if (this.value == 'bankAcc') {
    //write your logic here
 }
 });
 </script>

How is length implemented in Java Arrays?

According to the Java Language Specification (specifically §10.7 Array Members) it is a field:

  • The public final field length, which contains the number of components of the array (length may be positive or zero).

Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.

The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:

[...] arrays have a third header field, for the array size.

How do I calculate the normal vector of a line segment?

m1 = (y2 - y1) / (x2 - x1)

if perpendicular two lines:

m1*m2 = -1

then

m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)

y = m2*x + b //b is offset of new perpendicular line.. 

b is something if you want to pass it from a point you defined

How to set Android camera orientation properly?

I faced the issue when i was using ZBar for scanning in tabs. Camera orientation issue. Using below code i was able to resolve issue. This is not the whole code snippet, Please take only help from this.

 public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
     if (isPreviewRunning) {
            mCamera.stopPreview();
        }

 setCameraDisplayOrientation(mCamera);

        previewCamera();

    }



 public void previewCamera() {

        try {
            // Hard code camera surface rotation 90 degs to match Activity view
            // in portrait
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
            isPreviewRunning = true;
        } catch (Exception e) {
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }


    }


public void setCameraDisplayOrientation(android.hardware.Camera camera) {
        Camera.Parameters parameters = camera.getParameters();

        android.hardware.Camera.CameraInfo camInfo =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(getBackFacingCameraId(), camInfo);


        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (camInfo.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (camInfo.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }




    private int getBackFacingCameraId() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {

                cameraId = i;
                break;
            }
        }
        return cameraId;
    }

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

User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:

  1. Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:

    Create repository on Bitbucket

  2. Fill in the form, click next and then you automatically go to this page:

    Create repository from scratch or add existing files

  3. Choose to add existing files and you go to this page:

    Enter image description here

  4. You use those commands and you upload the existing files to Bitbucket. After that, the files are online.

jquery append div inside div with id and manipulate

Why not go even simpler with either one of these options:

$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Or, if you want to append it to existing content:

$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

How to extract the decimal part from a floating point number in C?

Try this:

int main() {
  double num = 23.345;
  int intpart = (int)num;
  double decpart = num - intpart;
  printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
}

For me, it produces:

Num = 23.345000, intpart = 23, decpart = 0.345000

Which appears to be what you're asking for.

Rounding SQL DateTime to midnight

Here is the simplest thing I've found

-- Midnight floor of current date

SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))

The DATEDIFF returns the integer number of days before or since 1900-1-1, and the Convert Datetime obligingly brings it back to that date at midnight.

Since DateDiff returns an integer you can use add or subtract days to get the right offset.

SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()) + @dayOffset)

This isn't rounding this is truncating...But I think that is what is being asked. (To round add one and truncate...and that's not rounding either, that the ceiling, but again most likely what you want. To really round add .5 (does that work?) and truncate.

It turns out you can add .5 to GetDate() and it works as expected.

-- Round Current time to midnight today or midnight tomorrow

SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE() + .5))

I did all my trials on SQL Server 2008, but I think these functions apply to 2005 as well.

How can I capture the result of var_dump to a string?

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( 'li.target' ).css("border", "3px double red");

Good Luck

How to parse XML using shellscript?

I am surprised no one has mentioned xmlsh. The mission statement :

A command line shell for XML Based on the philosophy and design of the Unix Shells

xmlsh provides a familiar scripting environment, but specifically tailored for scripting xml processes.

A list of shell like commands are provided here.

I use the xed command a lot which is equivalent to sed for XML, and allows XPath based search and replaces.

Get clicked item and its position in RecyclerView

public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.MyViewHolder>{
    public Context context;
    public ArrayList<RvDataItem> dataItems;

    ...
    constructor
    overrides
    ...

    class MyViewHolder extends RecyclerView.ViewHolder{
        public TextView textView;
        public Context context;

        public MyViewHolder(View itemView, Context context) {
            super(itemView);

            this.context = context;

            this.textView = (TextView)itemView.findViewById(R.id.textView);

            // on item click
            itemView.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    // get position
                    int pos = getAdapterPosition();

                    // check if item still exists
                    if(pos != RecyclerView.NO_POSITION){
                        RvDataItem clickedDataItem = dataItems.get(pos);
                        Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getName(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
}

What is "entropy and information gain"?

I really recommend you read about Information Theory, bayesian methods and MaxEnt. The place to start is this (freely available online) book by David Mackay:

http://www.inference.phy.cam.ac.uk/mackay/itila/

Those inference methods are really far more general than just text mining and I can't really devise how one would learn how to apply this to NLP without learning some of the general basics contained in this book or other introductory books on Machine Learning and MaxEnt bayesian methods.

The connection between entropy and probability theory to information processing and storing is really, really deep. To give a taste of it, there's a theorem due to Shannon that states that the maximum amount of information you can pass without error through a noisy communication channel is equal to the entropy of the noise process. There's also a theorem that connects how much you can compress a piece of data to occupy the minimum possible memory in your computer to the entropy of the process that generated the data.

I don't think it's really necessary that you go learning about all those theorems on communication theory, but it's not possible to learn this without learning the basics about what is entropy, how it's calculated, what is it's relationship with information and inference, etc...

How to insert TIMESTAMP into my MySQL table?

You do not need to insert the current timestamp manually as MySQL provides this facility to store it automatically. When the MySQL table is created, simply do this:

  • select TIMESTAMP as your column type
  • set the Default value to CURRENT_TIMESTAMP
  • then just insert any rows into the table without inserting any values for the time column

You'll see the current timestamp is automatically inserted when you insert a row. Please see the attached picture. enter image description here

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

How to make a .NET Windows Service start right after the installation?

You need to add a Custom Action to the end of the 'ExecuteImmediate' sequence in the MSI, using the component name of the EXE or a batch (sc start) as the source. I don't think this can be done with Visual Studio, you may have to use a real MSI authoring tool for that.

Render HTML string as real HTML in a React component

I could not get npm build to work with react-html-parser. However, in my case, I was able to successfully make use of https://reactjs.org/docs/fragments.html. I had a requirement to show few html unicode characters , but they should not be directly embedded in the JSX. Within the JSX, it had to be picked from the Component's state. Component code snippet is given below :

constructor() 
{
this.state = {
      rankMap : {"5" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9733;</Fragment> , 
                 "4" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9734;</Fragment>, 
                 "3" : <Fragment>&#9733; &#9733; &#9733; &#9734; &#9734;</Fragment> , 
                 "2" : <Fragment>&#9733; &#9733; &#9734; &#9734; &#9734;</Fragment>, 
                 "1" : <Fragment>&#9733; &#9734; &#9734; &#9734; &#9734;</Fragment>}
                };
}

render() 
{
       return (<div class="card-footer">
                    <small class="text-muted">{ this.state.rankMap["5"] }</small>
               </div>);
}

Load different application.yml in SpringBoot Test

One option is to work with profiles. Create a file called application-test.yml, move all properties you need for those tests to that file and then add the @ActiveProfiles annotation to your test class:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@ActiveProfiles("test") // Like this
public class MyIntTest{
}

Be aware, it will additionally load the application-test.yml, so all properties that are in application.yml are still going to be applied as well. If you don't want that, either use a profile for those as well, or override them in your application-test.yml.

Deserialize JSON string to c# object

solution :

 public Response Get(string jsonData) {
     var json = JsonConvert.DeserializeObject<modelname>(jsonData);
     var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
     return data;
 }

model:

 public class modelname {
     public long parameter{ get; set; }
     public int parameter{ get; set; }
     public int parameter{ get; set; }
     public string parameter{ get; set; }
 }

How to do date/time comparison

For case when your interval's end it's date without hours like "from 2017-01-01 to whole day of 2017-01-16" it's better to adjust interval's to 23 hours 59 minutes and 59 seconds like:

end = end.Add(time.Duration(23*time.Hour) + time.Duration(59*time.Minute) + time.Duration(59*time.Second)) 

if now.After(start) && now.Before(end) {
    ...
}

Rewrite URL after redirecting 404 error htaccess

Try this in your .htaccess:

.htaccess

ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]

RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]

# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]

The ErrorDocument redirects all 404s to a specific URL, all 500s to another url (replace with your domain).

The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.

Local Redirect:

Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):

ErrorDocument 404 /pages/errors/404_redirect.php

404_redirect.php

<?php
   header('Location: /404/');
   exit;
?>

Redirect based on error number

Looks like you'll need to specify an ErrorDocument line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.

error_redirect.php

<?php
   $error_url = $_SERVER["REDIRECT_STATUS"] . '/';
   $error_path = $error_url . '.php';

   if ( ! file_exists($error_path)) {
      // this is the default error if a specific error page is not found
      $error_url = '404/';
   }

   header('Location: ' . $error_url);
   exit;
?>

How to select a node of treeview programmatically in c#?

Call the TreeView.OnAfterSelect() protected method after you programatically select the node.

How to figure out the SMTP server host?

this really is a question for Serverfault.

Windows:

  1. Open up a command prompt (CMD.exe)
  2. Type nslookup and hit enter
  3. Type set type=MX and hit enter
  4. Type the domain name and hit enter, for example: google.com
  5. The results will be a list of host names that are set up for SMTP

Linux:

  1. Open a command prompt
  2. Type dig domain.name MX and hit enter where domain.name is the domain you are trying to find out the smtp server for.

If you do not get any answers back from your dns server, there is a good chance that there isn't any SMTP Servers set up for that domain. If this is the case, do like other's have suggested and call the hosting companies tech support.

jQuery Mobile - back button

You can try this script in the header of HTML code:

<script>
   $.extend(  $.mobile , {
   ajaxEnabled: false,
   hashListeningEnabled: false
   });
</script>

How to convert a HTMLElement to a string

I was using Angular, and needed the same thing, and landed at this post.

@ViewChild('myHTML', {static: false}) _html: ElementRef;
this._html.nativeElement;

How to check if the request is an AJAX request with PHP

From PHP 7 with null coalescing operator it will be shorter:

$is_ajax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );

How to create a generic array in Java?

What about this solution?

@SafeVarargs
public static <T> T[] toGenericArray(T ... elems) {
    return elems;
}

It works and looks too simple to be true. Is there any drawback?

How to remove anaconda from windows completely?

To use Uninstall-Anaconda.exe in C:\Users\username\Anaconda3 is a good way.

MySQL vs MySQLi when using PHP

There is a manual page dedicated to help choosing between mysql, mysqli and PDO at

The PHP team recommends mysqli or PDO_MySQL for new development:

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

The page also has a feature matrix comparing the extension APIs. The main differences between mysqli and mysql API are as follows:

                               mysqli     mysql
Development Status             Active     Maintenance only
Lifecycle                      Active     Long Term Deprecation Announced*
Recommended                    Yes        No
OOP API                        Yes        No
Asynchronous Queries           Yes        No
Server-Side Prep. Statements   Yes        No
Stored Procedures              Yes        No
Multiple Statements            Yes        No
Transactions                   Yes        No
MySQL 5.1+ functionality       Yes        No

* http://news.php.net/php.internals/53799

There is an additional feature matrix comparing the libraries (new mysqlnd versus libmysql) at

and a very thorough blog article at

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

There's a nice way to eject webpack.config.js from angular-cli. Just run:

$ ng eject

This will generate webpack.config.js in the root folder of your project, and you're free to configure it the way you want. The downside of this is that build/start scripts in your package.json will be replaced with the new commands and instead of

$ ng serve

you would have to do something like

$ npm run build & npm run start

This method should work in all the recent versions of angular-cli (I personally tried a few, with the oldest being 1.0.0-beta.21, and the latest 1.0.0-beta.32.3)

How to implement "confirmation" dialog in Jquery UI dialog?

As much as I hate to use eval, it seemed like the easiest way for me, without causing a lot of problems depending on different circumstances. Similar to the javascript settimeout function.

<a href="#" onclick="javascript:confirm('do_function(params)');">Confirm</a>
<div id="dialog-confirm" title="Confirm" style="display:none;">
    <p>Are you sure you want to do this?</p>
</div>
<script>
function confirm(callback){
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:140,
        modal: false,
        buttons: {
            "Ok": function() {
                $( this ).dialog( "close" );
                eval(callback)
            },
            Cancel: function() {
                $( this ).dialog( "close" );
                return false;
            }
        }
    });
}

function do_function(params){
    console.log('approved');
}
</script>

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

How do you calculate log base 2 in Java for integers?

To add to x4u answer, which gives you the floor of the binary log of a number, this function return the ceil of the binary log of a number :

public static int ceilbinlog(int number) // returns 0 for bits=0
{
    int log = 0;
    int bits = number;
    if ((bits & 0xffff0000) != 0) {
        bits >>>= 16;
        log = 16;
    }
    if (bits >= 256) {
        bits >>>= 8;
        log += 8;
    }
    if (bits >= 16) {
        bits >>>= 4;
        log += 4;
    }
    if (bits >= 4) {
        bits >>>= 2;
        log += 2;
    }
    if (1 << log < number)
        log++;
    return log + (bits >>> 1);
}

Unexpected token < in first line of HTML

Your page references a Javascript file at /Client/public/core.js.

This file probably can't be found, producing either the website's frontpage or an HTML error page instead. This is a pretty common issue for eg. websites running on an Apache server where paths are redirected by default to index.php.

If that's the case, make sure you replace /Client/public/core.js in your script tag <script type="text/javascript" src="/Client/public/core.js"></script> with the correct file path or put the missing file core.js at location /Client/public/ to fix your error!

If you do already find a file named core.js at /Client/public/ and the browser still produces a HTML page instead, check the permissions for folder and file. Either of these might be lacking the proper permissions.

How to communicate between Docker containers via "hostname"

That should be what --link is for, at least for the hostname part.
With docker 1.10, and PR 19242, that would be:

docker network create --net-alias=[]: Add network-scoped alias for the container

(see last section below)

That is what Updating the /etc/hosts file details

In addition to the environment variables, Docker adds a host entry for the source container to the /etc/hosts file.

For instance, launch an LDAP server:

docker run -t  --name openldap -d -p 389:389 larrycai/openldap

And define an image to test that LDAP server:

FROM ubuntu
RUN apt-get -y install ldap-utils
RUN touch /root/.bash_aliases
RUN echo "alias lds='ldapsearch -H ldap://internalopenldap -LL -b
ou=Users,dc=openstack,dc=org -D cn=admin,dc=openstack,dc=org -w
password'" > /root/.bash_aliases
ENTRYPOINT bash

You can expose the 'openldap' container as 'internalopenldap' within the test image with --link:

 docker run -it --rm --name ldp --link openldap:internalopenldap ldaptest

Then, if you type 'lds', that alias will work:

ldapsearch -H ldap://internalopenldap ...

That would return people. Meaning internalopenldap is correctly reached from the ldaptest image.


Of course, docker 1.7 will add libnetwork, which provides a native Go implementation for connecting containers. See the blog post.
It introduced a more complete architecture, with the Container Network Model (CNM)

https://blog.docker.com/media/2015/04/cnm-model.jpg

That will Update the Docker CLI with new “network” commands, and document how the “-net” flag is used to assign containers to networks.


docker 1.10 has a new section Network-scoped alias, now officially documented in network connect:

While links provide private name resolution that is localized within a container, the network-scoped alias provides a way for a container to be discovered by an alternate name by any other container within the scope of a particular network.
Unlike the link alias, which is defined by the consumer of a service, the network-scoped alias is defined by the container that is offering the service to the network.

Continuing with the above example, create another container in isolated_nw with a network alias.

$ docker run --net=isolated_nw -itd --name=container6 -alias app busybox
8ebe6767c1e0361f27433090060b33200aac054a68476c3be87ef4005eb1df17

--alias=[]         

Add network-scoped alias for the container

You can use --link option to link another container with a preferred alias

You can pause, restart, and stop containers that are connected to a network. Paused containers remain connected and can be revealed by a network inspect. When the container is stopped, it does not appear on the network until you restart it.

If specified, the container's IP address(es) is reapplied when a stopped container is restarted. If the IP address is no longer available, the container fails to start.

One way to guarantee that the IP address is available is to specify an --ip-range when creating the network, and choose the static IP address(es) from outside that range. This ensures that the IP address is not given to another container while this container is not on the network.

$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network

$ docker network connect --ip 172.20.128.2 multi-host-network container2
$ docker network connect --link container1:c1 multi-host-network container2

How to extract the substring between two markers?

You can find first substring with this function in your code (by character index). Also, you can find what is after a substring.

def FindSubString(strText, strSubString, Offset=None):
    try:
        Start = strText.find(strSubString)
        if Start == -1:
            return -1 # Not Found
        else:
            if Offset == None:
                Result = strText[Start+len(strSubString):]
            elif Offset == 0:
                return Start
            else:
                AfterSubString = Start+len(strSubString)
                Result = strText[AfterSubString:AfterSubString + int(Offset)]
            return Result
    except:
        return -1

# Example:

Text = "Thanks for contributing an answer to Stack Overflow!"
subText = "to"

print("Start of first substring in a text:")
start = FindSubString(Text, subText, 0)
print(start); print("")

print("Exact substring in a text:")
print(Text[start:start+len(subText)]); print("")

print("What is after substring \"%s\"?" %(subText))
print(FindSubString(Text, subText))

# Your answer:

Text = "gfgfdAAA1234ZZZuijjk"
subText1 = "AAA"
subText2 = "ZZZ"

AfterText1 = FindSubString(Text, subText1, 0) + len(subText1)
BeforText2 = FindSubString(Text, subText2, 0) 

print("\nYour answer:\n%s" %(Text[AfterText1:BeforText2]))

Split function equivalent in T-SQL?

CREATE FUNCTION Split
(
  @delimited nvarchar(max),
  @delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
  id int identity(1,1), -- I use this column for numbering splitted parts
  val nvarchar(max)
)
AS
BEGIN
  declare @xml xml
  set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'

  insert into @t(val)
  select
    r.value('.','varchar(max)') as item
  from @xml.nodes('//root/r') as records(r)

  RETURN
END
GO

usage

Select * from dbo.Split(N'1,2,3,4,6',',')

CSS table column autowidth

The following will solve your problem:

td.last {
    width: 1px;
    white-space: nowrap;
}

Flexible, Class-Based Solution

And a more flexible solution is creating a .fitwidth class and applying that to any columns you want to ensure their contents are fit on one line:

td.fitwidth {
    width: 1px;
    white-space: nowrap;
}

And then in your HTML:

<tr>
    <td class="fitwidth">ID</td>
    <td>Description</td>
    <td class="fitwidth">Status</td>
    <td>Notes</td>
</tr>

How to create bitmap from byte array?

In addition, you can simply convert byte array to Bitmap.

var bmp = new Bitmap(new MemoryStream(imgByte));

You can also get Bitmap from file Path directly.

Bitmap bmp = new Bitmap(Image.FromFile(filePath));

What are the First and Second Level caches in (N)Hibernate?

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.

Quoted from: http://javabeat.net/introduction-to-hibernate-caching/

How can I find the number of elements in an array?

Super easy.

Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof().

For example, given an integer array called myArray

int numArrElements = sizeof(myArray) / sizeof(int);

Now, if the data type of your array isn't constant and could possibly change, make the divisor in the equation use the size of the first value as the size of the data type

For example:

int numArrElements = sizeof(myArray) / sizeof(myArray[0]);

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).

If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.

I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.

It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:

1) You can change the recursion limit with sys.setrecursionlimit(n) until the maximum allowed for your platform:

sys.setrecursionlimit(limit):

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.

Get file size, image width and height before upload

Demo

Not sure if it is what you want, but just simple example:

var input = document.getElementById('input');

input.addEventListener("change", function() {
    var file  = this.files[0];
    var img = new Image();

    img.onload = function() {
        var sizes = {
            width:this.width,
            height: this.height
        };
        URL.revokeObjectURL(this.src);

        console.log('onload: sizes', sizes);
        console.log('onload: this', this);
    }

    var objectURL = URL.createObjectURL(file);

    console.log('change: file', file);
    console.log('change: objectURL', objectURL);
    img.src = objectURL;
});

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you could.

  • A null pointer is converted to false implicitly
  • a non-null pointer is converted to true.

This is part of the C++ standard conversion, which falls in Boolean conversion clause:

§ 4.12 Boolean conversions

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

Is there a way to set background-image as a base64 encoded image?

I tried to do the same as you, but apparently the backgroundImage doesn't work with encoded data. As an alternative, I suggest to use CSS classes and the change between those classes.

If you are generating the data "on the fly" you can load the CSS files dynamically.

CSS:

.backgroundA {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDUxRjY0ODgyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDUxRjY0ODkyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpENTFGNjQ4NjJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpENTFGNjQ4NzJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuT868wAAABESURBVHja7M4xEQAwDAOxuPw5uwi6ZeigB/CntJ2lkmytznwZFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW1qsrwABYuwNkimqm3gAAAABJRU5ErkJggg==");
}

.backgroundB {
    background-image:url("data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPbWLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVrApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=");
}

HTML:

<div id="test" height="20px" class="backgroundA"> 
  div test 1
</div>
<div id="test2" name="test2" height="20px" class="backgroundB">
  div test2
</div>
<input type="button" id="btn" />

Javascript:

function change() {
    if (document.getElementById("test").className =="backgroundA") {
        document.getElementById("test").className="backgroundB";
        document.getElementById("test2").className="backgroundA";
    } else {
        document.getElementById("test").className="backgroundA";
        document.getElementById("test2").className="backgroundB";
    }
}

btn.onclick= change;

I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

enter image description here

Summary:

  • PagingAndSortingRepository extends CrudRepository

  • JpaRepository extends PagingAndSortingRepository

The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.

The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.

Finally the JpaRepository add some more functionality that is specific to JPA.

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

How to open the default webbrowser using java

Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MultiBrowPop {

    public static void main(String[] args) {
        OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");

        String url = "http://www.birdfolk.co.uk/cricmob";
        OUT("We're going to this page: "+ url);

        String myOS = System.getProperty("os.name").toLowerCase();
        OUT("(Your operating system is: "+ myOS +")\n");

        try {
            if(Desktop.isDesktopSupported()) { // Probably Windows
                OUT(" -- Going with Desktop.browse ...");
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(url));
            } else { // Definitely Non-windows
                Runtime runtime = Runtime.getRuntime();
                if(myOS.contains("mac")) { // Apples
                    OUT(" -- Going on Apple with 'open'...");
                    runtime.exec("open " + url);
                } 
                else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours 
                    OUT(" -- Going on Linux with 'xdg-open'...");
                    runtime.exec("xdg-open " + url);
                }
                else 
                    OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
            }
            OUT("\nThings have finished.\nI hope you're OK.");
        }
        catch(IOException | URISyntaxException eek) {
            OUT("**Stuff wrongly: "+ eek.getMessage());
        }
    }

    private static void OUT(String str) {
        System.out.println(str);
    }
}

Display a message in Visual Studio's output window when not debug mode?

The Trace messages can occur in the output window as well, even if you're not in debug mode. You just have to make sure the the TRACE compiler constant is defined.

Locking pattern for proper use of .NET MemoryCache

I assume this code has concurrency issues:

Actually, it's quite possibly fine, though with a possible improvement.

Now, in general the pattern where we have multiple threads setting a shared value on first use, to not lock on the value being obtained and set can be:

  1. Disastrous - other code will assume only one instance exists.
  2. Disastrous - the code that obtains the instance is not can only tolerate one (or perhaps a certain small number) concurrent operations.
  3. Disastrous - the means of storage is not thread-safe (e.g. have two threads adding to a dictionary and you can get all sorts of nasty errors).
  4. Sub-optimal - the overall performance is worse than if locking had ensured only one thread did the work of obtaining the value.
  5. Optimal - the cost of having multiple threads do redundant work is less than the cost of preventing it, especially since that can only happen during a relatively brief period.

However, considering here that MemoryCache may evict entries then:

  1. If it's disastrous to have more than one instance then MemoryCache is the wrong approach.
  2. If you must prevent simultaneous creation, you should do so at the point of creation.
  3. MemoryCache is thread-safe in terms of access to that object, so that is not a concern here.

Both of these possibilities have to be thought about of course, though the only time having two instances of the same string existing can be a problem is if you're doing very particular optimisations that don't apply here*.

So, we're left with the possibilities:

  1. It is cheaper to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().
  2. It is cheaper not to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().

And working that out can be difficult (indeed, the sort of thing where it's worth profiling rather than assuming you can work it out). It's worth considering here though that most obvious ways of locking on insert will prevent all additions to the cache, including those that are unrelated.

This means that if we had 50 threads trying to set 50 different values, then we'll have to make all 50 threads wait on each other, even though they weren't even going to do the same calculation.

As such, you're probably better off with the code you have, than with code that avoids the race-condition, and if the race-condition is a problem, you quite likely either need to handle that somewhere else, or need a different caching strategy than one that expels old entries†.

The one thing I would change is I'd replace the call to Set() with one to AddOrGetExisting(). From the above it should be clear that it probably isn't necessary, but it would allow the newly obtained item to be collected, reducing overall memory use and allowing a higher ratio of low generation to high generation collections.

So yeah, you could use double-locking to prevent concurrency, but either the concurrency isn't actually a problem, or your storing the values in the wrong way, or double-locking on the store would not be the best way to solve it.

*If you know only one each of a set of strings exists, you can optimise equality comparisons, which is about the only time having two copies of a string can be incorrect rather than just sub-optimal, but you'd want to be doing very different types of caching for that to make sense. E.g. the sort XmlReader does internally.

†Quite likely either one that stores indefinitely, or one that makes use of weak references so it will only expel entries if there are no existing uses.

Static Classes In Java

There is a static nested class, this [static nested] class does not need an instance of the enclosing class in order to be instantiated itself.

These classes [static nested ones] can access only the static members of the enclosing class [since it does not have any reference to instances of the enclosing class...]

code sample:

public class Test { 
  class A { } 
  static class B { }
  public static void main(String[] args) { 
    /*will fail - compilation error, you need an instance of Test to instantiate A*/
    A a = new A(); 
    /*will compile successfully, not instance of Test is needed to instantiate B */
    B b = new B(); 
  }
}

How do I limit the number of rows returned by an Oracle query after ordering?

I'v started preparing for Oracle 1z0-047 exam, validated against 12c While prepping for it i came across a 12c enhancement known as 'FETCH FIRST' It enables you to fetch rows /limit rows as per your convenience. Several options are available with it

- FETCH FIRST n ROWS ONLY
 - OFFSET n ROWS FETCH NEXT N1 ROWS ONLY // leave the n rows and display next N1 rows
 - n % rows via FETCH FIRST N PERCENT ROWS ONLY

Example:

Select * from XYZ a
order by a.pqr
FETCH FIRST 10 ROWS ONLY

how to remove new lines and returns from php string?

$str = "Hello World!\n\n";
echo chop($str);

output : Hello World!

Time stamp in the C programming language

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

If might be better off to use gettimeofday() as mentioned here

How to run test cases in a specified file?

There are two ways. The easy one is to use the -run flag and provide a pattern matching names of the tests you want to run.

Example:

$ go test -run NameOfTest

See the docs for more info.

The other way is to name the specific file, containing the tests you want to run:

$ go test foo_test.go

But there's a catch. This works well if:

  • foo.go is in package foo.
  • foo_test.go is in package foo_test and imports 'foo'.

If foo_test.go and foo.go are the same package (a common case) then you must name all other files required to build foo_test. In this example it would be:

$ go test foo_test.go foo.go

I'd recommend to use the -run pattern. Or, where/when possible, always run all package tests.

Java 32-bit vs 64-bit compatibility

All byte code is 8-bit based. (That's why its called BYTE code) All the instructions are a multiple of 8-bits in size. We develop on 32-bit machines and run our servers with 64-bit JVM.

Could you give some detail of the problem you are facing? Then we might have a chance of helping you. Otherwise we would just be guessing what the problem is you are having.

How to run Python script on terminal?

First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:

cd ~/Documents/python

Now, you should be able to execute your file:

python gameover.py

How to make a local variable (inside a function) global

If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:

class StatefulFunction( object ):
    def __init__( self ):
        self.public_value = 'foo'

    def __call__( self ):
        return self.public_value


>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

How to use sed/grep to extract text between two words?

You can strip strings in Bash alone:

$ foo="Here is a String"
$ foo=${foo##*Here }
$ echo "$foo"
is a String
$ foo=${foo%% String*}
$ echo "$foo"
is a
$

And if you have a GNU grep that includes PCRE, you can use a zero-width assertion:

$ echo "Here is a String" | grep -Po '(?<=(Here )).*(?= String)'
is a

ASP.NET Web API session or something?

Well, REST by design is stateless. By adding session (or anything else of that kind) you are making it stateful and defeating any purpose of having a RESTful API.

The whole idea of RESTful service is that every resource is uniquely addressable using a universal syntax for use in hypermedia links and each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP".

So whatever you are trying to do with Web API here, should most likely be re-architectured if you wish to have a RESTful API.

With that said, if you are still willing to go down that route, there is a hacky way of adding session to Web API, and it's been posted by Imran here http://forums.asp.net/t/1780385.aspx/1

Code (though I wouldn't really recommend that):

public class MyHttpControllerHandler
  : HttpControllerHandler, IRequiresSessionState
{
    public MyHttpControllerHandler(RouteData routeData): base(routeData)
    { }
}

public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHttpControllerHandler(requestContext.RouteData);
    }
}

public class ValuesController : ApiController
{
   public string GET(string input)
   {
       var session = HttpContext.Current.Session;
       if (session != null)
       {
           if (session["Time"] == null)
           {
               session["Time"] = DateTime.Now;
           }
           return "Session Time: " + session["Time"] + input;
       }
       return "Session is not availabe" + input;
    }
}

and then add the HttpControllerHandler to your API route:

route.RouteHandler = new MyHttpControllerRouteHandler();

'float' vs. 'double' precision

float : 23 bits of significand, 8 bits of exponent, and 1 sign bit.

double : 52 bits of significand, 11 bits of exponent, and 1 sign bit.

Pretty-print an entire Pandas Series / DataFrame

You can achieve this using below method. just pass the total no. of columns present in the DataFrame as arg to

'display.max_columns'

For eg :

df= DataFrame(..)
with pd.option_context('display.max_rows', None, 'display.max_columns', df.shape[1]):
    print(df)

How to use Console.WriteLine in ASP.NET (C#) during debug?

Console.Write will not work in ASP.NET as it is called using the browser. Use Response.Write instead.

See Stack Overflow question Where does Console.WriteLine go in ASP.NET?.

If you want to write something to Output window during debugging, you can use

System.Diagnostics.Debug.WriteLine("SomeText");

but this will work only during debug.

See Stack Overflow question Debug.WriteLine not working.

How do I enter a multi-line comment in Perl?

POD is the official way to do multi line comments in Perl,

From faq.perl.org[perlfaq7]

The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with =cut, ending the Pod section:

=pod

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=cut

The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.

The =begin directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment. End the comment using =end with the same label. You still need the =cut to go back to Perl code from the Pod comment:

=begin comment

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=end comment

=cut

How to change JDK version for an Eclipse project

Click on the Add Library button. It brings your screen to point to the Java location.

Select "Directory", button right besides JRE home and point to the installed folder location.

Even though you want to just 1.5 compiler project, you can achieve it by changing compiler settings in Eclipse instead of removing 1.6 JRE and add 1.5 JRE.

GOTO -->JAVA--Compiler---> and change compiler level to `1.5` instead of `1.6`

As davidfmatheson suggested,

Just be careful, especially if you're setting this up for a team of people to work on. If anyone uses anything that is new or changed in 1.6, it will compile, but not run in an environment with JRE 1.5.

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

jQuery to retrieve and set selected option value of html select element

to get/set the actual selectedIndex property of the select element use:

$("#select-id").prop("selectedIndex");

$("#select-id").prop("selectedIndex",1);

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Here is one simple solution. It is capable to display and hide custom UIView inside UITableViewCell. Displaying logic is contained inside class extended from UITableViewCell, BaseTableViewCell.

BaseTableViewCell.h

#import <UIKit/UIKit.h>

@interface BaseTableViewCell : UITableViewCell

@property(nonatomic,strong)UIView* customView;

-(void)showCustomView;

-(void)hideCustomView;

@end

BaseTableViewCell.M

#import "BaseTableViewCell.h"

@interface BaseTableViewCell()
{
    BOOL _isCustomViewVisible;
}

@end

@implementation BaseTableViewCell

- (void)awakeFromNib {
    // Initialization code
}

-(void)prepareForReuse
{
    self.customView = nil;
    _isCustomViewVisible = NO;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)showCustomView
{
    if(nil != self.customView)
    {
        if(!_isCustomViewVisible)
        {
            _isCustomViewVisible = YES;

            if(!self.customView.superview)
            {
                CGRect frame = self.customView.frame;
                frame.origin.x = self.contentView.frame.size.width;
                self.customView.frame = frame;
                [self.customView willMoveToSuperview:self.contentView];
                [self.contentView addSubview:self.customView];
                [self.customView didMoveToSuperview];
            }

            __weak BaseTableViewCell* blockSelf = self;
            [UIView animateWithDuration:.5 animations:^(){

                for(UIView* view in blockSelf.contentView.subviews)
                {
                    CGRect frame = view.frame;
                    frame.origin.x = frame.origin.x - blockSelf.customView.frame.size.width;
                    view.frame = frame;
                }
            }];
        }
    }
}

-(void)hideCustomView
{
    if(nil != self.customView)
    {
        if(_isCustomViewVisible)
        {
            __weak BaseTableViewCell* blockSelf = self;
            _isCustomViewVisible = NO;
            [UIView animateWithDuration:.5 animations:^(){
                for(UIView* view in blockSelf.contentView.subviews)
                {
                    CGRect frame = view.frame;
                    frame.origin.x = frame.origin.x + blockSelf.customView.frame.size.width;
                    view.frame = frame;
                }
            }];
        }
    }
}

@end

To get this functionality, simple extend your table view cell from BaseTableViewCell.

Next, Inside UIViewController, which implement UITableViewDelegate, create two gesture recognizers to handle left and right swipes.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.tableView registerNib:[UINib nibWithNibName:CUSTOM_CELL_NIB_NAME bundle:nil] forCellReuseIdentifier:CUSTOM_CELL_ID];

    UISwipeGestureRecognizer* leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftSwipe:)];
    leftSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.tableView addGestureRecognizer:leftSwipeRecognizer];

    UISwipeGestureRecognizer* rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleRightSwipe:)];
    rightSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.tableView addGestureRecognizer:rightSwipeRecognizer];
}

Than add two swipe handlers

- (void)handleLeftSwipe:(UISwipeGestureRecognizer*)recognizer
{
    CGPoint point = [recognizer locationInView:self.tableView];
    NSIndexPath* index = [self.tableView indexPathForRowAtPoint:point];

    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:index];

    if([cell respondsToSelector:@selector(showCustomView)])
    {
        [cell performSelector:@selector(showCustomView)];
    }
}

- (void)handleRightSwipe:(UISwipeGestureRecognizer*)recognizer
{
    CGPoint point = [recognizer locationInView:self.tableView];
    NSIndexPath* index = [self.tableView indexPathForRowAtPoint:point];

    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:index];

    if([cell respondsToSelector:@selector(hideCustomView)])
    {
        [cell performSelector:@selector(hideCustomView)];
    }
}

Now, inside cellForRowAtIndexPath, of UITableViewDelegate, you can create custom UIView and attach it to the dequeued cell.

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCellTableViewCell* cell = (CustomCellTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"CustomCellTableViewCell" forIndexPath:indexPath];

    NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"CellCustomView"
                                                      owner:nil
                                                    options:nil];

    CellCustomView* customView = (CellCustomView*)[ nibViews objectAtIndex: 0];

    cell.customView = customView;

    return cell;
}

Of course, this way of loading of custom UIView is just for this example. Manage it as you want.

How to set background image of a view?

You can set multiple background image in every view using custom method as below.

make plist for every theam with background image name and other color

#import <Foundation/Foundation.h>
@interface ThemeManager : NSObject
@property (nonatomic,strong) NSDictionary*styles;
+ (ThemeManager *)sharedManager;
-(void)selectTheme;
 @end

             #import "ThemeManager.h"

            @implementation ThemeManager
            @synthesize styles;
            + (ThemeManager *)sharedManager
            {
                static ThemeManager *sharedManager = nil;
                if (sharedManager == nil)
                {
                    sharedManager = [[ThemeManager alloc] init];
                }
                [sharedManager selectTheme];
                return sharedManager;
            }
            - (id)init
            {
                if ((self = [super init]))
                {

                }
                return self;
            }
            -(void)selectTheme{
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *themeName = [defaults objectForKey:@"AppTheme"] ?: @"DefaultTheam";

                NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
                self.styles = [NSDictionary dictionaryWithContentsOfFile:path];
            }
            @end

Can use this via

 NSDictionary *styles = [ThemeManager sharedManager].styles;
 NSString *imageName = [styles objectForKey:@"backgroundImage"];
[imgViewBackGround setImage:[UIImage imageNamed:imageName]];

JavaScript: How do I print a message to the error console?

Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.

function log(msg) {
    setTimeout(function() {
        throw new Error(msg);
    }, 0);
}

Usage:

log('Hello World');
log('another message');

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.

HELP!!!

You are trying to add a non-nullable field 'new_field' to userprofile without a default

What Django actually says is:

Userprofile table has data in it and there might be new_field values which are null, but I do not know, so are you sure you want to mark property as non nullable, because if you do you might get an error if there are values with NULL

If you are sure that none of values in the userprofile table are NULL - fell free and ignore the warning.

The best practice in such cases would be to create a RunPython migration to handle empty values as it states in option 2

2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)

In RunPython migration you have to find all UserProfile instances with empty new_field value and put a correct value there (or a default value as Django asks you to set in the model). You will get something like this:

# please keep in mind that new_value can be an empty string. You decide whether it is a correct value.
for profile in UserProfile.objects.filter(new_value__isnull=True).iterator():
    profile.new_value = calculate_value(profile)
    profile.save() # better to use batch save

Have fun!

Using css transform property in jQuery

Setting a -vendor prefix that isn't supported in older browsers can cause them to throw an exception with .css. Instead detect the supported prefix first:

// Start with a fall back
var newCss = { 'zoom' : ui.value };

// Replace with transform, if supported
if('WebkitTransform' in document.body.style) 
{
    newCss = { '-webkit-transform': 'scale(' + ui.value + ')'};
}
// repeat for supported browsers
else if('transform' in document.body.style) 
{
    newCss = { 'transform': 'scale(' + ui.value + ')'};
}

// Set the CSS
$('.user-text').css(newCss)

That works in old browsers. I've done scale here but you could replace it with whatever other transform you wanted.

Insert null/empty value in sql datetime column by default

Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()

-Just a side thought. seems you have things working.

Ruby, remove last N characters from a string?

If you're ok with creating class methods and want the characters you chop off, try this:

class String
  def chop_multiple(amount)
    amount.times.inject([self, '']){ |(s, r)| [s.chop, r.prepend(s[-1])] }
  end
end

hello, world = "hello world".chop_multiple 5
hello #=> 'hello '
world #=> 'world'

Create Pandas DataFrame from a string

A quick and easy solution for interactive work is to copy-and-paste the text by loading the data from the clipboard.

Select the content of the string with your mouse:

Copy data for pasting into a Pandas dataframe

In the Python shell use read_clipboard()

>>> pd.read_clipboard()
  col1;col2;col3
0       1;4.4;99
1      2;4.5;200
2       3;4.7;65
3      4;3.2;140

Use the appropriate separator:

>>> pd.read_clipboard(sep=';')
   col1  col2  col3
0     1   4.4    99
1     2   4.5   200
2     3   4.7    65
3     4   3.2   140

>>> df = pd.read_clipboard(sep=';') # save to dataframe

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

enter image description here

Combining multiple commits before pushing in Git

There are quite a few working answers here, but I found this the easiest. This command will open up an editor, where you can just replace pick with squash in order to remove/merge them into one

git rebase -i HEAD~4

where, 4 is the number of commits you want to squash into one. This is explained here as well.

How to validate date with format "mm/dd/yyyy" in JavaScript?

  1. Javascript

    function validateDate(date) {
        try {
            new Date(date).toISOString();
            return true;
        } catch (e) { 
            return false; 
        }
    }
    
  2. JQuery

    $.fn.validateDate = function() {
        try {
            new Date($(this[0]).val()).toISOString();
            return true;
        } catch (e) { 
            return false; 
        }
    }
    

returns true for a valid date string.

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

Note that Matt's code will result in an extra comma at the end of the string; using COALESCE (or ISNULL for that matter) as shown in the link in Lance's post uses a similar method but doesn't leave you with an extra comma to remove. For the sake of completeness, here's the relevant code from Lance's link on sqlteam.com:

DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
    CAST(EmpUniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

Is it possible to add dynamically named properties to JavaScript object?

A perfect easy way

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};

var newProperty = 'getThisFromUser';
data[newProperty] = 4;

console.log(data);

If you want to apply it on an array of data (ES6/TS version)

const data = [
  { 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 },
  { 'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33 }
];

const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );

console.log(data);

How to change the color of an svg element?

To simply change the color of the svg :

Go to the svg file and under styles, mention the color in fill.

<style>.cls-1{fill:#FFFFFF;}</style>

Why should I use IHttpActionResult instead of HttpResponseMessage?

We have the following benefits of using IHttpActionResult over HttpResponseMessage:

  1. By using the IHttpActionResult we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.
  2. Unit testing of the implemented controller method will be easier.
  3. Uses async and await by default.

Delete cookie by name?

In my case I used blow code for different environment.

  document.cookie = name +`=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;Domain=.${document.domain.split('.').splice(1).join('.')}`;

Split string into array of character strings

for(int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}

jQuery if statement, syntax

I little sophisticated way:

$(selector).is(condition)? alert('true') : alert('false');

Ex:

$("#btn-primary").is(":disabled")? alert('button disabled') : alert('button disabled');

How to fix Git error: object file is empty?

Had the same problem after checking out master from a clean branch. After a while I recognized a lot of modified files in master. I don't know why they have been there, after switching from a clean branch. Anyways, because the modified files made no sense to me, I just stashed them and the error was gone.

git:(master) git stash

PHP: How to remove specific element from an array?

unset($array[array_search('strawberry', $array)]);

How to show DatePickerDialog on Button click?

it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.

 btnDate.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                              DialogFragment newFragment = new DatePickerFragment();
                                    newFragment.show(getSupportFragmentManager(), "datePicker");
                            }
                        });

            public static class DatePickerFragment extends DialogFragment
                        implements DatePickerDialog.OnDateSetListener {

                    @Override
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                        final Calendar c = Calendar.getInstance();
                        int year = c.get(Calendar.YEAR);
                        int month = c.get(Calendar.MONTH);
                        int day = c.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
                        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
                        return  dialog;
                    }

                    public void onDateSet(DatePicker view, int year, int month, int day) {
                       btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
                    }
                }

Getting date format m-d-Y H:i:s.u from milliseconds

php.net says:

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So use as simple:

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Recommended and use dateTime() class from referenced:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note u is microseconds (1 seconds = 1000000 µs).

Another example from php.net:

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime() on php.net

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds

Signing a Windows EXE file

I had the same scenario in my job and here are our findings

The first thing you have to do is get the certificate and install it on your computer, you can either buy one from a Certificate Authority or generate one using makecert.

Here are the pros and cons of the 2 options

Buy a certificate

Generate a certificate using Makecert

  • Pros:
    • The steps are easy and you can share the certificate with the end users
  • Cons:
    • End users will have to manually install the certificate on their machines and depending on your clients that might not be an option
    • Certificates generated with makecert are normally used for development and testing, not production

Sign the executable file

There are two ways of signing the file you want:

  • Using a certificate installed on the computer

    signtool.exe sign /a /s MY /sha1 sha1_thumbprint_value /t http://timestamp.verisign.com/scripts/timstamp.dll /v "C:\filename.dll"

    • In this example we are using a certificate stored on the Personal folder with a SHA1 thumbprint (This thumbprint comes from the certificate) to sign the file located at C:\filename.dll
  • Using a certificate file

    signtool sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /f "c:\path\to\mycert.pfx" /p pfxpassword "c:\path\to\file.exe"

    • In this example we are using the certificate c:\path\to\mycert.pfx with the password pfxpassword to sign the file c:\path\to\file.exe

Test Your Signature

  • Method 1: Using signtool

    Go to: Start > Run
    Type CMD > click OK
    At the command prompt, enter the directory where signtool exists
    Run the following:

    signtool.exe verify /pa /v "C:\filename.dll"

  • Method 2: Using Windows

    Right-click the signed file
    Select Properties
    Select the Digital Signatures tab. The signature will be displayed in the Signature list section.

I hope this could help you

Sources:

How to loop through elements of forms with JavaScript?

You can iterate named fields somehow like this:

let jsonObject = {};
for(let field of form.elements) {
  if (field.name) {
      jsonObject[field.name] = field.value;
  }
}

Or, if you need only submiting fields:

function formDataToJSON(form) {
  let jsonObject = {};
  let formData = new FormData(form);
  for(let field of formData) {
      jsonObject[field[0]] = field[1];
  }
  return JSON.stringify(jsonObject);
}

Expanding a parent <div> to the height of its children

Where We’re Starting From

Here’s some boilerplate HTML and CSS. In our example, we have a parent element with two floated child elements.

_x000D_
_x000D_
/* The CSS you're starting with may look similar to this._x000D_
 * This doesn't solve our problem yet, but we'll get there shortly._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
<!-- The HTML you're starting with might look similar to this -->_x000D_
<div class="containing-div">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Solution #1: overflow: auto

A solution that works in all modern browsers and in Internet Explorer back to IE8 is to add overflow: auto to the parent element. This also works in IE7, with scrollbars added.

_x000D_
_x000D_
/* Our Modified CSS._x000D_
 * This is one way we can solve our problem._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
  overflow: auto;_x000D_
  /*This is what we added!*/_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
_x000D_
_x000D_

Solution #2: Float Parent Container

Another solution that works in all modern browsers and back to IE7 is to float the parent container.

This may not always be practical, because floating your parent div may affect other parts of your page layout.

_x000D_
_x000D_
/* Modified CSS #2._x000D_
 * Floating parent div._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  float: left;_x000D_
  /*Added*/_x000D_
  height: auto;_x000D_
  width: 100%;_x000D_
  /*Added*/_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
_x000D_
_x000D_

Method #3: Add Clearing Div Below Floated Elements

_x000D_
_x000D_
/* _x000D_
 * CSS to Solution #3._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
_x000D_
/*Added*/_x000D_
_x000D_
.clear {_x000D_
  clear: both;_x000D_
}
_x000D_
<!-- Solution 3, Add a clearing div to bottom of parent element -->_x000D_
<div class="containing-div">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Method #4: Add Clearing Div To The Parent Element This solution is pretty bulletproof for older browsers and newer browsers alike.

_x000D_
_x000D_
/* _x000D_
 * CSS to Solution #4._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
_x000D_
/*Added*/_x000D_
_x000D_
.clearfix {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.clearfix:after {_x000D_
  clear: both;_x000D_
  content: "";_x000D_
  display: table;_x000D_
}
_x000D_
<!-- Solution 4, make parent element self-clearing -->_x000D_
<div class="containing-div clearfix">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

from https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/

libxml/tree.h no such file or directory

Blockquote Adding libxml2 in Xcode 4.3.x

Adding libxml2 is a big, fat, finicky pain in the ass. If you're going to do it do it before you get too far in building your project.

Here's how.

Target settings

Click on your target (not your project) and select "Build Phases". Click on the reveal triangle titled "Link Binary With Libraries". Click on the "+" to add a library. Scroll to the bottom of the list and select "libxml2.dylib". That adds the libxml2 library 2 your project… but wait.

Project settings

Now you have to tell your project where to look for it three more times.

Select the "Build Settings tab". Scroll down to the "Linking" section. Under your project's columns double click on the "Other Linker Flags" row. Click the "+" and add "-lxml2" to the list.

Still more.

In the same tab, scroll down to the "Search Paths" section. Under your project's column in the "Framework Search Paths" row add "/usr/lib/libxml2.dylib".

In the "Header Search Paths" AND the "User Header Search Paths" row add "$(SDKROOT)/usr/include/libxml2". In those last two cases make sure that path is entered in Debug AND Release.

Then. Under the "Product" Menu select "Clean".

This is working and for Xcode5 too! Thank you!

Is there a 'foreach' function in Python 3?

Look at this article. The iterator object nditer from numpy package, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

Example:

import random
import numpy as np

ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]])

for ptr in np.nditer(ptrs, op_flags=['readwrite']):
    # apply random shift on 1 for each element of the matrix
    ptr += random.choice([-1, 1])

print(ptrs)

d:\>python nditer.py
[[ -1   1]
 [399  -1]
 [  1 399]
 [399 401]]

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

Create a HTML table where each TR is a FORM

If all of these rows are related and you need to alter the tabular data ... why not just wrap the entire table in a form, and change GET to POST (unless you know that you're not going to be sending more than the max amount of data a GET request can send).

I cannot wrap the entire table in a form, because some input fields of each row are input type="file" and files may be large. When the user submits the form, I want to POST only fields of current row, not all fields of the all rows which may have unneeded huge files, causing form to submit very slowly.

So, I tried incorrect nesting: tr/form and form/tr. However, it works only when one does not try to add new inputs dynamically into the form. Dynamically added inputs will not belong to incorrectly nested form, thus won't get submitted. (valid form/table dynamically inputs are submitted just fine).

Nesting div[display:table]/form/div[display:table-row]/div[display:table-cell] produced non-uniform widths of grid columns. I managed to get uniform layout when I replaced div[display:table-row] to form[display:table-row] :

div.grid {
    display: table;
}

div.grid > form {
    display: table-row;


div.grid > form > div {
    display: table-cell;
}
div.grid > form > div.head {
    text-align: center;
    font-weight: 800;
}

For the layout to be displayed correctly in IE8:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
...
<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9, IE=10" />

Sample of output:

<div class="grid" id="htmlrow_grid_item">
<form>
    <div class="head">Title</div>
    <div class="head">Price</div>
    <div class="head">Description</div>
    <div class="head">Images</div>
    <div class="head">Stock left</div>
    <div class="head">Action</div>
</form>
<form action="/index.php" enctype="multipart/form-data" method="post">
    <div title="Title"><input required="required" class="input_varchar" name="add_title" type="text" value="" /></div>

It would be much harder to make this code work in IE6/7, however.

Should we @Override an interface's method implementation?

Overriding your own methods inherited from your own classes will typically not break on refactorings using an ide. But if you override a method inherited from a library it is recommended to use it. If you dont, you will often get no error on a later library change, but a well hidden bug.

Strtotime() doesn't work with dd/mm/YYYY format

You can parse dates from a custom format (as of PHP 5.3) with DateTime::createFromFormat

$timestamp = DateTime::createFromFormat('!d/m/Y', '23/05/2010')->getTimestamp();

(Aside: The ! is used to reset non-specified values to the Unix timestamp, ie. the time will be midnight.)


If you do not want to (or cannot) use PHP 5.3, then a full list of available date/time formats which strtotime accepts is listed on the Date Formats manual page. That page more thoroughly describes the fact that m/d/Y is inferred over d/m/Y (but you can, as mentioned in the answers here, use d-m-Y, d.m.Y or d\tm\tY).


In the past, I've also resorted to the quicky str_replace mentioned in another answer, as well as self-parsing the date string into another format like

$subject   = '23/05/2010';
$formatted = vsprintf('%3$04d/%2$02d/%1$02d', sscanf($subject,'%02d/%02d/%04d'));
$timestamp = strtotime($formatted);

Excel - Button to go to a certain sheet

You don't need to create a button. The facility exists by default.

Just right click on the arrow buttons on the bottom left hand corner of the Excel window. These are the arrow buttons which if you left click move left or right one worksheet.

If you right-click on these arrows Excel will pop up a dialogue with a list of worksheets from which you can click to set your chosen sheet active.

bootstrap button shows blue outline when clicked

This was happening to me in Chrome (though not in Firefox). I've found out that the outline property was being set by Bootstrap as outline: 5px auto -webkit-focus-ring-color;. Solved by overriding the outline property later in my custom CSS as follows:

.btn.active.focus, .btn.active:focus, .btn.focus, .btn:active.focus, .btn:active:focus, .btn:focus {
    outline: 0;
}

jQuery Set Select Index

select 3rd option

$('#selectBox').val($('#selectBox option').eq(2).val());

Example on jsfiddle

Attach IntelliJ IDEA debugger to a running Java process

It's possible, but you have to add some JVM flags when you start your application.

You have to add remote debug configuration: Edit configuration -> Remote.

Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y)

Access Control Request Headers, is added to header in AJAX request with jQuery

Here is an example how to set a request header in a jQuery Ajax call:

$.ajax({
  type: "POST",
  beforeSend: function(request) {
    request.setRequestHeader("Authority", authorizationToken);
  },
  url: "entities",
  data: "json=" + escape(JSON.stringify(createRequestObject)),
  processData: false,
  success: function(msg) {
    $("#results").append("The result =" + StringifyPretty(msg));
  }
});

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Here is where you went wrong:

this.result = http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result.json());

it should be:

http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result);

or

http.get('friends.json')
                  .subscribe(result => this.result =result.json());

You have made two mistakes:

1- You assigned the observable itself to this.result. When you actually wanted to assign the list of friends to this.result. The correct way to do it is:

  • you subscribe to the observable. .subscribe is the function that actually executes the observable. It takes three callback parameters as follow:

    .subscribe(success, failure, complete);

for example:

.subscribe(
    function(response) { console.log("Success Response" + response)},
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
);

Usually, you take the results from the success callback and assign it to your variable. the error callback is self explanatory. the complete callback is used to determine that you have received the last results without any errors. On your plunker, the complete callback will always be called after either the success or the error callback.

2- The second mistake, you called .json() on .map(res => res.json()), then you called it again on the success callback of the observable. .map() is a transformer that will transform the result to whatever you return (in your case .json()) before it's passed to the success callback you should called it once on either one of them.

How to get div height to auto-adjust to background size?

Just background-size: contain; works for me:

_x000D_
_x000D_
div {
  background-image: url('your-image.png');
  background-size: contain;
}
_x000D_
_x000D_
_x000D_

Setting a windows batch file variable to the day of the week

I Improved Aacini Answer to make it Echo Full day of week Name

So here's my Code

@echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
   for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
      set %%A=%%a
      set %%B=%%b
      set %%C=%%c
   )
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=4-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,dow=(c+dd+e+f-1523)%%7 + 1
for /F "tokens=%dow%" %%a in ("Sunday Monday Tuesday Wednesday Thursday Friday Saturday ") do set dow=%%a
echo Today is %dow%>"Today is %dow%.txt"
echo Today is %dow%
Pause>Nul

REM Sun Mon Tue Wed Thu Fri Sat
REM Sunday Monday Tuesday Wednesday Thursday Friday Saturday  

How to check if a specific key is present in a hash or not?

In latest Ruby versions Hash instance has a key? method:

{a: 1}.key?(:a)
=> true

Be sure to use the symbol key or a string key depending on what you have in your hash:

{'a' => 2}.key?(:a)
=> false

Remove the string on the beginning of an URL

You can cut the url and use response.sendredirect(new url), this will bring you to the same page with the new url

How to resolve symbolic links in a shell script

Common shell scripts often have to find their "home" directory even if they are invoked as a symlink. The script thus have to find their "real" position from just $0.

cat `mvn`

on my system prints a script containing the following, which should be a good hint at what you need.

if [ -z "$M2_HOME" ] ; then
  ## resolve links - $0 may be a link to maven's home
  PRG="$0"

  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG="`dirname "$PRG"`/$link"
    fi
  done

  saveddir=`pwd`

  M2_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  M2_HOME=`cd "$M2_HOME" && pwd`

Regular expression to match characters at beginning of line only

Not sure how to apply that to your file on your server, but typically, the regex to match the beginning of a string would be :

^CTR


The ^ means beginning of string / line

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

Automatically open Chrome developer tools when new tab/new window is opened

If you use Visual Studio Code (vscode), using the very popular vscode chrome debug extension (https://github.com/Microsoft/vscode-chrome-debug) you can setup a launch configuration file launch.json and specify to open the developer tool during a debug session.

This the launch.json I use for my React projects :

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome against localhost",
      "url": "http://localhost:3000",
      "runtimeArgs": ["--auto-open-devtools-for-tabs"],
      "webRoot": "${workspaceRoot}/src"
    }
  ]
}

The important line is "runtimeArgs": ["--auto-open-devtools-for-tabs"],

From vscode you can now type F5, Chrome opens your app and the console tab as well.

Convert array values from string to int?

If you have a multi-dimensional array, none of the previously mentioned solutions will work. Here is my solution:

public function arrayValuesToInt(&$array){
  if(is_array($array)){
    foreach($array as &$arrayPiece){
      arrayValuesToInt($arrayPiece);
    }
  }else{
    $array = intval($array);
  }
}

Then, just do this:

arrayValuesToInt($multiDimentionalArray);

This will make an array like this:

[["1","2"]["3","4"]]

look like this:

[[1,2][3,4]]

This will work with any level of depth.

Alternatively, you can use array_walk_recursive() for a shorter answer:

array_walk_recursive($array, function(&$value){
    $value = intval($value);
});

How to set textColor of UILabel in Swift

Made an app with two labels in IB and the following:

@IBOutlet var label1: UILabel!
@IBOutlet var label2: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    label1.textColor = UIColor.redColor() // in Swift 3 it's UIColor.red
    label2.textColor = label1.textColor
}

label2 color changed as expected, so your line works. Try println(otherLabel.textColor) right before you set myLabel.textColor to see if the color's what you expect.

Determine if running on a rooted device

In my application I was checking if device is rooted or not by executing "su" command. But today I've removed this part of my code. Why?

Because my application became a memory killer. How? Let me tell you my story.

There were some complaints that my application was slowing down devices(Of course I thought that can not be true). I tried to figure out why. So I used MAT to get heap dumps and analyze, and everything seemed perfect. But after relaunching my app many times I realized that device is really getting slower and stopping my application didn't make it faster (unless I restart device). I analyzed dump files again while device is very slow. But everything was still perfect for dump file. Then I did what must be done at first. I listed processes.

$ adb shell ps

Surprize; there were many processes for my application (with my application's process tag at manifest). Some of them was zombie some of them not.

With a sample application which has a single Activity and executes just "su" command, I realized that a zombie process is being created on every launch of application. At first these zombies allocate 0KB but than something happens and zombie processes are holding nearly same KBs as my application's main process and they became standart processes.

There is a bug report for same issue on bugs.sun.com: http://bugs.sun.com/view_bug.do?bug_id=6474073 this explains if command is not found zombies are going to be created with exec() method. But I still don't understand why and how can they become standart processes and hold significant KBs. (This is not happening all the time)

You can try if you want with code sample below;

String commandToExecute = "su";
executeShellCommand(commandToExecute);

Simple command execution method;

private boolean executeShellCommand(String command){
    Process process = null;            
    try{
        process = Runtime.getRuntime().exec(command);
        return true;
    } catch (Exception e) {
        return false;
    } finally{
        if(process != null){
            try{
                process.destroy();
            }catch (Exception e) {
            }
        }
    }
}

To sum up; I have no advice for you to determine if device is rooted or not. But if I were you I would not use Runtime.getRuntime().exec().

By the way; RootTools.isRootAvailable() causes same problem.

How do I clear/delete the current line in terminal?

Alt+# comments out the current line. It will be available in history if needed.

How to use order by with union all in sql?

Select 'Shambhu' as ShambhuNewsFeed,Note as [News Fedd],NotificationId
from Notification with(nolock) where DesignationId=@Designation 
Union All 
Select 'Shambhu' as ShambhuNewsFeed,Note as [Notification],NotificationId
from Notification with(nolock) 
where DesignationId=@Designation 
order by NotificationId desc

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

Why should hash functions use a prime number modulus?

The first thing you do when inserting/retreiving from hash table is to calculate the hashCode for the given key and then find the correct bucket by trimming the hashCode to the size of the hashTable by doing hashCode % table_length. Here are 2 'statements' that you most probably have read somewhere

  1. If you use a power of 2 for table_length, finding (hashCode(key) % 2^n ) is as simple and quick as (hashCode(key) & (2^n -1)). But if your function to calculate hashCode for a given key isn't good, you will definitely suffer from clustering of many keys in a few hash buckets.
  2. But if you use prime numbers for table_length, hashCodes calculated could map into the different hash buckets even if you have a slightly stupid hashCode function.

And here is the proof.

If suppose your hashCode function results in the following hashCodes among others {x , 2x, 3x, 4x, 5x, 6x...}, then all these are going to be clustered in just m number of buckets, where m = table_length/GreatestCommonFactor(table_length, x). (It is trivial to verify/derive this). Now you can do one of the following to avoid clustering

Make sure that you don't generate too many hashCodes that are multiples of another hashCode like in {x, 2x, 3x, 4x, 5x, 6x...}.But this may be kind of difficult if your hashTable is supposed to have millions of entries. Or simply make m equal to the table_length by making GreatestCommonFactor(table_length, x) equal to 1, i.e by making table_length coprime with x. And if x can be just about any number then make sure that table_length is a prime number.

From - http://srinvis.blogspot.com/2006/07/hash-table-lengths-and-prime-numbers.html

Center content vertically on Vuetify

Still surprised that no one proposed the shortest solution with align-center justify-center to center content vertically and horizontally. Check this CodeSandbox and code below:

<v-container fluid fill-height>
  <v-layout align-center justify-center>
    <v-flex>
      <!-- Some HTML elements... -->
    </v-flex>
  </v-layout>
</v-container>

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

Best practice to return errors in ASP.NET Web API

ASP.NET Web API 2 really simplified it. For example, the following code:

public HttpResponseMessage GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        var message = string.Format("Product with id = {0} not found", id);
        HttpError err = new HttpError(message);
        return Request.CreateResponse(HttpStatusCode.NotFound, err);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OK, item);
    }
}

returns the following content to the browser when the item is not found:

HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Aug 2012 23:27:18 GMT
Content-Length: 51

{
  "Message": "Product with id = 12 not found"
}

Suggestion: Don't throw HTTP Error 500 unless there is a catastrophic error (for example, WCF Fault Exception). Pick an appropriate HTTP status code that represents the state of your data. (See the apigee link below.)

Links:

C# if/then directives for debug vs release

Slightly modified (bastardized?) version of the answer by Tod Thomson as a static function rather than a separate class (I wanted to be able to call it in a WebForm viewbinding from a viewutils class I already had included).

public static bool isDebugging() {
    bool debugging = false;

    WellAreWe(ref debugging);

    return debugging;
}

[Conditional("DEBUG")]
private static void WellAreWe(ref bool debugging)
{
    debugging = true;
}

Get Folder Size from Windows Command Line

I guess this would only work if the directory is fairly static and its contents don't change between the execution of the two dir commands. Maybe a way to combine this into one command to avoid that, but this worked for my purpose (I didn't want the full listing; just the summary).

GetDirSummary.bat Script:

@echo off
rem  get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem  dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem  now output just the last 3 lines
dir /S %1 | more +%summaryStart%

Usage:

GetDirSummary.bat c:\temp

Output:

 Total Files Listed:
          22 File(s)         63,600 bytes
           8 Dir(s)  104,350,330,880 bytes free

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to prevent scanf causing a buffer overflow in C?

Limiting the length of the input is definitely easier. You could accept an arbitrarily-long input by using a loop, reading in a bit at a time, re-allocating space for the string as necessary...

But that's a lot of work, so most C programmers just chop off the input at some arbitrary length. I suppose you know this already, but using fgets() isn't going to allow you to accept arbitrary amounts of text - you're still going to need to set a limit.

Error ITMS-90717: "Invalid App Store Icon"

changed the icon from .png format to .jpg and everything went well.

C# catch a stack overflow exception

Yes from CLR 2.0 stack overflow is considered a non-recoverable situation. So the runtime still shut down the process.

For details please see the documentation http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

When use ResponseEntity<T> and @RestController for Spring RESTful applications

According to official documentation: Creating REST Controllers with the @RestController annotation

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

It seems that it's best to use @RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

For example:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    @ResponseStatus(HttpStatus.OK)
    public User test() {
        User user = new User();
        user.setName("Name 1");

        return user;
    }

}

is the same as:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    public ResponseEntity<User> test() {
        User user = new User();
        user.setName("Name 1");

        HttpHeaders responseHeaders = new HttpHeaders();
        // ...
        return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
    }

}

This way, you can define ResponseEntity only when needed.

Update

You can use this:

    return ResponseEntity.ok().headers(responseHeaders).body(user);

explode string in jquery

if your input's id is following

<input type='text'  id='kg_row1' >

then you can get explode/split the above with the following function of split in jquery

  var kg_id = $(this).attr("id");
  var getvalues =kg_id.split("_");
  var id = getvalues[1];

CSS table-cell equal width

HTML

<div class="table">
    <div class="table_cell">Cell-1</div>
    <div class="table_cell">Cell-2 Cell-2 Cell-2 Cell-2Cell-2 Cell-2</div>
    <div class="table_cell">Cell-3Cell-3 Cell-3Cell-3 Cell-3Cell-3</div>
    <div class="table_cell">Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4Cell-4</div>
</div>?

CSS

.table{
    display:table;
    width:100%;
    table-layout:fixed;
}
.table_cell{
    display:table-cell;
    width:100px;
    border:solid black 1px;
}

DEMO.

Relation between CommonJS, AMD and RequireJS?

RequireJS implements the AMD API (source).

CommonJS is a way of defining modules with the help of an exports object, that defines the module contents. Simply put, a CommonJS implementation might work like this:

// someModule.js
exports.doSomething = function() { return "foo"; };

//otherModule.js
var someModule = require('someModule'); // in the vein of node    
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };

Basically, CommonJS specifies that you need to have a require() function to fetch dependencies, an exports variable to export module contents and a module identifier (which describes the location of the module in question in relation to this module) that is used to require the dependencies (source). CommonJS has various implementations, including Node.js, which you mentioned.

CommonJS was not particularly designed with browsers in mind, so it doesn't fit in the browser environment very well (I really have no source for this--it just says so everywhere, including the RequireJS site.) Apparently, this has something to do with asynchronous loading, etc.

On the other hand, RequireJS implements AMD, which is designed to suit the browser environment (source). Apparently, AMD started as a spinoff of the CommonJS Transport format and evolved into its own module definition API. Hence the similarities between the two. The new feature in AMD is the define() function that allows the module to declare its dependencies before being loaded. For example, the definition could be:

define('module/id/string', ['module', 'dependency', 'array'], 
function(module, factory function) {
  return ModuleContents;  
});

So, CommonJS and AMD are JavaScript module definition APIs that have different implementations, but both come from the same origins.

  • AMD is more suited for the browser, because it supports asynchronous loading of module dependencies.
  • RequireJS is an implementation of AMD, while at the same time trying to keep the spirit of CommonJS (mainly in the module identifiers).

To confuse you even more, RequireJS, while being an AMD implementation, offers a CommonJS wrapper so CommonJS modules can almost directly be imported for use with RequireJS.

define(function(require, exports, module) {
  var someModule = require('someModule'); // in the vein of node    
  exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
});

I hope this helps to clarify things!

subsetting a Python DataFrame

Just for someone looking for a solution more similar to R:

df[(df.Product == p_id) & (df.Time> start_time) & (df.Time < end_time)][['Time','Product']]

No need for data.loc or query, but I do think it is a bit long.

What does "var" mean in C#?

  • As the name suggested, var is variable without any data type.
  • If you don't know which type of data will be returned by any method, such cases are good for using var.
  • var is Implicit type which means system will define the data type itself. The compiler will infer its type based on the value to the right of the "=" operator.
  • int/string etc. are the explicit types as it is defined by you explicitly.
  • Var can only be defined in a method as a local variable
  • Multiple vars cannot be declared and initialized in a single statement. For example, var i=1, j=2; is invalid.
int i = 100;// explicitly typed 
var j = 100; // implicitly typed

How can I center text (horizontally and vertically) inside a div block?

Common techniques as of 2014:


  • Approach 1 - transform translateX/translateY:

    Example Here / Full Screen Example

    In supported browsers (most of them), you can use top: 50%/left: 50% in combination with translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.

    .container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
    }
    

  • Approach 2 - Flexbox method:

    Example Here / Full Screen Example

    In supported browsers, set the display of the targeted element to flex and use align-items: center for vertical centering and justify-content: center for horizontal centering. Just don't forget to add vendor prefixes for additional browser support (see example).

    html, body, .container {
        height: 100%;
    }
    .container {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    

  • Approach 3 - table-cell/vertical-align: middle:

    Example Here / Full Screen Example

    In some cases, you will need to ensure that the html/body element's height is set to 100%.

    For vertical alignment, set the parent element's width/height to 100% and add display: table. Then for the child element, change the display to table-cell and add vertical-align: middle.

    For horizontal centering, you could either add text-align: center to center the text and any other inline children elements. Alternatively, you could use margin: 0 auto assuming the element is block level.

    html, body {
        height: 100%;
    }
    .parent {
        width: 100%;
        height: 100%;
        display: table;
        text-align: center;
    }
    .parent > .child {
        display: table-cell;
        vertical-align: middle;
    }
    

  • Approach 4 - Absolutely positioned 50% from the top with displacement:

    Example Here / Full Screen Example

    This approach assumes that the text has a known height - in this instance, 18px. Just absolutely position the element 50% from the top, relative to the parent element. Use a negative margin-top value that is half of the element's known height, in this case - -9px.

    html, body, .container {
        height: 100%;
    }
    .container {
        position: relative;
        text-align: center;
    }
    .container > p {
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        margin-top: -9px;
    }
    

  • Approach 5 - The line-height method (Least flexible - not suggested):

    Example Here

    In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a line-height value on the child element equal to the fixed height of the parent element.

    Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this.

    .parent {
        height: 200px;
        width: 400px;
        text-align: center;
    }
    .parent > .child {
        line-height: 200px;
    }
    

Methods 4 and 5 aren't the most reliable. Go with one of the first 3.

How can I play sound in Java?

I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).

private static void playSound(String sound){
    // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
    URL file = cl.getResource(sound);
    final Media media = new Media(file.toString());
    final MediaPlayer mediaPlayer = new MediaPlayer(media);
    mediaPlayer.play();
}

Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :

static{
    JFXPanel fxPanel = new JFXPanel();
}

How to merge remote master to local branch

From your feature branch (e.g configUpdate) run:

git fetch
git rebase origin/master

Or the shorter form:

git pull --rebase

Why this works:

  • git merge branchname takes new commits from the branch branchname, and adds them to the current branch. If necessary, it automatically adds a "Merge" commit on top.

  • git rebase branchname takes new commits from the branch branchname, and inserts them "under" your changes. More precisely, it modifies the history of the current branch such that it is based on the tip of branchname, with any changes you made on top of that.

  • git pull is basically the same as git fetch; git merge origin/master.

  • git pull --rebase is basically the same as git fetch; git rebase origin/master.

So why would you want to use git pull --rebase rather than git pull? Here's a simple example:

  • You start working on a new feature.

  • By the time you're ready to push your changes, several commits have been pushed by other developers.

  • If you git pull (which uses merge), your changes will be buried by the new commits, in addition to an automatically-created merge commit.

  • If you git pull --rebase instead, git will fast forward your master to upstream's, then apply your changes on top.

Cut Corners using CSS

Another idea using mask and CSS variables to have better control over the whole shape. It's reponsive, transparent and allow any kind of background:

_x000D_
_x000D_
.box {
  --all:0px;
  width:200px;
  height:150px;
  display:inline-block;
  margin:10px;
  background:red;
  -webkit-mask:
     linear-gradient(  45deg, transparent 0 var(--bottom-left,var(--all)) ,#fff 0) bottom left,
     linear-gradient( -45deg, transparent 0 var(--bottom-right,var(--all)),#fff 0) bottom right,
     linear-gradient( 135deg, transparent 0 var(--top-left,var(--all))    ,#fff 0) top left,
     linear-gradient(-135deg, transparent 0 var(--top-right,var(--all))   ,#fff 0) top right;
   -webkit-mask-size:50.5% 50.5%;
   -webkit-mask-repeat:no-repeat;
}


body {
  background:grey;
}
_x000D_
<div class="box" style="--top-left:20px"></div>
<div class="box" style="--top-right:20px;--bottom-right:50px;background:radial-gradient(red,yellow)"></div>
<div class="box" style="--all:30px;background:url(https://picsum.photos/id/104/200/200)"></div>
<div class="box" style="--all:30px;--bottom-right:0px;background:linear-gradient(red,blue)"></div>
<div class="box" style="--all:50%;width:150px;background:green"></div>
<div class="box" style="--all:12%;width:150px;background:repeating-linear-gradient(45deg,#000 0 10px,#fff 0 20px)"></div>
_x000D_
_x000D_
_x000D_

CSS cut corner div using mask

And below in case you want to consider border:

_x000D_
_x000D_
.box {
  --all:0px;
  --b:pink;
  
  width:200px;
  height:150px;
  display:inline-block;
  margin:10px;
  border:5px solid var(--b);
  background:
     linear-gradient(  45deg, var(--b) 0 calc(var(--bottom-left,var(--all)) + 5px) ,transparent 0) bottom left /50% 50%,
     linear-gradient( -45deg, var(--b) 0 calc(var(--bottom-right,var(--all)) + 5px),transparent 0) bottom right/50% 50%,
     linear-gradient( 135deg, var(--b) 0 calc(var(--top-left,var(--all)) + 5px)    ,transparent 0) top left    /50% 50%,
     linear-gradient(-135deg, var(--b) 0 calc(var(--top-right,var(--all)) + 5px)   ,transparent 0) top right   /50% 50%,
     var(--img,red);
  background-origin:border-box;
  background-repeat:no-repeat;
  -webkit-mask:
     linear-gradient(  45deg, transparent 0 var(--bottom-left,var(--all)) ,#fff 0) bottom left,
     linear-gradient( -45deg, transparent 0 var(--bottom-right,var(--all)),#fff 0) bottom right,
     linear-gradient( 135deg, transparent 0 var(--top-left,var(--all))    ,#fff 0) top left,
     linear-gradient(-135deg, transparent 0 var(--top-right,var(--all))   ,#fff 0) top right;
   -webkit-mask-size:50.5% 50.5%;
   -webkit-mask-repeat:no-repeat;
}


body {
  background:grey;
}
_x000D_
<div class="box" style="--top-left:20px"></div>
<div class="box" style="--top-right:20px;--bottom-right:50px;--img:radial-gradient(red,yellow);--b:white;"></div>
<div class="box" style="--all:30px;--img:url(https://picsum.photos/id/104/200/200) center/cover;--b:orange;"></div>
<div class="box" style="--all:30px;--bottom-right:0px;--img:linear-gradient(red,blue)"></div>
<div class="box" style="--all:50%;width:150px;--img:green;--b:red;"></div>
<div class="box" style="--all:12%;width:150px;--img:repeating-linear-gradient(45deg,#000 0 10px,#fff 0 20px)"></div>
_x000D_
_x000D_
_x000D_

CSS cut corner with border and gradient

Let's also add some radius:

_x000D_
_x000D_
.box {
  --all:0px;
  --b:pink;
  
  width:200px;
  height:150px;
  display:inline-block;
  margin:10px;
  filter:url(#round);
}
.box::before {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:var(--img,red);
  -webkit-mask:
     linear-gradient(  45deg, transparent 0 var(--bottom-left,var(--all)) ,#fff 0) bottom left,
     linear-gradient( -45deg, transparent 0 var(--bottom-right,var(--all)),#fff 0) bottom right,
     linear-gradient( 135deg, transparent 0 var(--top-left,var(--all))    ,#fff 0) top left,
     linear-gradient(-135deg, transparent 0 var(--top-right,var(--all))   ,#fff 0) top right;
   -webkit-mask-size:50.5% 50.5%;
   -webkit-mask-repeat:no-repeat;
}

body {
  background:grey;
}
_x000D_
<div class="box" style="--top-left:20px"></div>
<div class="box" style="--top-right:20px;--bottom-right:50px;--img:radial-gradient(red,yellow);--b:white;"></div>
<div class="box" style="--all:30px;--img:url(https://picsum.photos/id/104/200/200) center/cover;--b:orange;"></div>
<div class="box" style="--all:30px;--bottom-right:0px;--img:linear-gradient(red,blue)"></div>
<div class="box" style="--all:50%;width:150px;--img:green;--b:red;"></div>
<div class="box" style="--all:12%;width:150px;--img:repeating-linear-gradient(45deg,#000 0 10px,#fff 0 20px)"></div>

<svg style="visibility: hidden; position: absolute;" width="0" height="0" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
        <filter id="round">
            <feGaussianBlur in="SourceGraphic" stdDeviation="5" result="blur" />    
            <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 19 -9" result="goo" />
            <feComposite in="SourceGraphic" in2="goo" operator="atop"/>
        </filter>
    </defs>
</svg>
_x000D_
_x000D_
_x000D_

Rounded cutted corner CSS

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

Include PHP inside JavaScript (.js) files

Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

The problem is that you mapped your servlet to /register.html and it expects POST method, because you implemented only doPost() method. So when you open register.html page, it will not open html page with the form but servlet that handles the form data.

Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).

To fix:

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

You should also try checking the error messages in curl_error(). You might need to do this once after each curl_* function.

http://www.php.net/curl_error

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

How can I check if my Element ID has focus?

Use document.activeElement

Should work.

P.S getElementById("myID") not getElementById("#myID")

Where should I put the CSS and Javascript code in an HTML webpage?

You should put CSS in the <head> because that's what the specification says do to.

If you have more than one CSS file, they will be loaded in the order you put them in the code. If there is style in the second CSS file, it overwrites the style in the first; That will happen by design. Thus, Cascading Style Sheets.

Most browser will still effectivly render CSS files out of the head, but your code is not semantically correct.

You can use JavaScript file links anywhere on the document. There are different reasons to use some in the <head> and some elsewhere on the page. (For example, Google analytic code is instructed to be put at the bottom.)

CMake is not able to find BOOST libraries

Try to complete cmake process with following libs:

sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev

Export specific rows from a PostgreSQL table as INSERT SQL script

For my use-case I was able to simply pipe to grep.

pg_dump -U user_name --data-only --column-inserts -t nyummy.cimory | grep "tokyo" > tokyo.sql

Split array into chunks

Hi try this -

 function split(arr, howMany) {
        var newArr = []; start = 0; end = howMany;
        for(var i=1; i<= Math.ceil(arr.length / howMany); i++) {
            newArr.push(arr.slice(start, end));
            start = start + howMany;
            end = end + howMany
        }
        console.log(newArr)
    }
    split([1,2,3,4,55,6,7,8,8,9],3)

Make a DIV fill an entire table cell

you can do it like that:

<td>
  <div style="width: 100%; position: relative; float: left;">inner div</div>
</td>

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

How do I convert NSInteger to NSString datatype?

%zd works for NSIntegers (%tu for NSUInteger) with no casts and no warnings on both 32-bit and 64-bit architectures. I have no idea why this is not the "recommended way".

NSString *string = [NSString stringWithFormat:@"%zd", month];

If you're interested in why this works see this question.

JQuery get all elements by class name

One possible way is to use .map() method:

var all = $(".mbox").map(function() {
    return this.innerHTML;
}).get();

console.log(all.join());

DEMO: http://jsfiddle.net/Y4bHh/

N.B. Please don't use document.write. For testing purposes console.log is the best way to go.

How do I copy a 2 Dimensional array in Java?

current = old ;

Assignment operations doesnot copy elements of one array to another. You are just making the current matrix refer to the old matrix. You need to do a member wise copy.

How to check if a string "StartsWith" another string?

data.substring(0, input.length) === input

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I have try with the SCFRench and with the Ru Hasha on octave.

And finally it works: but I have done some modification

function message = makefuns
    assignin('base','fun1', @fun1);   % Ru Hasha
    assignin('base', 'fun2', @fun2);  % Ru Hasha
    message.fun1=@fun1;               % SCFrench
    message.fun2=@fun2;               % SCFrench
end

function y=fun1(x)
    y=x;
end

function z=fun2
    z=1;
end

Can be called in other 'm' file:

printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());

update:

I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).

What are public, private and protected in object oriented programming?

as above, but qualitatively:

private - least access, best encapsulation
protected - some access, moderate encapsulation
public - full access, no encapsulation

the less access you provide the fewer implementation details leak out of your objects. less of this sort of leakage means more flexibility (aka "looser coupling") in terms of changing how an object is implemented without breaking clients of the object. this is a truly fundamental thing to understand.