Programs & Examples On #Pyqt4

PyQt is a set of Python bindings for Digia's Qt application framework and runs on all platforms supported by Qt including Windows, MacOS/X and Linux.

How to install PyQt4 in anaconda?

Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:

conda install pyqt=4

This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example

conda install pyqt=4.11

would install the latest (or last) release of version 4.11.

Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.

How to install PyQt4 on Windows using pip?

Here are Windows wheel packages built by Chris Golke - Python Windows Binary packages - PyQt

In the filenames cp27 means C-python version 2.7, cp35 means python 3.5, etc.

Since Qt is a more complicated system with a compiled C++ codebase underlying the python interface it provides you, it can be more complex to build than just a pure python code package, which means it can be hard to install it from source.

Make sure you grab the correct Windows wheel file (python version, 32/64 bit), and then use pip to install it - e.g:

C:\path\where\wheel\is\> pip install PyQt4-4.11.4-cp35-none-win_amd64.whl

Should properly install if you are running an x64 build of Python 3.5.

ImportError: No module named PyQt4

I solved the same problem for my own program by installing python3-pyqt4.

I'm not using Python 3 but it still helped.

How to get text in QlineEdit when QpushButton is pressed in a string?

Acepted solution implemented in PyQt5

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        self.pb.clicked.connect(self.button_click)

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)

        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print (shost)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

How do you get the current text contents of a QComboBox?

If you want the text value of a QString object you can use the __str__ property, like this:

>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'

Hope that helps.

Background thread with QThread in PyQt

Very nice example from Matt, I fixed the typo and also pyqt4.8 is common now so I removed the dummy class as well and added an example for the dataReady signal

# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt


# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    dataReady = QtCore.pyqtSignal(list, dict)

    @QtCore.pyqtSlot()
    def processA(self):
        print "Worker.processA()"
        self.finished.emit()

    @QtCore.pyqtSlot(str, list, list)
    def processB(self, foo, bar=None, baz=None):
        print "Worker.processB()"
        for thing in bar:
            # lots of processing...
            self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
        self.finished.emit()


def onDataReady(aList, aDict):
    print 'onDataReady'
    print repr(aList)
    print repr(aDict)


app = QtGui.QApplication(sys.argv)

thread = QtCore.QThread()  # no parent!
obj = Worker()  # no parent!
obj.dataReady.connect(onDataReady)

obj.moveToThread(thread)

# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)

# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread.  As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.finished.connect(app.exit)

thread.start()

# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
                                QtCore.Q_ARG(str, "Hello World!"),
                                QtCore.Q_ARG(list, ["args", 0, 1]),
                                QtCore.Q_ARG(list, []))

# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls.  Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking

app.exec_()

How to embed matplotlib in pyqt - for Dummies

Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...


import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

import random

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        # ax.hold(False) # deprecated, see above

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

What is the proper use of an EventEmitter?

There is no: nono and no: yesyes. The truth is in the middle And no reasons to be scared because of the next version of Angular.

From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.

I know..Maybe I'm a bit an old fashioned developer. But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.

Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly. You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.

git-diff to ignore ^M

Is there an option like "treat ^M as newline when diffing" ?

There will be one with Git 2.16 (Q1 2018), as the "diff" family of commands learned to ignore differences in carriage return at the end of line.

See commit e9282f0 (26 Oct 2017) by Junio C Hamano (gitster).
Helped-by: Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 10f65c2, 27 Nov 2017)

diff: --ignore-cr-at-eol

A new option --ignore-cr-at-eol tells the diff machinery to treat a carriage-return at the end of a (complete) line as if it does not exist.

Just like other "--ignore-*" options to ignore various kinds of whitespace differences, this will help reviewing the real changes you made without getting distracted by spurious CRLF<->LF conversion made by your editor program.

How do I remove the space between inline/inline-block elements?

There are lots of solutions like font-size:0,word-spacing,margin-left,letter-spacing and so on.

Normally I prefer using letter-spacing because

  1. it seems ok when we assign a value which is bigger than the width of extra space(e.g. -1em).
  2. However, it won't be okay with word-spacing and margin-left when we set bigger value like -1em.
  3. Using font-size is not convenient when we try to using em as font-size unit.

So, letter-spacing seems to be the best choice.

However, I have to warn you

when you using letter-spacing you had better using -0.3em or -0.31em not others.

_x000D_
_x000D_
* {
  margin: 0;
  padding: 0;
}
a {
  text-decoration: none;
  color: inherit;
  cursor: auto;
}
.nav {
  width: 260px;
  height: 100px;
  background-color: pink;
  color: white;
  font-size: 20px;
  letter-spacing: -1em;
}
.nav__text {
  width: 90px;
  height: 40px;
  box-sizing: border-box;
  border: 1px solid black;
  line-height: 40px;
  background-color: yellowgreen;
  text-align: center;
  display: inline-block;
  letter-spacing: normal;
}
_x000D_
<nav class="nav">
    <span class="nav__text">nav1</span>
    <span class="nav__text">nav2</span>
    <span class="nav__text">nav3</span>
</nav>
_x000D_
_x000D_
_x000D_

If you are using Chrome(test version 66.0.3359.139) or Opera(test version 53.0.2907.99), what you see might be:

enter image description here

If you are using Firefox(60.0.2),IE10 or Edge, what you see might be:

enter image description here

That's interesting. So, I checked the mdn-letter-spacing and found this:

length

Specifies extra inter-character space in addition to the default space between characters. Values may be negative, but there may be implementation-specific limits. User agents may not further increase or decrease the inter-character space in order to justify text.

It seems that this is the reason.

How to convert a String to Bytearray

In C# running this

UnicodeEncoding encoding = new UnicodeEncoding();
byte[] bytes = encoding.GetBytes("Hello");

Will create an array with

72,0,101,0,108,0,108,0,111,0

byte array

For a character which the code is greater than 255 it will look like this

byte array

If you want a very similar behavior in JavaScript you can do this (v2 is a bit more robust solution, while the original version will only work for 0x00 ~ 0xff)

_x000D_
_x000D_
var str = "Hello?";_x000D_
var bytes = []; // char codes_x000D_
var bytesv2 = []; // char codes_x000D_
_x000D_
for (var i = 0; i < str.length; ++i) {_x000D_
  var code = str.charCodeAt(i);_x000D_
  _x000D_
  bytes = bytes.concat([code]);_x000D_
  _x000D_
  bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);_x000D_
}_x000D_
_x000D_
// 72, 101, 108, 108, 111, 31452_x000D_
console.log('bytes', bytes.join(', '));_x000D_
_x000D_
// 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 220, 122_x000D_
console.log('bytesv2', bytesv2.join(', '));
_x000D_
_x000D_
_x000D_

Use a loop to plot n charts Python

Here are two examples of how to generate graphs in separate windows (frames), and, an example of how to generate graphs and save them into separate graphics files.

Okay, first the on-screen example. Notice that we use a separate instance of plt.figure(), for each graph, with plt.plot(). At the end, we have to call plt.show() to put it all on the screen.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace( 0,10 )

for n in range(3):
    y = np.sin( x+n )
    plt.figure()
    plt.plot( x, y )

plt.show()

Another way to do this, is to use plt.show(block=False) inside the loop:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace( 0,10 )

for n in range(3):
    y = np.sin( x+n )
    plt.figure()
    plt.plot( x, y )
    plt.show( block=False )

Now, let's generate the graphs and instead, write them each to a file. Here we replace plt.show(), with plt.savefig( filename ). The difference from the previous example is that we don't have to account for ''blocking'' at each graph. Note also, that we number the file names. Here we use %03d so that we can conveniently have them in number order afterwards.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace( 0,10 )

for n in range(3):
    y = np.sin( x+n )
    plt.figure()
    plt.plot( x, y )
    plt.savefig('myfilename%03d.png'%(n))

Why is sed not recognizing \t as a tab?

Instead of BSD sed, i use perl:

ct@MBA45:~$ python -c "print('\t\t\thi')" |perl -0777pe "s/\t/ /g"
   hi

remove table row with specific id

ID attributes cannot start with a number and they should be unique. In any case, you can use :eq() to select a specific row using a 0-based integer:

// Remove the third row
$("#test tr:eq(2)").remove();

Alternatively, rewrite your HTML so that it's valid:

<table id="test">
 <tr id=test1><td>bla</td></tr>
 <tr id=test2><td>bla</td></tr>
 <tr id=test3><td>bla</td></tr>
 <tr id=test4><td>bla</td></tr>
</table>

And remove it referencing just the id:

$("#test3").remove();

How to add a TextView to a LinearLayout dynamically in Android?

I customized more @Suragch code. My output looks

enter image description here

I wrote a method to stop code redundancy.

public TextView createATextView(int layout_widh, int layout_height, int align,
        String text, int fontSize, int margin, int padding) {

    TextView textView_item_name = new TextView(this);

    // LayoutParams layoutParams = new LayoutParams(
    // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    // layoutParams.gravity = Gravity.LEFT;
    RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
            layout_widh, layout_height);

    _params.setMargins(margin, margin, margin, margin);
    _params.addRule(align);
    textView_item_name.setLayoutParams(_params);

    textView_item_name.setText(text);
    textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
    textView_item_name.setTextColor(Color.parseColor("#000000"));
    // textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView_item_name.setPadding(padding, padding, padding, padding);

    return textView_item_name;

}

It can be called like

createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20);

Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.

    RelativeLayout primary_layout = new RelativeLayout(this);

    LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);

    primary_layout.setLayoutParams(layoutParam);

    // FOR LINEAR LAYOUT SET ORIENTATION
    // primary_layout.setOrientation(LinearLayout.HORIZONTAL);

    // FOR BACKGROUND COLOR 
    primary_layout.setBackgroundColor(0xff99ccff);

    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
            20, 10, 20));
    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20));

how to convert current date to YYYY-MM-DD format with angular 2

Example as per doc

@Component({
  selector: 'date-pipe',
  template: `<div>
    <p>Today is {{today | date}}</p>
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
    <p>The time is {{today | date:'jmZ'}}</p>
  </div>`
})
export class DatePipeComponent {
  today: number = Date.now();
}

Template

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mmss' }}        // output is '43:11'
{{dateObj  | date: 'dd/MM/yyyy'}} // 15/06/2015

To Use in your component.

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need. 
  }
}

In your app.module.ts

providers: [DatePipe,...] 

all you have to do is use this service now.

How to wrap text using CSS?

The better option if you cannot control user input, it is to establish the css property, overflow:hidden, so if the string is superior to the width, it will not deform the design.

Edited:

I like the answer: "word-wrap: break-word", and for those browsers that do not support it, for example, IE6 or IE7, I would use my solution.

sscanf in Python

There is an example in the official python docs about how to use sscanf from libc:

    # import libc
    from ctypes import CDLL
    if(os.name=="nt"):
        libc = cdll.msvcrt 
    else:
        # assuming Unix-like environment
        libc = cdll.LoadLibrary("libc.so.6")
        libc = CDLL("libc.so.6")  # alternative

    # allocate vars
    i = c_int()
    f = c_float()
    s = create_string_buffer(b'\000' * 32)

    # parse with sscanf
    libc.sscanf(b"1 3.14 Hello", "%d %f %s", byref(i), byref(f), s)

    # read the parsed values
    i.value  # 1
    f.value  # 3.14
    s.value # b'Hello'

Converting a PDF to PNG

To convert pdf to image files use following commands:

For PNG gs -sDEVICE=png16m -dTextAlphaBits=4 -r300 -o a.png a.pdf

For JPG gs -sDEVICE=jpeg -dTextAlphaBits=4 -r300 -o a.jpg a.pdf

If you have multiple pages add to name %03d gs -o a%03d.jpg a.pdf

What each option means:

  • sDEVICE={jpeg,pngalpha,png16m...} - filetype
  • -o - output file (%stdout to stdout)
  • -dTextAlphaBits=4 - font antialiasing.
  • -r300 - 300 dpi

CSS to prevent child element from inheriting parent styles

Can't you style the forms themselves? Then, style the divs accordingly.

form
{
    /* styles */
}

You can always overrule inherited styles by making it important:

form
{
    /* styles */ !important
}

Returning an array using C

How about this deliciously evil implementation?

array.h

#define IMPORT_ARRAY(TYPE)    \
    \
struct TYPE##Array {    \
    TYPE* contents;    \
    size_t size;    \
};    \
    \
struct TYPE##Array new_##TYPE##Array() {    \
    struct TYPE##Array a;    \
    a.contents = NULL;    \
    a.size = 0;    \
    return a;    \
}    \
    \
void array_add(struct TYPE##Array* o, TYPE value) {    \
    TYPE* a = malloc((o->size + 1) * sizeof(TYPE));    \
    TYPE i;    \
    for(i = 0; i < o->size; ++i) {    \
        a[i] = o->contents[i];    \
    }    \
    ++(o->size);    \
    a[o->size - 1] = value;    \
    free(o->contents);    \
    o->contents = a;    \
}    \
void array_destroy(struct TYPE##Array* o) {    \
    free(o->contents);    \
}    \
TYPE* array_begin(struct TYPE##Array* o) {    \
    return o->contents;    \
}    \
TYPE* array_end(struct TYPE##Array* o) {    \
    return o->contents + o->size;    \
}

main.c

#include <stdlib.h>
#include "array.h"

IMPORT_ARRAY(int);

struct intArray return_an_array() {
    struct intArray a;
    a = new_intArray();
    array_add(&a, 1);
    array_add(&a, 2);
    array_add(&a, 3);
    return a;
}

int main() {
    struct intArray a;
    int* it;
    int* begin;
    int* end;
    a = return_an_array();
    begin = array_begin(&a);
    end = array_end(&a);
    for(it = begin; it != end; ++it) {
        printf("%d ", *it);
    }
    array_destroy(&a);
    getchar();
    return 0;
}

Build not visible in itunes connect

This was My Mistake:

I had a minor update in a Push Notification content part and I did not even touch my code.

But I thought I might have to re-upload it in order to reflect that change in the latest version.

And I did.

Tried to upload 3 Builds One by One.

But Not a single build has shown in the Test Flight Version.(Shocked)

Later I realized my mistake that just by updating APNS content part without even touching my code, I was trying to upload a new build and was expecting to reflect it in the Test Flight. (So stupid of me)

How to push a docker image to a private repository

Create repository on dockerhub :

$docker tag IMAGE_ID UsernameOnDockerhub/repoNameOnDockerhub:latest

$docker push UsernameOnDockerhub/repoNameOnDockerhub:latest

Note : here "repoNameOnDockerhub" : repository with the name you are mentioning has to be present on dockerhub

"latest" : is just tag

Add error bars to show standard deviation on a plot in R

A solution with ggplot2 :

qplot(x,y)+geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.25)

enter image description here

Is try-catch like error handling possible in ASP Classic?

Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.

If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.

If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.

Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.

Change marker size in Google maps V3

The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:

new google.maps.Size(42,68)

I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

.attr('checked','checked') does not work

Why not try IS?

$('selector').is(':checked') /* result true or false */

Look a FAQ: jQuery .is() enjoin us ;-)

Convert Map<String,Object> to Map<String,String>

Not possible.

This a little counter-intuitive.

You're encountering the "Apple is-a fruit" but "Every Fruit is not an Apple"

Go for creating a new map and checking with instance of with String

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even

SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;

Converting String to "Character" array in Java

This method take String as a argument and return the Character Array

/**
 * @param sourceString
 *            :String as argument
 * @return CharcterArray
 */
public static Character[] toCharacterArray(String sourceString) {
    char[] charArrays = new char[sourceString.length()];
    charArrays = sourceString.toCharArray();
    Character[] characterArray = new Character[charArrays.length];
    for (int i = 0; i < charArrays.length; i++) {
        characterArray[i] = charArrays[i];
    }
    return characterArray;
}

<button> vs. <input type="button" />. Which to use?

I just want to add something to the rest of the answers here. Input elements are considered empty or void elements (other empty elements are area , base , br , col , hr , img , input , link , meta , and param. You can also check here), meaning they cannot have any content. In addition to not having any content, empty elements cannot have any pseudo-elements like ::after and ::before, which I consider a major drawback.

Convert Text to Date?

You can use DateValue to convert your string to a date in this instance

Dim c As Range
For Each c In ActiveSheet.UsedRange.columns("A").Cells
    c.Value = DateValue(c.Value)
Next c

It can convert yyyy-mm-dd format string directly into a native Excel date value.

Turning off hibernate logging console output

Try to set more reasonable logging level. Setting logging level to info means that only log event at info or higher level (warn, error and fatal) are logged, that is debug logging events are ignored.

log4j.logger.org.hibernate=info

or in XML version of log4j config file:

<logger name="org.hibernate">
  <level value="info"/> 
</logger>

See also log4j manual.

Downloading and unzipping a .zip file without writing to disk

It wasn't obvious in Vishal's answer what the file name was supposed to be in cases where there is no file on disk. I've modified his answer to work without modification for most needs.

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen

def unzip_string(zipped_string):
    unzipped_string = ''
    zipfile = ZipFile(StringIO(zipped_string))
    for name in zipfile.namelist():
        unzipped_string += zipfile.open(name).read()
    return unzipped_string

Explaining Apache ZooKeeper

Zookeeper is one of the best open source server and service that helps to reliably coordinates distributed processes. Zookeeper is a CP system (Refer CAP Theorem) that provides Consistency and Partition tolerance. Replication of Zookeeper state across all the nodes makes it an eventually consistent distributed service.

Moreover, any newly elected leader will update its followers with missing proposals or with a snapshot of the state, if the followers have many proposals missing.

Zookeeper also provides an API that is very easy to use. This blog post, Zookeeper Java API examples, has some examples if you are looking for examples.

So where do we use this? If your distributed service needs a centralized, reliable and consistent configuration management, locks, queues etc, you will find Zookeeper a reliable choice.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

The "double quote" + 'single quote' combo is not needed

console.log( $('#'+d) ); // single quotes only
console.log( $("#"+d) ); // double quotes only

Your selector results like this, which is overkill with the quotes:

$('"#abc"') // -> it'll try to find  <div id='"#abc"'>

// In css, this would be the equivalent:
"#abc"{ /* Wrong */ } // instead of:
#abc{ /* Right */ }

WordPress - Check if user is logged in

Try following code that worked fine for me

global $current_user;
get_currentuserinfo();

Then, use following code to check whether user has logged in or not.

if ($current_user->ID == '') { 
    //show nothing to user
}
else { 
    //write code to show menu here
}

How to remove a character at the end of each line in unix

alternative commands that does same job

tr -d ",$" < infile
awk 'gsub(",$","")' infile

How to properly highlight selected item on RecyclerView?

this is my solution, you can set on an item (or a group) and deselect it with another click:

 private final ArrayList<Integer> seleccionados = new ArrayList<>();
@Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
        viewHolder.san.setText(android_versions.get(i).getAndroid_version_name());
        if (!seleccionados.contains(i)){ 
            viewHolder.inside.setCardBackgroundColor(Color.LTGRAY);
        }
        else {
            viewHolder.inside.setCardBackgroundColor(Color.BLUE);
        }
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (seleccionados.contains(i)){
                    seleccionados.remove(seleccionados.indexOf(i)); 
                    viewHolder.inside.setCardBackgroundColor(Color.LTGRAY);
                } else { 
                    seleccionados.add(i);
                    viewHolder.inside.setCardBackgroundColor(Color.BLUE);
                }
            }
        });
    }

What are the "spec.ts" files generated by Angular CLI for?

if you generate new angular project using "ng new", you may skip a generating of spec.ts files. For this you should apply --skip-tests option.

ng new ng-app-name --skip-tests

What do the crossed style properties in Google Chrome devtools mean?

There is some cases when you copy and paste the CSS code in somewhere and it breaks the format so Chrome show the yellow warning. You should try to reformat the CSS code again and it should be fine.

Push Notifications in Android Platform

My understanding/experience with Android push notification are:

  1. C2DM GCM - If your target android platform is 2.2+, then go for it. Just one catch, device users have to be always logged with a Google Account to get the messages.

  2. MQTT - Pub/Sub based approach, needs an active connection from device, may drain battery if not implemented sensibly.

  3. Deacon - May not be good in a long run due to limited community support.

Edit: Added on November 25, 2013

GCM - Google says...

For pre-3.0 devices, this requires users to set up their Google account on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.*

import .css file into .less file

Change the file extension of your css file to .less. You don't need to write any LESS in it; all CSS is valid LESS (except of the MS stuff that you have to escape, but that's another issue.)

Per Fractalf's answer this is fixed in v1.4.0

C++ int float casting

Integer division occurs, then the result, which is an integer, is assigned as a float. If the result is less than 1 then it ends up as 0.

You'll want to cast the expressions to floats first before dividing, e.g.

float m = (float)(a.y - b.y) / (float)(a.x - b.x);

How to un-commit last un-pushed git commit without losing the changes

If you pushed the changes, you can undo it and move the files back to stage without using another branch.

git show HEAD > patch
git revert HEAD
git apply patch

It will create a patch file that contain the last branch changes. Then it revert the changes. And finally, apply the patch files to the working tree.

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

Ansible: filter a list by its attributes

Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:

- debug:
    msg: "{% for address in network.addresses.private_man %}\
        {% if address.type == 'fixed' %}\
          {{ address.addr }}\
        {% endif %}\
      {% endfor %}"

Or if you prefer to put it all on one line:

- debug:
    msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"

Which returns:

ok: [localhost] => {
    "msg": "172.16.1.100"
}

How to call stopservice() method of Service class from the calling activity class

In fact to stopping the service we must use the method stopService() and you are doing in right way:

Start service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  startService(myService);

Stop service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  stopService(myService);

if you call stopService(), then the method onDestroy() in the service is called (NOT the stopService() method):

  @Override
    public void onDestroy() {
      timer.cancel();
      task.cancel();    
        Log.i(TAG, "onCreate() , service stopped...");
    }

you must implement the onDestroy() method!.

Here is a complete example including how to start/stop the service.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used

var currentValue = parseInt($("#replies").text(),10);

format a Date column in a Data Frame

This should do it (where df is your dataframe)

df$JoiningDate <- as.Date(df$JoiningDate , format = "%m/%d/%y")

df[order(df$JoiningDate ),]

Delete a closed pull request from GitHub

This is the reply I received from Github when I asked them to delete a pull request:

"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

jQuery: Wait/Delay 1 second without executing code

ES6 setTimeout

setTimeout(() => {
  console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);

Edit: 204586560000 ms is the approximate time between the original question and this answer... assuming I calculated correctly.

Unable to find a @SpringBootConfiguration when doing a JpaTest

Indeed, Spring Boot does set itself up for the most part. You can probably already get rid of a lot of the code you posted, especially in Application.

I wish you had included the package names of all your classes, or at least the ones for Application and JpaTest. The thing about @DataJpaTest and a few other annotations is that they look for a @SpringBootConfiguration annotation in the current package, and if they cannot find it there, they traverse the package hierarchy until they find it.

For example, if the fully qualified name for your test class was com.example.test.JpaTest and the one for your application was com.example.Application, then your test class would be able to find the @SpringBootApplication (and therein, the @SpringBootConfiguration).

If the application resided in a different branch of the package hierarchy, however, like com.example.application.Application, it would not find it.

Example

Consider the following Maven project:

my-test-project
  +--pom.xml
  +--src
    +--main
      +--com
        +--example
          +--Application.java
    +--test
      +--com
        +--example
          +--test
            +--JpaTest.java

And then the following content in Application.java:

package com.example;

@SpringBootApplication
public class Application {

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

Followed by the contents of JpaTest.java:

package com.example.test;

@RunWith(SpringRunner.class)
@DataJpaTest
public class JpaTest {

    @Test
    public void testDummy() {
    }
}

Everything should be working. If you create a new folder inside src/main/com/example called app, and then put your Application.java inside it (and update the package declaration inside the file), running the test will give you the following error:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

LDAP root query syntax to search more than one specific OU

It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL

Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.

Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.

ModuleNotFoundError: No module named 'sklearn'

SOLVED:

The above did not help. Then I simply installed sklearn from within Jypyter-lab, even though sklearn 0.0 shows in 'pip list':

!pip install sklearn
import sklearn

What I learned later is that pip installs, in my case, packages in a different folder than Jupyter. This can be seen by executing:

import sys
print(sys.path)

Once from within Jupyter_lab notebook, and once from the command line using 'py notebook.py'.

In my case Jupyter list of paths where subfolders of 'anaconda' whereas Python list where subfolders of c:\users[username]...

Extract text from a string

If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]" does the matching, result will be in $Matches[0]

How to integrate SAP Crystal Reports in Visual Studio 2017

I had a workaround for this problem. I created dll project with viewer in vs2015 and used this dll in vs2017. Report showing perfectly.

css to make bootstrap navbar transparent

Further to Jochem Stoel's answer... I added 'navbar-fixed-top' to the DIV tag's class and it worked.

How to format date and time in Android?

You can use DateFormat. Result depends on default Locale of the phone, but you can specify Locale too :

https://developer.android.com/reference/java/text/DateFormat.html

This is results on a

DateFormat.getDateInstance().format(date)                                          

FR Locale : 3 nov. 2017

US/En Locale : Jan 12, 1952


DateFormat.getDateInstance(DateFormat.SHORT).format(date)

FR Locale : 03/11/2017

US/En Locale : 12.13.52


DateFormat.getDateInstance(DateFormat.MEDIUM).format(date)

FR Locale : 3 nov. 2017

US/En Locale : Jan 12, 1952


DateFormat.getDateInstance(DateFormat.LONG).format(date)

FR Locale : 3 novembre 2017

US/En Locale : January 12, 1952


DateFormat.getDateInstance(DateFormat.FULL).format(date)

FR Locale : vendredi 3 novembre 2017

US/En Locale : Tuesday, April 12, 1952


DateFormat.getDateTimeInstance().format(date)

FR Locale : 3 nov. 2017 16:04:58


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date)

FR Locale : 03/11/2017 16:04


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date)

FR Locale : 03/11/2017 16:04:58


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(date)

FR Locale : 03/11/2017 16:04:58 GMT+01:00


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL).format(date)

FR Locale : 03/11/2017 16:04:58 heure normale d’Europe centrale


DateFormat.getTimeInstance().format(date)

FR Locale : 16:04:58


DateFormat.getTimeInstance(DateFormat.SHORT).format(date)

FR Locale : 16:04


DateFormat.getTimeInstance(DateFormat.MEDIUM).format(date)

FR Locale : 16:04:58


DateFormat.getTimeInstance(DateFormat.LONG).format(date)

FR Locale : 16:04:58 GMT+01:00


DateFormat.getTimeInstance(DateFormat.FULL).format(date)

FR Locale : 16:04:58 heure normale d’Europe centrale


Retrieving JSON Object Literal from HttpServletRequest

This is simple method to get request data from HttpServletRequest using Java 8 Stream API:

String requestData = request.getReader().lines().collect(Collectors.joining());

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

How do I link to Google Maps with a particular longitude and latitude?

The best way is to use q parameter so that it displays the map with the point marked. eg.:

https://maps.google.com/?q=<lat>,<lng>

minimum double value in C/C++

The original question concerns infinity. So, why not use

#define Infinity  ((double)(42 / 0.0))

according to the IEEE definition? You can negate that of course.

MySQL Great Circle Distance (Haversine formula)

I have written a procedure that can calculate the same, but you have to enter the latitude and longitude in the respective table.

drop procedure if exists select_lattitude_longitude;

delimiter //

create procedure select_lattitude_longitude(In CityName1 varchar(20) , In CityName2 varchar(20))

begin

    declare origin_lat float(10,2);
    declare origin_long float(10,2);

    declare dest_lat float(10,2);
    declare dest_long float(10,2);

    if CityName1  Not In (select Name from City_lat_lon) OR CityName2  Not In (select Name from City_lat_lon) then 

        select 'The Name Not Exist or Not Valid Please Check the Names given by you' as Message;

    else

        select lattitude into  origin_lat from City_lat_lon where Name=CityName1;

        select longitude into  origin_long  from City_lat_lon where Name=CityName1;

        select lattitude into  dest_lat from City_lat_lon where Name=CityName2;

        select longitude into  dest_long  from City_lat_lon where Name=CityName2;

        select origin_lat as CityName1_lattitude,
               origin_long as CityName1_longitude,
               dest_lat as CityName2_lattitude,
               dest_long as CityName2_longitude;

        SELECT 3956 * 2 * ASIN(SQRT( POWER(SIN((origin_lat - dest_lat) * pi()/180 / 2), 2) + COS(origin_lat * pi()/180) * COS(dest_lat * pi()/180) * POWER(SIN((origin_long-dest_long) * pi()/180 / 2), 2) )) * 1.609344 as Distance_In_Kms ;

    end if;

end ;

//

delimiter ;

PostgreSQL ERROR: canceling statement due to conflict with recovery

As stated here about hot_standby_feedback = on :

Well, the disadvantage of it is that the standby can bloat the master, which might be surprising to some people, too

And here:

With what setting of max_standby_streaming_delay? I would rather default that to -1 than default hot_standby_feedback on. That way what you do on the standby only affects the standby


So I added

max_standby_streaming_delay = -1

And no more pg_dump error for us, nor master bloat :)

For AWS RDS instance, check http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html

Firebase (FCM) how to get token

This line should get you the firebase FCM token.

String token = FirebaseInstanceId.getInstance().getToken();
Log.d("MYTAG", "This is your Firebase token" + token);

Do Log.d to print it out to the android monitor.

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

Image.open() cannot identify image file - Python?

Just a note for people having the same problem as me. I've been using OpenCV/cv2 to export numpy arrays into Tiffs but I had problems with opening these Tiffs with PIL Open Image and had the same error as in the title. The problem turned out to be that PIL Open Image could not open Tiffs which was created by exporting numpy float64 arrays. When I changed it to float32, PIL could open the Tiff again.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

How to 'bulk update' with Django?

If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:

some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)

If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.

If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.

Filter dataframe rows if value in column is in a set list of values

You can also directly query your DataFrame for this information.

rpt.query('STK_ID in (600809,600141,600329)')

Or similarly search for ranges:

rpt.query('60000 < STK_ID < 70000')

Where to find Application Loader app in Mac?

With Application Loader now gone from Xcode I had a look around to see how to upload an .ipa file, since I use UE4 and I don't touch Xcode at all during development. Turns out it's pretty hidden away, You need to go to Window, Organiser, Archives. The archive will only appear if you ticked the "Generate Xcode Archive Package" tickbox in Project Settings. Then you just click Distribute and it's just does it.

how to prevent "directory already exists error" in a makefile when using mkdir

$(OBJDIR):
    mkdir $@

Which also works for multiple directories, e.g..

OBJDIRS := $(sort $(dir $(OBJECTS)))

$(OBJDIRS):
    mkdir $@

Adding $(OBJDIR) as the first target works well.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

To clarify for anyone who is looking for what is the difference between the 3 on a simpler level. You can expose your service with minimal ClusterIp (within k8s cluster) or larger exposure with NodePort (within cluster external to k8s cluster) or LoadBalancer (external world or whatever you defined in your LB).

ClusterIp exposure < NodePort exposure < LoadBalancer exposure

  • ClusterIp
    Expose service through k8s cluster with ip/name:port
  • NodePort
    Expose service through Internal network VM's also external to k8s ip/name:port
  • LoadBalancer
    Expose service through External world or whatever you defined in your LB.

Java: Identifier expected

You can't call methods outside a method. Code like this cannot float around in the class.

You need something like:

public class MyClass {

  UserInput input = new UserInput();

  public void foo() {
      input.name();
  }
}

or inside a constructor:

public class MyClass {

  UserInput input = new UserInput();

  public MyClass() {
      input.name();
  }
}

What is __gxx_personality_v0 for?

A quick grep of the libstd++ code base revealed the following two usages of __gx_personality_v0:

In libsupc++/unwind-cxx.h

// GNU C++ personality routine, Version 0.                                      
extern "C" _Unwind_Reason_Code __gxx_personality_v0
     (int, _Unwind_Action, _Unwind_Exception_Class,
      struct _Unwind_Exception *, struct _Unwind_Context *);

In libsupc++/eh_personality.cc

#define PERSONALITY_FUNCTION    __gxx_personality_v0
extern "C" _Unwind_Reason_Code
PERSONALITY_FUNCTION (int version,
                      _Unwind_Action actions,
                      _Unwind_Exception_Class exception_class,
                      struct _Unwind_Exception *ue_header,
                      struct _Unwind_Context *context)
{
  // ... code to handle exceptions and stuff ...
}

(Note: it's actually a little more complicated than that; there's some conditional compilation that can change some details).

So, as long as your code isn't actually using exception handling, defining the symbol as void* won't affect anything, but as soon as it does, you're going to crash - __gxx_personality_v0 is a function, not some global object, so trying to call the function is going to jump to address 0 and cause a segfault.

Syntax error: Illegal return statement in JavaScript

This can happen in ES6 if you use the incorrect (older) syntax for static methods:

export default class MyClass
{
    constructor()
    {
       ...
    }

    myMethod()
    {
       ...
    }
}

MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works

MyClass.anotherMethod() //or
MyClass.anotherMethod = function()
{
   return something; //doesn't work
}

Whereas the correct syntax is:

export default class MyClass
{
    constructor()
    {
       ...
    }

    myMethod()
    {
       ...
    }

    static anotherMethod()
    {
       return something; //works
    }
}

MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

Difference between @click and v-on:click Vuejs

v-bind and v-on are two frequently used directives in vuejs html template. So they provided a shorthand notation for the both of them as follows:

You can replace v-on: with @

v-on:click='someFunction'

as:

@click='someFunction'

Another example:

v-on:keyup='someKeyUpFunction'

as:

@keyup='someKeyUpFunction'

Similarly, v-bind with :

v-bind:href='var1'

Can be written as:

:href='var1'

Hope it helps!

jquery mobile background image

None of the above worked for me using JQM 1.2.0

This did work for me:

.ui-page.ui-body-c {
    background: url(bg.png);
    background-repeat:no-repeat;
    background-position:center center;
    background-size:cover;  
}

How do I find the duplicates in a list and create another list with them?

Try this For check duplicates

>>> def checkDuplicate(List):
    duplicate={}
    for i in List:
            ## checking whether the item is already present in dictionary or not
            ## increasing count if present
            ## initializing count to 1 if not present

        duplicate[i]=duplicate.get(i,0)+1

    return [k for k,v in duplicate.items() if v>1]

>>> checkDuplicate([1,2,3,"s",1,2,3])
[1, 2, 3]

How to change the docker image installation directory?

Much easier way to do so:

Stop docker service

sudo systemctl stop docker

Move existing docker directory to new location

sudo mv /var/lib/docker/ /path/to/new/docker/

Create symbolic link

sudo ln -s /path/to/new/docker/ /var/lib/docker

Start docker service

sudo systemctl start docker

CodeIgniter: 404 Page Not Found on Live Server

I am doing it on local and production server this way:


Routes:

$route['default_controller']   = 'Home_controller';

Files' names:

  • in controllers folder: Home_controller.php
  • in models folder: Home_model.php
  • in views folder: Home.php

Home_controller.php:

       class Home_controller extends CI_Controller {

           public function index(){

              //loading Home_model
              $this->load->model('Home_model');

              //get data from DB
              $data['db_data']  = $this->Home_model->getData();

              //pass $data to Home.html
              $this->load->view('Home', $data);
           }
       }

Home_model.php:

       class Home_model extends CI_Model {
       ...
       }

There should be no more problems with cases anymore :)

How to debug Apache mod_rewrite

One trick is to turn on the rewrite log. To turn it on, try this line in your apache main config or current virtual host file (not in .htaccess):

LogLevel alert rewrite:trace6

Before Apache httpd 2.4 mod_rewrite, such a per-module logging configuration did not exist yet, instead you could use the following logging settings:

RewriteEngine On
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Show constraints on tables command

Try doing:

SHOW TABLE STATUS FROM credentialing1;

The foreign key constraints are listed in the Comment column of the output.

Resetting Select2 value in dropdown with reset button

To achieve a generic solution, why not do this:

$(':reset').live('click', function(){
    var $r = $(this);
    setTimeout(function(){ 
        $r.closest('form').find('.select2-offscreen').trigger('change'); 
    }, 10);
});

This way: You'll not have to make a new logic for each select2 on your application.

And, you don't have to know the default value (which, by the way, does not have to be "" or even the first option)

Finally, setting the value to :selected would not always achieve a true reset, since the current selected might well have been set programmatically on the client, whereas the default action of the form select is to return input element values to the server-sent ones.

EDIT: Alternatively, considering the deprecated status of live, we could replace the first line with this:

$('form:has(:reset)').on('click', ':reset', function(){

or better still:

$('form:has(:reset)').on('reset', function(){

PS: I personally feel that resetting on reset, as well as triggering blur and focus events attached to the original select, are some of the most conspicuous "missing" features in select2!

Running Facebook application on localhost

None of the answers above worked for me. I am running on FB API 2.5. Mine was a combination of issues that lead to success once resolved

  1. Create a test app to ensure that it is maintained and managed as such and can be disabled when going live
  2. Read the error message properly :) - I had to enable "Web OAuth Login" WITH "Client OAuth Login"
  3. Use https://www.whatismyip.com/ to find out what my current IP is
  4. Create an A record on my Domain i.e. http://localhost.mydomain.com that points to my current IP

It's probably not ideal as Dynamic IP's change and one could probably use DynDNS or something similar to make the IP more "static" but it worked for me

joining two select statements

Not sure what you are trying to do, but you have two select clauses. Do this instead:

SELECT * 
FROM ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
       WHERE products_id = 181) AS A
JOIN ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id
       WHERE products_id = 180) AS B

ON A.orders_id=B.orders_id

Update:

You could probably reduce it to something like this:

SELECT o.orders_id, 
       op1.products_id, 
       op1.quantity, 
       op2.products_id, 
       op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id  
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id  
WHERE op1.products_id = 180
AND op2.products_id = 181

Get the date (a day before current time) in Bash

Sorry not mentioning I on Solaris system. As such, the -date switch is not available on Solaris bash.

I find out I can get the previous date with little trick on timezone.

DATE=`TZ=MYT+16 date +%Y-%m-%d_%r`
echo $DATE

Show space, tab, CRLF characters in editor of Visual Studio

For those who are looking for a button toggle:

The name of this command is View white space in GUI menu (Edit -> Advanced -> View white space).

Menu toggle

The name of this command in the Add command popup is Toggle Visual Space.

Button toggle.

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

This can be changed in your my.ini file (on Windows, located in \Program Files\MySQL\MySQL Server) under the server section, for example:

[mysqld]

max_allowed_packet = 10M

Java, Shifting Elements in an Array

static void pushZerosToEnd(int arr[])
    {   int n = arr.length;
        int count = 0;  // Count of non-zero elements
        // Traverse the array. If element encountered is non-zero, then
        // replace the element at index 'count' with this element
        for (int i = 0; i < n; i++){
            if (arr[i] != 0)`enter code here`
               // arr[count++] = arr[i]; // here count is incremented
                swapNumbers(arr,count++,i);
        }
        for (int j = 0; j < n; j++){
            System.out.print(arr[j]+",");
        }
     }

    public static void swapNumbers(int [] arr, int pos1, int pos2){
        int temp  = arr[pos2];
        arr[pos2] = arr[pos1];
        arr[pos1] = temp;
    }

How do I remove version tracking from a project cloned from git?

In addition to the steps below, you may want to also remove the .gitignore file.

  • Consider removing the .gitignore file if you want to remove any trace of Git in your project.

  • ** Consider leaving the .gitignore file if you would ever want reincorporate Git into the project.

Some frameworks may automatically produce the .gitignore file so you may want to leave it.


Linux, Mac, or Unix based operating systems

Open a terminal and navigate to the directory of your project, i.e. - cd path_to_your_project.

Run this command:

rm -rf .git*

This will remove the Git tracking and metadata from your project. If you want to keep the metadata (such as .gitignore and .gitkeep), you can delete only the tracking by running rm -rf .git.


Windows

Using the command prompt

The rmdir or rd command will not delete/remove any hidden files or folders within the directory you specify, so you should use the del command to be sure that all files are removed from the .git folder.

  1. Open the command prompt

    1. Either click Start then Run or hit the Windows key key and r at the same time.

    2. Type cmd and hit enter

  2. Navigate to the project directory, i.e. - cd path_to_your_project

  1. Run these commands

    1. del /F /S /Q /A .git

    2. rmdir .git

The first command removes all files and folder within the .git folder. The second removes the .git folder itself.

No command prompt

  1. Open the file explorer and navigate to your project

  2. Show hidden files and folders - refer to this article for a visual guide

    1. In the view menu on the toolbar, select Options

    2. In the Advanced Settings section, find Hidden files and Folders under the Files and Folders list and select Show hidden files and folders

  3. Close the options menu and you should see all hidden folders and files including the .git folder.

    Delete the .git folder Delete the .gitignore file ** (see note at the top of this answer)

Why does a base64 encoded string have an = sign at the end

= is a padding character. If the input stream has length that is not a multiple of 3, the padding character will be added. This is required by decoder: if no padding present, the last byte would have an incorrect number of zero bits.

Better and deeper explanation here: https://base64tool.com/detect-whether-provided-string-is-base64-or-not/

HTML Entity Decode

I think that is the exact opposite of the solution chosen.

var decoded = $("<div/>").text(encodedStr).html();

Try it :)

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

Checking character length in ruby

Ruby provides a built-in function for checking the length of a string. Say it's called s:

if s.length <= 25
  # We're OK
else
  # Too long
end

What's the difference between VARCHAR and CHAR?

What's the difference between VARCHAR and CHAR in MySQL?

To already given answers I would like to add that in OLTP systems or in systems with frequent updates consider using CHAR even for variable size columns because of possible VARCHAR column fragmentation during updates.

I am trying to store MD5 hashes.

MD5 hash is not the best choice if security really matters. However, if you will use any hash function, consider BINARY type for it instead (e.g. MD5 will produce 16-byte hash, so BINARY(16) would be enough instead of CHAR(32) for 32 characters representing hex digits. This would save more space and be performance effective.

CSS: Position text in the middle of the page

Try this CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}

jsFiddle: http://jsfiddle.net/wprw3/

Visual Studio Code open tab in new window

Just an update, Feb 1, 2019: cmd+shift+n on Mac now opens a new window where you can drag over tabs. I didn't find that out until I when through KyleMit's response and saw his key mapping suggestion was already mapped to the correct action.

Received an invalid column length from the bcp client for colid 6

Check the size of the columns in the table you are doing bulk insert/copy. the varchar or other string columns might needs to be extended or the value your are inserting needs to be trim. Column order also should be same as in table.

e.g, Increase size of varchar column 30 to 50 =>

ALTER TABLE [dbo].[TableName] ALTER COLUMN [ColumnName] Varchar(50)

MySQL LEFT JOIN 3 tables

You are trying to join Person_Fear.PersonID onto Person_Fear.FearID - This doesn't really make sense. You probably want something like:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear
    INNER JOIN Fears
    ON Person_Fear.FearID = Fears.FearID
ON Person_Fear.PersonID = Persons.PersonID

This joins Persons onto Fears via the intermediate table Person_Fear. Because the join between Persons and Person_Fear is a LEFT JOIN, you will get all Persons records.

Alternatively:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID
LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID

AFNetworking Post Request

Using AFNetworking 3.0, you should write:

NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
NSURL * urlStr = [NSURL URLWithString:strURL];

NSDictionary *dictParameters = @{@"user[height]": height,@"user[weight]": weight};

AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];


[manager POST:url.absoluteString parameters:dictParameters success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"PLIST: %@", responseObject);
   
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    
}];

Cannot download Docker images behind a proxy

This doesn't exactly answer the question, but might help, especially if you don't want to deal with service files.

In case you are the one is hosting the image, one way is to convert the image as a tar archive instead, using something like the following at the server.

docker save <image-name> --output <archive-name>.tar

Simply download the archive and turn it back into an image.

docker load <archive-name>.tar

Where does Chrome store extensions?

Another alternative is to do right click on the chrome icon and then go to shortcut tab (according to windows 10). You will see there "Target", copy the path and remove "chrome.exe".

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

Get IP address of an interface on Linux

Try this:

#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>

int
main()
{
 int fd;
 struct ifreq ifr;

 fd = socket(AF_INET, SOCK_DGRAM, 0);

 /* I want to get an IPv4 IP address */
 ifr.ifr_addr.sa_family = AF_INET;

 /* I want IP address attached to "eth0" */
 strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);

 ioctl(fd, SIOCGIFADDR, &ifr);

 close(fd);

 /* display result */
 printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

 return 0;
}

The code sample is taken from here.

How to resolve the C:\fakepath?

I use the object FileReader on the input onchange event for your input file type! This example uses the readAsDataURL function and for that reason you should have an tag. The FileReader object also has readAsBinaryString to get the binary data, which can later be used to create the same file on your server

Example:

var input = document.getElementById("inputFile");
var fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event){
    var img = document.getElementById("yourImgTag");
    img.src = event.target.result;
}

How does the Java 'for each' loop work?

The concept of a foreach loop as mentioned in Wikipedia is highlighted below:

Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read.

So the concept of a foreach loop describes that the loop does not use any explicit counter which means that there is no need of using indexes to traverse in the list thus it saves user from off-by-one error. To describe the general concept of this off-by-one error, let us take an example of a loop to traverse in a list using indexes.

// In this loop it is assumed that the list starts with index 0
for(int i=0; i<list.length; i++){

}

But suppose if the list starts with index 1 then this loop is going to throw an exception as it will found no element at index 0 and this error is called an off-by-one error. So to avoid this off-by-one error the concept of a foreach loop is used. There may be other advantages too, but this is what I think is the main concept and advantage of using a foreach loop.

Getting value of HTML text input

If you want to use the value of the email input somewhere else on the same page, for example to do some sort of validation, you could use JavaScript. First I would assign an "id" attribute to your email textbox:

<input type="text" name="email" id="email"/>

and then I would retrieve the value with JavaScript:

var email = document.getElementById('email').value;

From there, you can do additional processing on the value of 'email'.

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

Using import fs from 'fs'

If we are using TypeScript, we can update the type definition file by running the command npm install @types/node from the terminal or command prompt.

Launch programs whose path contains spaces

You van use Exec

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Exec("c:\Program Files\Mozilla Firefox\firefox.exe")
Set objShell = Nothing

How to include (source) R script in other scripts

Say util.R produces a function foo(). You can check if this function is available in the global environment and source the script if it isn't:

if(identical(length(ls(pattern = "^foo$")), 0))
    source("util.R")

That will find anything with the name foo. If you want to find a function, then (as mentioned by @Andrie) exists() is helpful but needs to be told exactly what type of object to look for, e.g.

if(exists("foo", mode = "function"))
    source("util.R")

Here is exists() in action:

> exists("foo", mode = "function")
[1] FALSE
> foo <- function(x) x
> exists("foo", mode = "function")
[1] TRUE
> rm(foo)
> foo <- 1:10
> exists("foo", mode = "function")
[1] FALSE

What is the difference between a static and const variable?

static value may exists into a function and can be used in different forms and can have different value in the program. Also during program after increment of decrement their value may change but const in constant during the whole program.

Can we pass parameters to a view in SQL?

There are two ways to achieve what you want. Unfortunately, neither can be done using a view.

You can either create a table valued user defined function that takes the parameter you want and returns a query result

Or you can do pretty much the same thing but create a stored procedure instead of a user defined function.

For example:

the stored procedure would look like

CREATE PROCEDURE s_emp
(
    @enoNumber INT
) 
AS 
SELECT
    * 
FROM
    emp 
WHERE 
    emp_id=@enoNumber

Or the user defined function would look like

CREATE FUNCTION u_emp
(   
    @enoNumber INT
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT    
        * 
    FROM    
        emp 
    WHERE     
        emp_id=@enoNumber
)

Error : Index was outside the bounds of the array.

public int[] posStatus;       

public UsersInput()    
{    
    //It means postStatus will contain 9 elements from index 0 to 8. 
    this.posStatus = new int[9];   
}

int intUsersInput = 0;   

if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?    
{    
    posStatus[intUsersInput-1] += 1; //set it to 1    
} 

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

Escape double quotes in parameter

Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.

Here's a set of basic rules:

  1. When not wrapped in double-quoted groups, spaces separate parameters:
    program param1 param2 param 3 will pass four parameters to program.exe:
         param1, param2, param, and 3.
  2. A double-quoted group ignores spaces as value separators when passing parameters to programs:
    program one two "three and more" will pass three parameters to program.exe:
         one, two, and three and more.
  3. Now to explain some of the confusion:
  4. Double-quoted groups that appear directly adjacent to text not wrapped with double-quotes join into one parameter:
    hello"to the entire"world acts as one parameter: helloto the entireworld.
  5. Note: The previous rule does NOT imply that two double-quoted groups can appear directly adjacent to one another.
  6. Any double-quote directly following a closing quote is treated as (or as part of) plain unwrapped text that is adjacent to the double-quoted group, but only one double-quote:
    "Tim says, ""Hi!""" will act as one parameter: Tim says, "Hi!"

Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:

"   open double-quote group
T   inside ""s
i   inside ""s
m   inside ""s
    inside ""s - space doesn't separate
s   inside ""s
a   inside ""s
y   inside ""s
s   inside ""s
,   inside ""s
    inside ""s - space doesn't separate
"   close double-quoted group
"   quote directly follows closer - acts as plain unwrapped text: "
H   outside ""s - gets joined to previous adjacent group
i   outside ""s - ...
!   outside ""s - ...
"   open double-quote group
"   close double-quote group
"   quote directly follows closer - acts as plain unwrapped text: "

Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,  is the first, wrapped to escape the spaces
"Hi! is the second, not wrapped (there are no spaces)
 is the third, a double-quote group wrapping nothing
" is the fourth, the unwrapped close quote.

As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.

From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:

"Tim said to him, """What's been happening lately?""""

will print Tim said to him, "What's been happening lately?" as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.

Here are a few examples to close it off:

program a b                       REM sends (a) and (b)
program """a"""                   REM sends ("a")
program """a b"""                 REM sends ("a) and (b")
program """"Hello,""" Mike said." REM sends ("Hello," Mike said.)
program ""a""b""c""d""            REM sends (abcd) since the "" groups wrap nothing
program "hello to """quotes""     REM sends (hello to "quotes")
program """"hello world""         REM sends ("hello world")
program """hello" world""         REM sends ("hello world")
program """hello "world""         REM sends ("hello) and (world")
program "hello ""world"""         REM sends (hello "world")
program "hello """world""         REM sends (hello "world")

Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.

I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).

Mac install and open mysql using terminal

This command works for me:

Command:

mysql --host=localhost -uroot -proot

What's the difference between emulation and simulation?

This is a hard question to answer definitively because the terms and often misused or confused.

Often, an emulator is a complete re-implementation of a particular device or platform. The emulator acts exactly like the real device would. For example, a NES emulator implements the CPU, the sound chip, the video output, the controller signals, etc. The unmodified code from a NES castridge can be dumped and then the resulting image can be loaded into our emulator and played.

A simulator is a partial implementation of a device/platform, it does just enough for its own purposes. For example, the iPhone Simulator runs an "iPhone app" that has been specifically compiled to target x86 and the Cocoa API rather than the real device's ARM CPU and Cocoa Touch API. However, the binary that we run in the simulator would not work on the real device.

How do I delete everything in Redis?

You can use FLUSHALL which will delete all keys from your every database. Where as FLUSHDB will delete all keys from our current database.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Initializing entire 2D array with one value

To initialize 2d array with zero use the below method: int arr[n][m] = {};

NOTE : The above method will only work to initialize with 0;

What is the relative performance difference of if/else versus switch statement in Java?

According to Cliff Click in his 2009 Java One talk A Crash Course in Modern Hardware:

Today, performance is dominated by patterns of memory access. Cache misses dominate – memory is the new disk. [Slide 65]

You can get his full slides here.

Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.

So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP ? XML ? DOM ? SQL ? …" which "passes all the data through the cache".

Unit testing void methods?

Void return types / Subroutines are old news. I haven't made a Void return type (Unless I was being extremely lazy) in like 8 years (From the time of this answer, so just a bit before this question was asked).

Instead of a method like:

public void SendEmailToCustomer()

Make a method that follows Microsoft's int.TryParse() paradigm:

public bool TrySendEmailToCustomer()

Maybe there isn't any information your method needs to return for usage in the long-run, but returning the state of the method after it performs its job is a huge use to the caller.

Also, bool isn't the only state type. There are a number of times when a previously-made Subroutine could actually return three or more different states (Good, Normal, Bad, etc). In those cases, you'd just use

public StateEnum TrySendEmailToCustomer()

However, while the Try-Paradigm somewhat answers this question on how to test a void return, there are other considerations too. For example, during/after a "TDD" cycle, you would be "Refactoring" and notice you are doing two things with your method... thus breaking the "Single Responsibility Principle." So that should be taken care of first. Second, you might have idenetified a dependency... you're touching "Persistent" Data.

If you are doing the data access stuff in the method-in-question, you need to refactor into an n-tier'd or n-layer'd architecture. But we can assume that when you say "The strings are then inserted into a database", you actually mean you're calling a business logic layer or something. Ya, we'll assume that.

When your object is instantiated, you now understand that your object has dependencies. This is when you need to decide if you are going to do Dependency Injection on the Object, or on the Method. That means your Constructor or the method-in-question needs a new Parameter:

public <Constructor/MethodName> (IBusinessDataEtc otherLayerOrTierObject, string[] stuffToInsert)

Now that you can accept an interface of your business/data tier object, you can mock it out during Unit Tests and have no dependencies or fear of "Accidental" integration testing.

So in your live code, you pass in a REAL IBusinessDataEtc object. But in your Unit Testing, you pass in a MOCK IBusinessDataEtc object. In that Mock, you can include Non-Interface Properties like int XMethodWasCalledCount or something whose state(s) are updated when the interface methods are called.

So your Unit Test will go through your Method(s)-In-Question, perform whatever logic they have, and call one or two, or a selected set of methods in your IBusinessDataEtc object. When you do your Assertions at the end of your Unit Test you have a couple of things to test now.

  1. The State of the "Subroutine" which is now a Try-Paradigm method.
  2. The State of your Mock IBusinessDataEtc object.

For more information on Dependency Injection ideas on the Construction-level... as they pertain to Unit Testing... look into Builder design patterns. It adds one more interface and class for each current interface/class you have, but they are very tiny and provide HUGE functionality increases for better Unit-Testing.

How to get the file extension in PHP?

No need to use string functions. You can use something that's actually designed for what you want: pathinfo():

$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

In Objective-C, how do I test the object type?

Simple, [yourobject class] it will return the class name of yourobject.

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

What are native methods in Java and where should they be used?

The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.

Native methods are usually used to interface with system calls or libraries written in other programming languages.

Node.js: what is ENOSPC error and how to solve?

If your /tmp mount on a linux filesystem is mounted as overflow (often sized at 1MB), this is likely due to you not specifying /tmp as its own partition and your root filesystem filled up and /tmp was remounted as a fallback.

To fix this after you’ve cleared space, just unmount the fallback and it should remount at its original point:

sudo umount overflow

How to pass parameters on onChange of html select

jQuery solution

How do I get the text value of a selected option

Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:

$( "#myselect" ).val();
// => 1

The second is the text value of the select.
For example, using the following select box:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:

$( "#myselect option:selected" ).text();
// => "Mr"  

See also

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

How to convert a char array back to a string?

 //Given Character Array 
  char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};


    //Converting Character Array to String using String funtion     
    System.out.println(String.valueOf(a));
    //OUTPUT : hello world

Converting any given Array type to String using Java 8 Stream function

String stringValue = 
Arrays.stream(new char[][]{a}).map(String::valueOf).collect(Collectors.joining());

Convert String[] to comma separated string in java

As tempting and "cool" as the code may appear, do not use fold or reduce on large collections of strings, as these will suffer from the string concatenation problem

String[] strings = { "foo", "bar", "baz" };
Optional<String> result = Arrays.stream(strings)
        .reduce((a, b) -> String.format("%s,%s", a, b));
System.out.println(result.get());

Instead, as per other answers, use String.join() if you already have a collection, or a StringBuilder if not.

Default parameters with C++ constructors

I would go with the default parameters, for this reason: Your example assumes that ctor parameters directly correspond to member variables. But what if that is not the case, and you have to process the parameters before the object is initialize. Having one common ctor would be the best way to go.

Android Camera : data intent returns null

When we capture the image from Camera in Android then Uri or data.getdata() becomes null. We have two solutions to resolve this issue.

  1. Retrieve the Uri path from the Bitmap Image
  2. Retrieve the Uri path from cursor.

This is how to retrieve the Uri from the Bitmap Image. First capture image through Intent that will be the same for both methods:

// Capture Image
captureImg.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, reqcode);
        }
    }
});

Now implement OnActivityResult, which will be the same for both methods:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==reqcode && resultCode==RESULT_OK)
    {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        ImageView.setImageBitmap(photo);

        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);

        // Show Uri path based on Image
        Toast.makeText(LiveImage.this,"Here "+ tempUri, Toast.LENGTH_LONG).show();

        // Show Uri path based on Cursor Content Resolver
        Toast.makeText(this, "Real path for URI : "+getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
    }
}

Now create all above methods to create the Uri from Image and Cursor methods:

Uri path from Bitmap Image:

private Uri getImageUri(Context applicationContext, Bitmap photo) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
    return Uri.parse(path);
}

Uri from Real path of saved image:

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

OnClick in Excel VBA

Clearly, there is no perfect answer. However, if you want to allow the user to

  1. select certain cells
  2. allow them to change those cells, and
  3. trap each click,even repeated clicks on the same cell,

then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.

One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own.

If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'prevent Select event triggering again when we extend the selection below
  Application.EnableEvents = False
  Target.Resize(1, 2).Select
  Application.EnableEvents = True
End Sub

How to read integer value from the standard input in Java

You can use java.util.Scanner (API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

Can I load a UIImage from a URL?

Try this code, you can set loading image with it, so the users knows that your app is loading an image from url:

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]];
    [yourImageView setContentMode:UIViewContentModeScaleAspectFit];

    //Request image data from the URL:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://yourdomain.com/yourimg.png"]];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (imgData)
            {
                //Load the data into an UIImage:
                UIImage *image = [UIImage imageWithData:imgData];

                //Check if your image loaded successfully:
                if (image)
                {
                    yourImageView.image = image;
                }
                else
                {
                    //Failed to load the data into an UIImage:
                    yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
                }
            }
            else
            {
                //Failed to get the image data:
                yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
            }
        });
    });

Static nested class in Java, why?

From http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html:

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.

Change Twitter Bootstrap Tooltip content on click

I think Mehmet Duran is almost right, but there were some problems when using multiple classes with the same tooltip and their placement. The following code also avoids js errors checking if there is any class called "tooltip_class". Hope this helps.

if (jQuery(".tooltip_class")[0]){    

        jQuery('.tooltip_class')
            .attr('title', 'New Title.')
            .attr('data-placement', 'right')
            .tooltip('fixTitle')
            .tooltip('hide');

    }

'module' has no attribute 'urlencode'

urllib has been split up in Python 3.

The urllib.urlencode() function is now urllib.parse.urlencode(),

the urllib.urlopen() function is now urllib.request.urlopen().

How to align an input tag to the center without specifying the width?

you can put in a table cell and then align the cell content.

<table>
   <tr>
     <td align="center">
        <input type="button" value="Some Button">
     </td>
   </tr>
</table>

How to dismiss keyboard iOS programmatically when pressing return

Try to get an idea about what a first responder is in iOS view hierarchy. When your textfield becomes active(or first responder) when you touch inside it (or pass it the messasge becomeFirstResponder programmatically), it presents the keyboard. So to remove your textfield from being the first responder, you should pass the message resignFirstResponder to it there.

[textField resignFirstResponder];

And to hide the keyboard on its return button, you should implement its delegate method textFieldShouldReturn: and pass the resignFirstResponder message.

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

Timer for Python game

New to the python world!
I need a System Time independent Stopwatch so I did translate my old C++ class into Python:

from ctypes.wintypes import DWORD
import win32api
import datetime

class Stopwatch:

    def __init__(self):
        self.Restart()

    def Restart(self):
        self.__ulStartTicks = DWORD(win32api.GetTickCount()).value

    def ElapsedMilliSecs(self):
        return DWORD(DWORD(win32api.GetTickCount()).value-DWORD(self.__ulStartTicks).value).value

    def ElapsedTime(self):
        return datetime.timedelta(milliseconds=self.ElapsedMilliSecs())

This has no 49 days run over issue due to DWORD math but NOTICE that GetTickCount has about 15 milliseconds granularity so do not use this class if your need 1-100 milliseconds elapsed time ranges.

Any improvement or feedback is welcome!

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

Pad left or right with string.format (not padleft or padright) with arbitrary string

There is another solution.

Implement IFormatProvider to return a ICustomFormatter that will be passed to string.Format :

public class StringPadder : ICustomFormatter
{
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
  {
     // do padding for string arguments
     // use default for others
  }
}

public class StringPadderFormatProvider : IFormatProvider
{
  public object GetFormat(Type formatType)
  { 
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  }
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();
}

Then you can use it like this :

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

java.math.BigInteger cannot be cast to java.lang.Integer

The column in the database is probably a DECIMAL. You should process it as a BigInteger, not an Integer, otherwise you are losing digits. Or else change the column to int.

How to dynamically create generic C# object using reflection?

Make sure you're doing this for a good reason, a simple function like the following would allow static typing and allows your IDE to do things like "Find References" and Refactor -> Rename.

public Task <T> factory (String name)
{
  Task <T> result;

  if (name.CompareTo ("A") == 0)
  {
    result = new TaskA ();
  }
  else if (name.CompareTo ("B") == 0)
  {
    result = new TaskB ();
  }

  return result;
}

Declare global variables in Visual Studio 2010 and VB.NET

Public Class Form1

   Public Shared SomeValue As Integer = 5

End Class

The answer:

MessageBox.Show("this is the number"&GlobalVariables.SomeValue)

How do I convert a numpy array to (and display) an image?

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)

Adding an identity to an existing column

As per my current condition, I follow this approach. I want to give identity to a primary table after data inserted via script.

As I want to append identity, so it always start from 1 to End of record count that I want.

--first drop column and add with identity
ALTER TABLE dbo.tblProductPriceList drop column ID 
ALTER TABLE dbo.tblProductPriceList add ID INT IDENTITY(1,1)

--then add primary key to that column (exist option you can ignore)
IF  NOT EXISTS (SELECT * FROM sys.key_constraints  WHERE object_id = OBJECT_ID(N'[dbo].[PK_tblProductPriceList]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblProductPriceList]'))
    ALTER TABLE [tblProductPriceList] ADD PRIMARY KEY (id)
GO

This will create the same primary key column with identity

I used this links : https://blog.sqlauthority.com/2014/10/11/sql-server-add-auto-incremental-identity-column-to-table-after-creating-table/

Add primary key to existing table

Why is document.write considered a "bad practice"?

There's actually nothing wrong with document.write, per se. The problem is that it's really easy to misuse it. Grossly, even.

In terms of vendors supplying analytics code (like Google Analytics) it's actually the easiest way for them to distribute such snippets

  1. It keeps the scripts small
  2. They don't have to worry about overriding already established onload events or including the necessary abstraction to add onload events safely
  3. It's extremely compatible

As long as you don't try to use it after the document has loaded, document.write is not inherently evil, in my humble opinion.

C# LINQ find duplicates in List

You can do this:

var list = new[] {1,2,3,1,4,2};
var duplicateItems = list.Duplicates();

With these extension methods:

public static class Extensions
{
    public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
    {
        var grouped = source.GroupBy(selector);
        var moreThan1 = grouped.Where(i => i.IsMultiple());
        return moreThan1.SelectMany(i => i);
    }

    public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source)
    {
        return source.Duplicates(i => i);
    }

    public static bool IsMultiple<T>(this IEnumerable<T> source)
    {
        var enumerator = source.GetEnumerator();
        return enumerator.MoveNext() && enumerator.MoveNext();
    }
}

Using IsMultiple() in the Duplicates method is faster than Count() because this does not iterate the whole collection.

Does Visual Studio Code have box select/multi-line edit?

For multiple select in Visual Studio Code, hold down the Alt key and starting clicking wherever you want to edit.

Visual Studio Code supports multiple line edit.

what does numpy ndarray shape do?

Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray. You can check the dimensionality of a numpy array using the .ndim property. The .shape property is a tuple of length .ndim containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:

a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32

If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.

If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.

a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T

Adding a regression line on a ggplot

The simple solution using geom_abline:

geom_abline(slope = coef(data.lm)[[2]], intercept = coef(data.lm)[[1]])

Where data.lm is an lm object, and coef(data.lm) looks something like this:

> coef(data.lm)
(Intercept)    DepDelay 
  -2.006045    1.025109 

The numeric indexing assumes that (Intercept) is listed first, which is the case if the model includes an intercept. If you have some other linear model object, just plug in the slope and intercept values similarly.

Python integer division yields float

Hope it might help someone instantly.

Behavior of Division Operator in Python 2.7 and Python 3

In Python 2.7: By default, division operator will return integer output.

to get the result in double multiple 1.0 to "dividend or divisor"

100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857

In Python 3

// => used for integer output
/ => used for double output

100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0    # floating-point result if divsor or dividend real

How do I subscribe to all topics of a MQTT broker

Use the wildcard "#" but beware that at some point you will have to somehow understand the data passing through the bus!

Get list of data-* attributes using javascript / jQuery

As mentioned above modern browsers have the The HTMLElement.dataset API.
That API gives you a DOMStringMap, and you can retrieve the list of data-* attributes simply doing:

var dataset = el.dataset; // as you asked in the question

you can also retrieve a array with the data- property's key names like

var data = Object.keys(el.dataset);

or map its values by

Object.keys(el.dataset).map(function(key){ return el.dataset[key];});
// or the ES6 way: Object.keys(el.dataset).map(key=>{ return el.dataset[key];});

and like this you can iterate those and use them without the need of filtering between all attributes of the element like we needed to do before.

Default SecurityProtocol in .NET 4.5

The default System.Net.ServicePointManager.SecurityProtocol in both .NET 4.0/4.5 is SecurityProtocolType.Tls|SecurityProtocolType.Ssl3.

.NET 4.0 supports up to TLS 1.0 while .NET 4.5 supports up to TLS 1.2

However, an application targeting .NET 4.0 can still support up to TLS 1.2 if .NET 4.5 is installed in the same environment. .NET 4.5 installs on top of .NET 4.0, replacing System.dll.

I've verified this by observing the correct security protocol set in traffic with fiddler4 and by manually setting the enumerated values in a .NET 4.0 project:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |
(SecurityProtocolType)768 | (SecurityProtocolType)3072;

Reference:

namespace System.Net
{
    [System.Flags]
    public enum SecurityProtocolType
    {
       Ssl3 = 48,
       Tls = 192,
       Tls11 = 768,
       Tls12 = 3072,
    }
}

If you attempt the hack on an environment with ONLY .NET 4.0 installed, you will get the exception:

Unhandled Exception: System.NotSupportedException: The requested security protocol is not supported. at System.Net.ServicePointManager.set_SecurityProtocol(SecurityProtocolType v alue)

However, I wouldn't recommend this "hack" since a future patch, etc. may break it.*

Therefore, I've decided the best route to remove support for SSLv3 is to:

  1. Upgrade all applications to .NET 4.5
  2. Add the following to boostrapping code to override the default and future proof it:

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

*Someone correct me if this hack is wrong, but initial tests I see it works

How to export specific request to file using postman?

Thanks to the previous answers you knew how to save/download a request.

For people who are asking for a way to save/export the response you can use the arrow beside the "Send" button, click "Send and Download" to get the response in .json

enter image description here

How to Update Date and Time of Raspberry Pi With out Internet

Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.

This is how it works:

  1. Type sudo raspi-config in the Raspberry Pi command line
  2. Internationalization options
  3. Change Time Zone
  4. Select geographical area
  5. Select city or region
  6. Reboot your pi

Next thing you can set time using this command

sudo date -s "Mon Aug  12 20:14:11 UTC 2014"

More about data and time

man date

When Pi is connected to computer should have to manually set data and time

Fatal error: Class 'ZipArchive' not found in

1) You should require your file with ZipArchive file.

require 'path/to/file/ZipArchive.php';

2) Or use __autoload method of class. In PHP 5 it is a greate method __autoload().

function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1(); // creating an object without require.

http://www.php.net/manual/en/language.oop5.autoload.php

Xcode 9 error: "iPhone has denied the launch request"

I attentively read all answers but they don't help me. My solution:

  1. Go to Xcode preferences, select accounts (? + ,)
  2. Select your Apple ID, choose team and click Manage Certificates
  3. In Pop up menu in bottom left corner click + button and select iOS Development, then click done and close popup
  4. Try to relaunch application, now it's should fine.

How to implement a confirmation (yes/no) DialogPreference?

Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below

intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
    Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);

    intentClearCookies.setIntent(clearcookies);
    intentClearCookies.setTitle(R.string.ClearCookies);
    intentClearCookies.setEnabled(true);
    launchPrefCat.addPreference(intentClearCookies);

And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.

public class ClearCookies extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    showDialog();
}

/**
 * @throws NotFoundException
 */
private void showDialog() throws NotFoundException {
    new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.ClearCookies))
            .setMessage(
                    getResources().getString(R.string.ClearCookieQuestion))
            .setIcon(
                    getResources().getDrawable(
                            android.R.drawable.ic_dialog_alert))
            .setPositiveButton(
                    getResources().getString(R.string.PostiveYesButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here

                        }
                    })
            .setNegativeButton(
                    getResources().getString(R.string.NegativeNoButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here
                        }
                    }).show();
}}

As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.

Java code for getting current time

System.currentTimeMillis()

everything else works off that.. eg new Date() calls System.currentTimeMillis().

Remove quotes from a character vector in R

Just try noquote(a)

noquote("a")

[1] a

Can I pass parameters in computed properties in Vue.Js

Yes methods are there for using params. Like answers stated above, in your example it's best to use methods since execution is very light.

Only for reference, in a situation where the method is complex and cost is high, you can cache the results like so:

data() {
    return {
        fullNameCache:{}
    };
}

methods: {
    fullName(salut) {
        if (!this.fullNameCache[salut]) {
            this.fullNameCache[salut] = salut + ' ' + this.firstName + ' ' + this.lastName;
        }
        return this.fullNameCache[salut];
    }
}

note: When using this, watchout for memory if dealing with thousands

How to get html table td cell value by JavaScript?

This is my solution

var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
    console.log("My contents is \"" + cells[i].innerHTML + "\"");
}

How to easily resize/optimize an image size with iOS?

Best way to scale images without losing the aspect ratio (i.e. without stretching the imgage) is to use this method:

//to scale images without changing aspect ratio
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {

    float width = newSize.width;
    float height = newSize.height;

    UIGraphicsBeginImageContext(newSize);
    CGRect rect = CGRectMake(0, 0, width, height);

    float widthRatio = image.size.width / width;
    float heightRatio = image.size.height / height;
    float divisor = widthRatio > heightRatio ? widthRatio : heightRatio;

    width = image.size.width / divisor;
    height = image.size.height / divisor;

    rect.size.width  = width;
    rect.size.height = height;

    //indent in case of width or height difference
    float offset = (width - height) / 2;
    if (offset > 0) {
        rect.origin.y = offset;
    }
    else {
        rect.origin.x = -offset;
    }

    [image drawInRect: rect];

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return smallImage;

}

Add this method to your Utility class so you can use it throughout your project, and access it like so:

xyzImageView.image = [Utility scaleImage:yourUIImage toSize:xyzImageView.frame.size];

This method takes care of scaling while maintaining aspect ratio. It also adds indents to the image in case the scaled down image has more width than height (or vice versa).

Get HTML code from website in C#

Getting HTML code from a website. You can use code like this.

string urlAddress = "http://google.com";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;

  if (String.IsNullOrWhiteSpace(response.CharacterSet))
     readStream = new StreamReader(receiveStream);
  else
     readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

  string data = readStream.ReadToEnd();

  response.Close();
  readStream.Close();
}

This will give you the returned HTML code from the website. But find text via LINQ is not that easy. Perhaps it is better to use regular expression but that does not play well with HTML code

Are vectors passed to functions by value or by reference in C++

void foo(vector<int> test)

vector would be passed by value in this.

You have more ways to pass vectors depending on the context:-

1) Pass by reference:- This will let function foo change your contents of the vector. More efficient than pass by value as copying of vector is avoided.

2) Pass by const-reference:- This is efficient as well as reliable when you don't want function to change the contents of the vector.

Python, compute list difference

You can do a

list(set(A)-set(B))

and

list(set(B)-set(A))

Show Hide div if, if statement is true

<?php
$divStyle=''; // show div

// add condition
if($variable == '1'){
  $divStyle='style="display:none;"'; //hide div
}

print'<div '.$divStyle.'>Div to hide</div>';
?>

Real-world examples of recursion

Methods for finding a square root are recursive. Useful for calculating distances in the real world.

How can I make a clickable link in an NSAttributedString?

If you want to use the NSLinkAttributeName in a UITextView, then you may consider using the AttributedTextView library. It's a UITextView subclass that makes it very easy to handle these. For more info see: https://github.com/evermeer/AttributedTextView

You can make any part of the text interact like this (where textView1 is a UITextView IBoutlet):

textView1.attributer =
    "1. ".red
    .append("This is the first test. ").green
    .append("Click on ").black
    .append("evict.nl").makeInteract { _ in
        UIApplication.shared.open(URL(string: "http://evict.nl")!, options: [:], completionHandler: { completed in })
    }.underline
    .append(" for testing links. ").black
    .append("Next test").underline.makeInteract { _ in
        print("NEXT")
    }
    .all.font(UIFont(name: "SourceSansPro-Regular", size: 16))
    .setLinkColor(UIColor.purple) 

And for handling hashtags and mentions you can use code like this:

textView1.attributer = "@test: What #hashtags do we have in @evermeer #AtributedTextView library"
    .matchHashtags.underline
    .matchMentions
    .makeInteract { link in
        UIApplication.shared.open(URL(string: "https://twitter.com\(link.replacingOccurrences(of: "@", with: ""))")!, options: [:], completionHandler: { completed in })
    }

For homebrew mysql installs, where's my.cnf?

I believe the answer is no. Installing one in ~/.my.cnf or /usr/local/etc seems to be the preferred solution.

MySql Error: 1364 Field 'display_name' doesn't have default value

MySQL is most likely in STRICT mode.

Try running SET GLOBAL sql_mode='' or edit your my.cnf to make sure you aren't setting STRICT_ALL_TABLES or the like.

What is the difference between new/delete and malloc/free?

1.new syntex is simpler than malloc()

2.new/delete is a operator where malloc()/free() is a function.

3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.

4.we can change new/delete meaning in program with the help of operator overlading.

Check if any ancestor has a class using jQuery

You can use parents method with specified .class selector and check if any of them matches it:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

You can try,

<div asp-validation-summary="All" class="text-danger"></div>

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

How do I encrypt and decrypt a string in python?

For Encryption

  def encrypt(my_key=KEY, my_iv=IV, my_plain_text=PLAIN_TEXT): 

       key = binascii.unhexlify('ce975de9294067470d1684442555767fcb007c5a3b89927714e449c3f66cb2a4')
       iv = binascii.unhexlify('9aaecfcf7e82abb8118d8e567d42ee86')

       padder = PKCS7Padder()
       padded_text = padder.encode(my_plain_text)

      encryptor = AES.new(key, AES.MODE_CBC, iv, segment_size=128)  # Initialize encryptor
      result = encryptor.encrypt(padded_text)  

     return {
         "plain": my_plain_text,
         "key": binascii.hexlify(key),
         "iv": binascii.hexlify(iv),
         "ciphertext": result
}

Vertical Align text in a Label

The vertical-align style is used in table cells, so that won't do anything for you here.

To align the labels to the input boxes, you can use line-height:

line-height: 25px;

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Why isn't textarea an input[type="textarea"]?

I realize this is an older post, but thought this might be helpful to anyone wondering the same question:

While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.

As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.

How do I push a local Git branch to master branch in the remote?

As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .

Switch to branch ‘master’:

$ git checkout master

Merge from local repo to master:

$ git merge --no-ff FEATURE/<branch_Name>

Push to master:

$ git push

Turn a single number into single digits Python

Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n first):

>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]

Updating this after many years in response to comments of this not working for powers of 10:

[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]

The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.

In [32]: n = 43

In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]

In [34]: n = 1000

In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]

OpenCV - Apply mask to a color image

The other methods described assume a binary mask. If you want to use a real-valued single-channel grayscale image as a mask (e.g. from an alpha channel), you can expand it to three channels and then use it for interpolation:

assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
assert len(foreground_rgb.shape) == 3
assert len(background_rgb.shape) == 3

alpha3 = np.stack([mask]*3, axis=2)
blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb

Note that mask needs to be in range 0..1 for the operation to succeed. It is also assumed that 1.0 encodes keeping the foreground only, while 0.0 means keeping only the background.

If the mask may have the shape (h, w, 1), this helps:

alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))

Here np.atleast_3d(mask) makes the mask (h, w, 1) if it is (h, w) and np.squeeze(...) reshapes the result from (h, w, 3, 1) to (h, w, 3).

Convert String to java.util.Date

java.time

While in 2010, java.util.Date was the class we all used (toghether with DateFormat and Calendar), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss");

        String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14";
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter);
        System.out.println("output here: " + dateTime);

Output is:

output here: 2010-04-29T13:00:14

What went wrong in your code?

The combination of uppercase HH and aaa in your format pattern strings does not make much sense since HH is for hour of day, rendering the AM/PM marker from aaa superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat or the modern DateTimeFormatter:

'aaa' should not be used, if you use 'aaa' then specify 'hh'

Lowercase hh is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.

Other tips

  • In your database, since I understand that SQLite hasn’t got a built-in datetime type, use the standard ISO 8601 format and store time in UTC, for example 2010-04-29T07:30:14Z (the modern Instant class parses and formats such strings as its default, that is, without any explicit formatter).
  • Don’t use an offset such as GMT+05:30 for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.
  • If you wanted to use the outdated DateFormat, its parse method returns a Date, so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

pytest cannot import module while python can

Simply put an empty conftest.py file in the project root directory, because when pytest discovers a conftest.py, it modifies sys.path so it can import stuff from the conftest module. A general directory structure can be:

Root
+-- conftest.py
+-- module1
¦   +-- __init__.py
¦   +-- sample.py
+-- tests
    +-- test_sample.py

Java Date vs Calendar

Date is a simpler class and is mainly there for backward compatibility reasons. If you need to set particular dates or do date arithmetic, use a Calendar. Calendars also handle localization. The previous date manipulation functions of Date have since been deprecated.

Personally I tend to use either time in milliseconds as a long (or Long, as appropriate) or Calendar when there is a choice.

Both Date and Calendar are mutable, which tends to present issues when using either in an API.

datetime dtypes in pandas read_csv

There is a parse_dates parameter for read_csv which allows you to define the names of the columns you want treated as dates or datetimes:

date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

Fairly new to using PowerShell, think I might be able to help. Could you try this?

I believe you're not getting the correct parameters to your script block:

param([string]$one, [string]$two)
$res = Invoke-Command -Credential $migratorCreds -ScriptBlock {Get-LocalUsers -parentNodeXML $args[0] -migratorUser $args[1] } -ArgumentList $xmlPRE, $migratorCreds

Input jQuery get old value before onchange and get value after on change

my solution is here

function getVal() {
    var $numInput =  $('input');
    var $inputArr = [];
    for(let i=0; i < $numInput.length ; i++ ) 
       $inputArr[$numInput[i].name] = $numInput[i].value;
    return $inputArr;
}
var $inNum =  getVal();
$('input').on('change', function() {
    // inNum is last Val
    $inNum =  getVal(); 
    // in here we update value of input
    let $val = this.value;      
});

How to sum a variable by group

You could use the function group.sum from package Rfast.

Category <- Rfast::as_integer(Category,result.sort=FALSE) # convert character to numeric. R's as.numeric produce NAs.
result <- Rfast::group.sum(Frequency,Category)
names(result) <- Rfast::Sort(unique(Category)
# 30 5 34

Rfast has many group functions and group.sum is one of them.

How do I tar a directory of files and folders without including the directory itself?

cd my_directory && tar -czvf ../my_directory.tar.gz $(ls -A) && cd ..

This one worked for me and it's include all hidden files without putting all files in a root directory named "." like in tomoe's answer :

Bootstrap Responsive Text Size

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

Less

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

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


h5{
    font-size: 1.4rem;
}       

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

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

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

def norm(vector):
    return sqrt(sum(x * x for x in vector))    

def cosine_similarity(vec_a, vec_b):
        norm_a = norm(vec_a)
        norm_b = norm(vec_b)
        dot = sum(a * b for a, b in zip(vec_a, vec_b))
        return dot / (norm_a * norm_b)

This method seems to be somewhat faster than using sklearn's implementation if you pass in one pair of vectors at a time.