Programs & Examples On #Stateflow

StateFlow is a toolbox from MathWorks for development of state machines

What is the best way to implement "remember me" for a website?

Investigating persistent sessions myself I have found that it's simply not worth the security risk. Use it if you absolutely have to, but you should consider such a session only weakly authenticated and force a new login for anything that could be of value to an attacker.

The reason being of course is that your cookies containing your persistent session are so easily stolen.

4 ways to steal your cookies (from a comment by Jens Roland on the page @splattne based his answer on):

  1. By intercepting it over an unsecure line (packet sniffing / session hijacking)
  2. By directly accessing the user's browser (via either malware or physical access to the box)
  3. By reading it from the server database (probably SQL Injection, but could be anything)
  4. By an XSS hack (or similar client-side exploit)

Best approach to real time http streaming to HTML5 video client

One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):

  • Set up an icecast server (could be on the same machine you web server is on or on the machine that receives the RTSP-stream from the cam)
  • On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):

    gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
    

=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm

jQuery bind/unbind 'scroll' event on $(window)

Very old question, but in case someone else stumbles across it, I would recommend trying:

$j("html, body").stop(true, true).animate({
        scrollTop: $j('#main').offset().top 
}, 300);

Passing Parameters JavaFX FXML

I realize this is a very old post and has some great answers already, but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.

In this example, we will use 5 files:

  1. Main.java - Simply used to start the application and call the first controller.
  2. Controller1.java - The controller for the first FXML layout.
  3. Controller2.java - The controller for the second FXML layout.
  4. Layout1.fxml - The FXML layout for the first scene.
  5. Layout2.fxml - The FXML layout for the second scene.

All files are listed in their entirety at the bottom of this post.

The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.

The Program Flow:

  • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.
  • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.
  • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.

This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.

The code itself is also commented with some details of what is happening and how.

THE CODE

Main.java:

import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Create the first controller, which loads Layout1.fxml within its own constructor
        Controller1 controller1 = new Controller1();

        // Show the new stage
        controller1.showStage();

    }
}

Controller1.java:

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller1 {

    // Holds this controller's Stage
    private final Stage thisStage;

    // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
    @FXML
    private TextField txtToSecondController;
    @FXML
    private Button btnOpenLayout2;
    @FXML
    private Label lblFromController2;

    public Controller1() {

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

            // Set this class as the controller
            loader.setController(this);

            // Load the scene
            thisStage.setScene(new Scene(loader.load()));

            // Setup the window/stage
            thisStage.setTitle("Passing Controllers Example - Layout1");

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

    /**
     * Show the stage that was loaded in the constructor
     */
    public void showStage() {
        thisStage.showAndWait();
    }

    /**
     * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
     */
    @FXML
    private void initialize() {

        // Add an action for the "Open Layout2" button
        btnOpenLayout2.setOnAction(event -> openLayout2());
    }

    /**
     * Performs the action of loading and showing Layout2
     */
    private void openLayout2() {

        // Create the second controller, which loads its own FXML file. We pass a reference to this controller
        // using the keyword [this]; that allows the second controller to access the methods contained in here.
        Controller2 controller2 = new Controller2(this);

        // Show the new stage/window
        controller2.showStage();

    }

    /**
     * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
     */
    public String getEnteredText() {
        return txtToSecondController.getText();
    }

    /**
     * Allows other controllers to set the text of this layout's Label
     */
    public void setTextFromController2(String text) {
        lblFromController2.setText(text);
    }
}

Controller2.java:

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller2 {

    // Holds this controller's Stage
    private Stage thisStage;

    // Will hold a reference to the first controller, allowing us to access the methods found there.
    private final Controller1 controller1;

    // Add references to the controls in Layout2.fxml
    @FXML
    private Label lblFromController1;
    @FXML
    private TextField txtToFirstController;
    @FXML
    private Button btnSetLayout1Text;

    public Controller2(Controller1 controller1) {
        // We received the first controller, now let's make it usable throughout this controller.
        this.controller1 = controller1;

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

            // Set this class as the controller
            loader.setController(this);

            // Load the scene
            thisStage.setScene(new Scene(loader.load()));

            // Setup the window/stage
            thisStage.setTitle("Passing Controllers Example - Layout2");

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

    /**
     * Show the stage that was loaded in the constructor
     */
    public void showStage() {
        thisStage.showAndWait();
    }

    @FXML
    private void initialize() {

        // Set the label to whatever the text entered on Layout1 is
        lblFromController1.setText(controller1.getEnteredText());

        // Set the action for the button
        btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
    }

    /**
     * Calls the "setTextFromController2()" method on the first controller to update its Label
     */
    private void setTextOnLayout1() {
        controller1.setTextFromController2(txtToFirstController.getText());
    }

}

Layout1.fxml:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
    <VBox alignment="CENTER" spacing="10.0">
        <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
            <Label text="Enter Text:"/>
            <TextField fx:id="txtToSecondController"/>
            <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
        </HBox>
        <VBox alignment="CENTER">
            <Label text="Text From Controller2:"/>
            <Label fx:id="lblFromController2" text="Nothing Yet!"/>
        </VBox>
    </VBox>
</AnchorPane>

Layout2.fxml:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
    <VBox alignment="CENTER" spacing="10.0">
        <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
        <VBox alignment="CENTER">
            <Label text="Text From Controller1:"/>
            <Label fx:id="lblFromController1" text="Nothing Yet!"/>
        </VBox>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
            <Label text="Enter Text:"/>
            <TextField fx:id="txtToFirstController"/>
            <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
        </HBox>
    </VBox>
</AnchorPane>

How to compare oldValues and newValues on React Hooks useEffect?

Here's a custom hook that I use which I believe is more intuitive than using usePrevious.

import { useRef, useEffect } from 'react'

// useTransition :: Array a => (a -> Void, a) -> Void
//                              |_______|  |
//                                  |      |
//                              callback  deps
//
// The useTransition hook is similar to the useEffect hook. It requires
// a callback function and an array of dependencies. Unlike the useEffect
// hook, the callback function is only called when the dependencies change.
// Hence, it's not called when the component mounts because there is no change
// in the dependencies. The callback function is supplied the previous array of
// dependencies which it can use to perform transition-based effects.
const useTransition = (callback, deps) => {
  const func = useRef(null)

  useEffect(() => {
    func.current = callback
  }, [callback])

  const args = useRef(null)

  useEffect(() => {
    if (args.current !== null) func.current(...args.current)
    args.current = deps
  }, deps)
}

You'd use useTransition as follows.

useTransition((prevRate, prevSendAmount, prevReceiveAmount) => {
  if (sendAmount !== prevSendAmount || rate !== prevRate && sendAmount > 0) {
    const newReceiveAmount = sendAmount * rate
    // do something
  } else {
    const newSendAmount = receiveAmount / rate
    // do something
  }
}, [rate, sendAmount, receiveAmount])

Hope that helps.

When do you use the "this" keyword?

Any time you need a reference to the current object.

One particularly handy scenario is when your object is calling a function and wants to pass itself into it.

Example:

void onChange()
{
    screen.draw(this);
}

Clear text in EditText when entered

It's simple: declare the widget variables (editText, textView, button etc.) in class but initialize it in onCreate after setContentView.

The problem is when you try to access a widget of a layout first you have to declare the layout. Declaring the layout is setContentView. And when you initialize the widget variable via findViewById you are accessing the id of the widget in the main layout in the setContentView.

I hope you get it!

Run bash script from Windows PowerShell

You should put the script as argument for a *NIX shell you run, equivalent to the *NIXish

sh myscriptfile

Decimal number regular expression, where digit after decimal is optional

Try this regex:

\d+\.?\d*

\d+ digits before optional decimal
.? optional decimal(optional due to the ? quantifier)
\d* optional digits after decimal

join list of lists in python

If you need a list, not a generator, use list():

from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))

Hide text using css

To hide text from html use text-indent property in css

.classname {
 text-indent: -9999px;
 white-space: nowrap; 
}

/* for dynamic text you need to add white-space, so your applied css will not disturb. nowrap means text will never wrap to the next line, the text continues on the same line until a <br> tag is encountered

Open Form2 from Form1, close Form1 from Form2

This works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Hide()
    Form2.Show()

Java for loop syntax: "for (T obj : objects)"

It's called a for-each or enhanced for statement. See the JLS §14.14.2.

It's syntactic sugar provided by the compiler for iterating over Iterables and arrays. The following are equivalent ways to iterate over a list:

List<Foo> foos = ...;
for (Foo foo : foos)
{
    foo.bar();
}

// equivalent to:
List<Foo> foos = ...;
for (Iterator<Foo> iter = foos.iterator(); iter.hasNext();)
{
    Foo foo = iter.next();
    foo.bar();
}

and these are two equivalent ways to iterate over an array:

int[] nums = ...;
for (int num : nums)
{
    System.out.println(num);
}

// equivalent to:
int[] nums = ...;
for (int i=0; i<nums.length; i++)
{
    int num = nums[i];
    System.out.println(num);
}

Further reading

How to Force New Google Spreadsheets to refresh and recalculate?

Insert "checkbox". Every time you check or uncheck the box the sheet recalculates. If you put the text size for the checkbox at 2, the color at almost black and the cell shade to black, it becomes a button that recalculates.

Debugging in Maven?

Why not use the JPDA and attach to the launched process from a separate debugger process ? You should be able to specify the appropriate options in Maven to launch your process with the debugging hooks enabled. This article has more information.

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

How can I check for "undefined" in JavaScript?

If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined.

You can check the type of the variable:

if (typeof(something) != "undefined") ...

Sometimes you don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then you can just evalue the variable. Example:

if (something) {
  something(param);
}

How to fluently build JSON in Java?

You can use one of Java template engines. I love this method because you are separating your logic from the view.

Java 8+:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.9.6</version>
</dependency>

Java 6/7:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.8.18</version>
</dependency>

Example template file:

{{#items}}
Name: {{name}}
Price: {{price}}
  {{#features}}
  Feature: {{description}}
  {{/features}}
{{/items}}

Might be powered by some backing code:

public class Context {
  List<Item> items() {
    return Arrays.asList(
      new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
      new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
    );
  }

  static class Item {
    Item(String name, String price, List<Feature> features) {
      this.name = name;
      this.price = price;
      this.features = features;
    }
    String name, price;
    List<Feature> features;
  }

  static class Feature {
    Feature(String description) {
       this.description = description;
    }
    String description;
  }
}

And would result in:

Name: Item 1
Price: $19.99
  Feature: New!
  Feature: Awesome!
Name: Item 2
Price: $29.99
  Feature: Old.
  Feature: Ugly.

What does an exclamation mark before a cell reference mean?

If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.

As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).

edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p

How to access host port from docker container

This is an old question and had many answers, but none of those fit well enough to my context. In my case, the containers are very lean and do not contain any of the networking tools necessary to extract the host's ip address from within the container.

Also, usin the --net="host" approach is a very rough approach that is not applicable when one wants to have well isolated network configuration with several containers.

So, my approach is to extract the hosts' address at the host's side, and then pass it to the container with --add-host parameter:

$ docker run --add-host=docker-host:`ip addr show docker0 | grep -Po 'inet \K[\d.]+'` image_name

or, save the host's IP address in an environment variable and use the variable later:

$ DOCKERIP=`ip addr show docker0 | grep -Po 'inet \K[\d.]+'`
$ docker run --add-host=docker-host:$DOCKERIP image_name

And then the docker-host is added to the container's hosts file, and you can use it in your database connection strings or API URLs.

Getting multiple keys of specified value of a generic Dictionary?

Can't you create a subclass of Dictionary which has that functionality?


    public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
    {
        private Dictionary < TValue, TKey > _keys;

        public TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set 
            { 
                base[key] = value;
                _keys[value] = key;
            }
        }

        public MyDict()
        {
            _keys = new Dictionary < TValue, TKey >();
        }

        public TKey GetKeyFromValue(TValue value)
        {
            return _keys[value];
        }
    }

EDIT: Sorry, didn't get code right first time.

Get JSON object from URL

// Get the string from the URL
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452');

// Decode the JSON string into an object
$obj = json_decode($json);

// In the case of this input, do key and array lookups to get the values
var_dump($obj->results[0]->formatted_address);

What is the use of printStackTrace() method in Java?

See image here

printStackTrace() tells at what line you are getting error any why are you getting error.

Example:

 java.lang.ArithmeticException: / by zero
    at MinNumber.main(MinNumber.java:8) 

git ahead/behind info between master and branch?

Here's a trick I found to compare two branches and show how many commits each branch is ahead of the other (a more general answer on your question 1):

For local branches: git rev-list --left-right --count master...test-branch

For remote branches: git rev-list --left-right --count origin/master...origin/test-branch

This gives output like the following:

1 7

This output means: "Compared to master, test-branch is 7 commits ahead and 1 commit behind."

You can also compare local branches with remote branches, e.g. origin/master...master to find out how many commits the local master branch is ahead/behind its remote counterpart.

Avoid dropdown menu close on click inside

The simplest working solution for me is:

  • adding keep-open class to elements that should not cause dropdown closing
  • and this piece of code do the rest:
$('.dropdown').on('click', function(e) {
    var target = $(e.target);
    var dropdown = target.closest('.dropdown');
    return !dropdown.hasClass('open') || !target.hasClass('keep-open');
});

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

How can I catch all the exceptions that will be thrown through reading and writing a file?

It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.

For most file operations, IOException is the root exception. Better to catch that, instead.

Cross compile Go on OSX?

for people who need CGO enabled and cross compile from OSX targeting windows

I needed CGO enabled while compiling for windows from my mac since I had imported the https://github.com/mattn/go-sqlite3 and it needed it. Compiling according to other answers gave me and error:

/usr/local/go/src/runtime/cgo/gcc_windows_amd64.c:8:10: fatal error: 'windows.h' file not found

If you're like me and you have to compile with CGO. This is what I did:

1.We're going to cross compile for windows with a CGO dependent library. First we need a cross compiler installed like mingw-w64

brew install mingw-w64

This will probably install it here /usr/local/opt/mingw-w64/bin/.

2.Just like other answers we first need to add our windows arch to our go compiler toolchain now. Compiling a compiler needs a compiler (weird sentence) compiling go compiler needs a separate pre-built compiler. We can download a prebuilt binary or build from source in a folder eg: ~/Documents/go now we can improve our Go compiler, according to top answer but this time with CGO_ENABLED=1 and our separate prebuilt compiler GOROOT_BOOTSTRAP(Pooya is my username):

cd /usr/local/go/src
sudo GOOS=windows GOARCH=amd64 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean
sudo GOOS=windows GOARCH=386 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean

3.Now while compiling our Go code use mingw to compile our go file targeting windows with CGO enabled:

GOOS="windows" GOARCH="386" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/i686-w64-mingw32-gcc" go build hello.go
GOOS="windows" GOARCH="amd64" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc" go build hello.go

Code formatting shortcuts in Android Studio for Operation Systems

Just select the code and

  • on Windows do Ctrl + Alt + L

  • on Linux do Ctrl + Super + Alt + L

  • on Mac do CMD + Alt + L

This solution from junaidp

What does "select count(1) from table_name" on any database tables mean?

SELECT COUNT(1) from <table name>

should do the exact same thing as

SELECT COUNT(*)  from <table name>

There may have been or still be some reasons why it would perform better than SELECT COUNT(*)on some database, but I would consider that a bug in the DB.

SELECT COUNT(col_name) from <table name>

however has a different meaning, as it counts only the rows with a non-null value for the given column.

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

Probably there are many processes that use sources compiled, could be a server, an old maven instruction or IDE. Sure terminate all processes, stop the server and then execute maven again. If the problem persists, you should close java.exe process.

Regards!

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

Without opening Xcode:

open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app/

Simple way to query connected USB devices info in Python?

For a system with legacy usb coming back and libusb-1.0, this approach will work to retrieve the various actual strings. I show the vendor and product as examples. It can cause some I/O, because it actually reads the info from the device (at least the first time, anyway.) Some devices don't provide this information, so the presumption that they do will throw an exception in that case; that's ok, so we pass.

import usb.core
import usb.backend.libusb1

busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        if dev != None:
            try:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                stx = '%6d %6d: '+str(xdev._manufacturer).strip()+' = '+str(xdev._product).strip()
                print stx % (dev.idVendor,dev.idProduct)
            except:
                pass

MySQL error - #1062 - Duplicate entry ' ' for key 2

As it was said you have a unique index.

However, when I added most of the list yesterday I didn't get this error once even though a lot of the entries I added yesterday have a blank cell in column 2 as well. Whats going on?

That means that all these entries contain value NULL, not empty string ''. Mysql lets you have multiple NULL values in unique fields.

Finish all activities at a time

For API 16+, use

finishAffinity();

For lower, use

ActivityCompat.finishAffinity(YourActivity.this)

Redirect to Action in another controller

This should work

return RedirectToAction("actionName", "controllerName", null);

Git undo changes in some files

Why can't you simply mark what changes you want to have in a commit using "git add <file>" (or even "git add --interactive", or "git gui" which has option for interactive comitting), and then use "git commit" instead of "git commit -a"?

In your situation (for your example) it would be:

prompt> git add B
prompt> git commit

Only changes to file B would be comitted, and file A would be left "dirty", i.e. with those print statements in the working area version. When you want to remove those print statements, it would be enought to use

prompt> git reset A

or

prompt> git checkout HEAD -- A

to revert to comitted version (version from HEAD, i.e. "git show HEAD:A" version).

UINavigationBar custom back button without title

This is how I do it and the simplest, works and most clear way to do it.

This works if embed on Navigation Controller

Swift 3

In viewDidLoad I add this to the View Controller you want the back button to be just arrow.

if let topItem = self.navigationController?.navigationBar.topItem {
   topItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}

The difference of this to @Kyle Begeman's answer is that you call this on the view controller that you want the back button to be just arrow, not on the pushing stack view controller.

c# Best Method to create a log file

Instead of using log4net which is an external library I have created my own simple class, highly customizable and easy to use (edit YOURNAMESPACEHERE with the namespace that you need).

CONSOLE APP

using System;
using System.IO;

namespace YOURNAMESPACEHERE
{
    enum LogEvent
    {
        Info = 0,
        Success = 1,
        Warning = 2,
        Error = 3
    }

    internal static class Log
    {
        private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
        private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";

        internal static void Write(LogEvent Level, string Message, bool ShowConsole = true, bool WritelogFile = true)
        {
            string Event = string.Empty;
            ConsoleColor ColorEvent = Console.ForegroundColor;

            switch (Level)
            {
                case LogEvent.Info:
                    Event = "INFO";
                    ColorEvent = ConsoleColor.White;
                    break;
                case LogEvent.Success:
                    Event = "SUCCESS";
                    ColorEvent = ConsoleColor.Green;
                    break;
                case LogEvent.Warning:
                    Event = "WARNING";
                    ColorEvent = ConsoleColor.Yellow;
                    break;
                case LogEvent.Error:
                    Event = "ERROR";
                    ColorEvent = ConsoleColor.Red;
                    break;
            }

            if (ShowConsole)
            {
                Console.ForegroundColor = ColorEvent;
                Console.WriteLine(" [{0}] => {1}", DateTime.Now.ToString("HH:mm:ss"), Message);
                Console.ResetColor();
            }

            if (WritelogFile)
            {
                if (!Directory.Exists(LogPath))
                    Directory.CreateDirectory(LogPath);

                File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
            }
        }
    }
}

NO CONSOLE APP (ONLY LOG)

using System;
using System.IO;

namespace YOURNAMESPACEHERE
{
    enum LogEvent
    {
        Info = 0,
        Success = 1,
        Warning = 2,
        Error = 3
    }

internal static class Log
{
    private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
    private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";

    internal static void Write(LogEvent Level, string Message)
    {
        string Event = string.Empty;

        switch (Level)
        {
            case LogEvent.Info:
                Event = "INFO";
                break;
            case LogEvent.Success:
                Event = "SUCCESS";
                break;
            case LogEvent.Warning:
                Event = "WARNING";
                break;
            case LogEvent.Error:
                Event = "ERROR";
                break;
        }

        if (!Directory.Exists(LogPath))
            Directory.CreateDirectory(LogPath);

        File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
    }
}

Usage:

CONSOLE APP

Log.Write(LogEvent.Info, "Test message"); // It will print an info in your console, also will save a copy of this print in a .log file.
Log.Write(LogEvent.Warning, "Test message", false); // It will save the print as warning only in your .log file.
Log.Write(LogEvent.Error, "Test message", true, false); // It will print an error only in your console.

NO CONSOLE APP (ONLY LOG)

Log.Write(LogEvent.Info, "Test message"); // It will print an info in your .log file.

Chrome DevTools Devices does not detect device when plugged in

Samsung Note 8 User here - all i had to do was

  1. Enable USB Debugging on the phone.
  2. Install and run the "ADB and Fastboot" tool
  3. Input command adb devices in the adb prompt.
  4. Go to chrome://inspect/#devices and the device shows up.

After that i got a message on my phone and chrome recognized the phone.

simple vba code gives me run time error 91 object variable or with block not set

You need Set with objects:

 Set rng = Sheet8.Range("A12")

Sheet8 is fine.

 Sheet1.[a1]

How can I access an internal class from an external assembly?

I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.

Saying that there is a way to allow "Friend" assemblies access to internals:

In the AssemblyInfo.cs file of the project you add a line for each assembly.

[assembly: InternalsVisibleTo("name of assembly here")]

this info is available here.

Hope this helps.

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

How to get the real and total length of char * (char array)?

If the char * is 0-terminated, you can use strlen

Otherwise, there is no way to determine that information

How can I insert new line/carriage returns into an element.textContent?

None of the above solutions worked for me. I was trying to add a line feed and additional text to a <p> element. I typically use Firefox, but I do need browser compatibility. I read that only Firefox supports the textContent property, only Internet Explorer supports the innerText property, but both support the innerHTML property. However, neither adding <br /> nor \n nor \r\n to any of those properties resulted in a new line. The following, however, did work:

<html>
<body>
<script type="text/javascript">
  function modifyParagraph() {

  var p;
  p=document.getElementById("paragraphID");
  p.appendChild(document.createElement("br"));
  p.appendChild(document.createTextNode("Additional text."));
}    
</script>

<p id="paragraphID">Original text.</p>

<input type="button" id="pbutton" value="Modify Paragraph" onClick="modifyParagraph()" />
</body>
</html>

What is the difference between re.search and re.match?

re.match attempts to match a pattern at the beginning of the string. re.search attempts to match the pattern throughout the string until it finds a match.

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

How do I find out what License has been applied to my SQL Server installation?

I presume you mean via SSMS?

For a SQL Server Instance:

SELECT SERVERPROPERTY('productversion'), 
       SERVERPROPERTY ('productlevel'), 
       SERVERPROPERTY ('edition')

For a SQL Server Installation:

Select @@Version

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

Setting timezone to UTC (0) in PHP

Is 'UTC' a valid timezone identifier on your system?

<?php
if (date_default_timezone_set('UTC')){
    echo "UTC is a valid time zone";
}else{
    echo "The system doesn't know WTFUTC.  Maybe try updating tzinfo with your package manager?";
}

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

Android Studio installation on Windows 7 fails, no JDK found

On Windows 10, restarting the installer and running as admin worked for me.

CSS Font "Helvetica Neue"

It's a default font on Macs, but rare on PCs. Since it's not technically web-safe, some people may have it and some people may not. If you want to use a font like that, without using @font-face, you may want to write it out several different ways because it might not work the same for everyone.

I like using a font stack that touches on all bases like this:

font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", 
  Helvetica, Arial, "Lucida Grande", sans-serif;

This recommended font-family stack is further described in this CSS-Tricks snippet Better Helvetica which uses a font-weight: 300; as well.

Check if a string is not NULL or EMPTY

As in many other programming and scripting languages you can do so by adding ! in front of the condition

if (![string]::IsNullOrEmpty($version))
{
    $request += "/" + $version
}

Check if a Bash array contains a value

Here is my take on this problem. Here is the short version:

function arrayContains() {
        local haystack=${!1}
        local needle="$2"
        printf "%s\n" ${haystack[@]} | grep -q "^$needle$"
}

And the long version, which I think is much easier on the eyes.

# With added utility function.
function arrayToLines() {
        local array=${!1}
        printf "%s\n" ${array[@]}
}

function arrayContains() {
        local haystack=${!1}
        local needle="$2"
        arrayToLines haystack[@] | grep -q "^$needle$"
}

Examples:

test_arr=("hello" "world")
arrayContains test_arr[@] hello; # True
arrayContains test_arr[@] world; # True
arrayContains test_arr[@] "hello world"; # False
arrayContains test_arr[@] "hell"; # False
arrayContains test_arr[@] ""; # False

How can I initialize a MySQL database with schema in a Docker container?

After to struggle a little bit with that, take a look the Dockerfile using named volumes (db-data). It's important declare a plus at final part, where I mentioned that volume is [external]

All worked great this way!

version: "3"

services:

  database:
    image: mysql:5.7
    container_name: mysql
    ports:
      - "3306:3306"
    volumes:
      - db-data:/docker-entrypoint-initdb.d
    environment:
      - MYSQL_DATABASE=sample
      - MYSQL_ROOT_PASSWORD=root

volumes:
  db-data:
    external: true

Use of exit() function

Use process.h instead of stdlib and iostream... It will work 100%.

How to keep the local file or the remote file during merge using Git and the command line?

You can as well do:

git checkout --theirs /path/to/file

to keep the remote file, and:

git checkout --ours /path/to/file

to keep local file.

Then git add them and everything is done.

Edition: Keep in mind that this is for a merge scenario. During a rebase --theirs refers to the branch where you've been working.

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

Go to Matching Brace in Visual Studio?

On my Portuguese keyboard and SO with EN VS, it's CTRL + « to navigate to matching brace and CTRL + SHIFT + « if you intend to select the inner code.

What does <T> denote in C#

This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx

An example of this is to make a collection of items of a specific type.

class MyArray<T>
{
    T[] array = new T[10];

    public T GetItem(int index)
    {
        return array[index];
    }
}

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

SELECT INTO a table variable in T-SQL

The purpose of SELECT INTO is (per the docs, my emphasis)

To create a new table from values in another table

But you already have a target table! So what you want is

The INSERT statement adds one or more new rows to a table

You can specify the data values in the following ways:

...

By using a SELECT subquery to specify the data values for one or more rows, such as:

  INSERT INTO MyTable 
 (PriKey, Description)
        SELECT ForeignKey, Description
        FROM SomeView

And in this syntax, it's allowed for MyTable to be a table variable.

Compare dates in MySQL

You can try below query,

select * from players
where 
    us_reg_date between '2000-07-05'
and
    DATE_ADD('2011-11-10',INTERVAL 1 DAY)

An efficient way to Base64 encode a byte array?

Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[].

However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:

string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);

This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)

Where does Chrome store extensions?

For my Mac, extensions were here:

~/Library/Application Support/Google/Chrome/Default/Extensions/

if you go to chrome://extensions you'll find the "ID" of each extension. That is going to be a directory within Extensions directory. It is there you'll find all of the extension's files.

If file exists then delete the file

fileExists() is a method of FileSystemObject, not a global scope function.

You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.

Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.

So you could use the block:

if NOT fso.FileExists(newname) Then  

    file.move fso.buildpath(OUT_PATH, newname)           

else

    fso.DeleteFile newname
    file.move fso.buildpath(OUT_PATH, newname)  

end if 

Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.

Rails: Why "sudo" command is not recognized?

Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions. Windows doesn't not have (need?) this.

Yes, windows don't have sudo on its terminal. Try using pip instead.

  1. Install pip using the steps here.
  2. type pip install [package name] on the terminal. In this case, it may be pdfkit or wkhtmltopdf.

Get all parameters from JSP page

The fastest way should be:

<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
    if (entry.getKey().startsWith("question")) {
        String[] values = entry.getValue();
        // etc.

Note that you can't do:

for (Map.Entry<String, String[]> entry : 
     request.getParameterMap().entrySet()) { // WRONG!

for reasons explained here.

How to get the size of a varchar[n] field in one SQL statement?

select column_name, data_type, character_maximum_length    
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'Table1'

How to correctly use the extern keyword in C

A very good article that I came about the extern keyword, along with the examples: http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

Though I do not agree that using extern in function declarations is redundant. This is supposed to be a compiler setting. So I recommend using the extern in the function declarations when it is needed.

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

If element is not clickable and overlay issue is ocuring we use arguments[0].click().

WebElement ele = driver.findElement(By.xpath("//div[@class='input-group-btn']/input")); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", ele);

Cannot deserialize the current JSON array (e.g. [1,2,3])

You can use this to solve your problem:

private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
    HttpClient webClient = new HttpClient();
    Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
    HttpResponseMessage response = await webClient.GetAsync(uri);
    var jsonString = await response.Content.ReadAsStringAsync();
    var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
    foreach (Student Student in _Data)
    {
        tb1.Text = Student.student_name;
    }
}

Editing specific line in text file in Python

you can use fileinput to do in place editing

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line

Sublime Text 2: How to delete blank/empty lines

There is a wonderful package (for Sublime 2 & 3) called 'Trimmer' which deletes empty lines. It also does many other useful things.

Refer this: https://packagecontrol.io/packages/Trimmer

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Fitting a density curve to a histogram in R

I had the same problem but Dirk's solution didn't seem to work. I was getting this warning messege every time

"prob" is not a graphical parameter

I read through ?hist and found about freq: a logical vector set TRUE by default.

the code that worked for me is

hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)

jquery Ajax call - data parameters are not being passed to MVC Controller action

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

How to pass the button value into my onclick event function?

You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test by passing this. Then in the function you can access the value like this:

function dosomething(element) {
  console.log(element.value);
}

Parse JSON response using jQuery

Try bellow code. This is help your code.

  $("#btnUpdate").on("click", function () {
            //alert("Alert Test");
            var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';
            $.ajax({
                type: "GET",
                url: url,
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    debugger;

                    $.each(result.callback, function (index, value) {
                        alert(index + ': ' + value.Name);
                    });
                },
                failure: function (result) { alert('Fail'); }
            });
        });

I could not access your url. Bellow error is shows

XMLHttpRequest cannot load http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:19829' is therefore not allowed access. The response had HTTP status code 501.

How to install MySQLi on MacOS

For mysqli on Docker's official php containers:

Tagged php versions that support mysqli may still not come with mysqli configured out of the box, You can install it with the docker-php-ext-install utility (see comment by Konstantin). This is built-in, but also available from the docker-php-extension-installer project.

They can be used to add mysqli either in a Dockerfile, for example:

FROM php:5.6.5-apache
COPY ./php.ini /usr/local/etc/php/
RUN docker-php-ext-install mysqli

or in a compose file that uses a generic php container and then injects mysqli installation as a setup step into command:

  web:
    image: php:5.6.5-apache
    volumes:
      - app:/var/www/html/
    ports:
      - "80:80"
    command:  >
      sh -c "docker-php-ext-install mysqli &&
             apache2-foreground"

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

How do I install PIL/Pillow for Python 3.6?

For python version 2.x you can simply use

  • pip install pillow

But for python version 3.X you need to specify

  • (sudo) pip3 install pillow

when you enter pip in bash hit tab and you will see what options you have

Exporting the values in List to excel

The most straightforward way (in my opinion) would be to simply put together a CSV file. If you want to get into formatting and actually writing to a *.xlsx file, there are more complicated solutions (and APIs) to do that for you.

Getting the folder name from a path

Simple & clean. Only uses System.IO.FileSystem - works like a charm:

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;

PowerShell: Create Local User Account

Another alternative is the old school NET USER commands:

NET USER username "password" /ADD

OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.

NET LOCALGROUP "group" "user" /add to set group membership.

Removing a non empty directory programmatically in C or C++

C++17 has <experimental\filesystem> which is based on the boost version.

Use std::experimental::filesystem::remove_all to remove recursively.

If you need more control, try std::experimental::filesystem::recursive_directory_iterator.

You can also write your own recursion with the non-resursive version of the iterator.

namespace fs = std::experimental::filesystem;
void IterateRecursively(fs::path path)
{
  if (fs::is_directory(path))
  {
    for (auto & child : fs::directory_iterator(path))
      IterateRecursively(child.path());
  }

  std::cout << path << std::endl;
}

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Installing lxml module in python

If you are encountering this issue on an Alpine based image try this :

apk add --update --no-cache g++ gcc libxml2-dev libxslt-dev python-dev libffi-dev openssl-dev make

// pip install -r requirements.txt

Assignment inside lambda expression in Python

There's no need to use a lambda, when you can remove all the null ones, and put one back if the input size changes:

input = [Object(name=""), Object(name="fake_name"), Object(name="")] 
output = [x for x in input if x.name]
if(len(input) != len(output)):
    output.append(Object(name=""))

How to check the installed version of React-Native

To see what version you have on your Mac(Window also can run that code.), run react-native -v and you should get something like this:

enter image description here

If you want to know what version your project is running, look in /node_modules/react-native/package.json and look for the version key:

enter image description here

How to include static library in makefile

Make sure that the -L option appears ahead of the -l option; the order of options in linker command lines does matter, especially with static libraries. The -L option specifies a directory to be searched for libraries (static or shared). The -lname option specifies a library which is with libmine.a (static) or libmine.so (shared on most variants of Unix, but Mac OS X uses .dylib and HP-UX used to use .sl). Conventionally, a static library will be in a file libmine.a. This is convention, not mandatory, but if the name is not in the libmine.a format, you cannot use the -lmine notation to find it; you must list it explicitly on the compiler (linker) command line.

The -L./libmine option says "there is a sub-directory called libmine which can be searched to find libraries". I can see three possibilities:

  1. You have such a sub-directory containing libmine.a, in which case you also need to add -lmine to the linker line (after the object files that reference the library).
  2. You have a file libmine that is a static archive, in which case you simply list it as a file ./libmine with no -L in front.
  3. You have a file libmine.a in the current directory that you want to pick up. You can either write ./libmine.a or -L . -lmine and both should find the library.

UITableViewCell, show delete button on swipe

I had a problem which I have just managed to solve so I am sharing it as it may help someone.

I have a UITableView and added the methods shown to enable swipe to delete:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
    }    
}

I am working on an update that allows me to put the table into edit mode and enables multiselect. To do that I added the code from Apple's TableMultiSelect sample. Once I got that working I found that my swipe the delete function had stopped working.

It turns out that adding the following line to viewDidLoad was the issue:

self.tableView.allowsMultipleSelectionDuringEditing = YES;

With this line in, the multiselect would work but the swipe to delete wouldn't. Without the line it was the other way around.

The fix:

Add the following method to your viewController:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    self.tableView.allowsMultipleSelectionDuringEditing = editing; 
    [super setEditing:editing animated:animated];
}

Then in your method that puts the table into editing mode (from a button press for example) you should use:

[self setEditing:YES animated:YES];

instead of:

[self.tableView setEditing:YES animated:YES];

This means that multiselect is only enabled when the table is in editing mode.

Remove property for all objects in array

i have tried with craeting a new object without deleting the coulmns in Vue.js.

let data =this.selectedContactsDto[];

//selectedContactsDto[] = object with list of array objects created in my project

console.log(data); let newDataObj= data.map(({groupsList,customFields,firstname, ...item }) => item); console.log("newDataObj",newDataObj);

Unable to create Android Virtual Device

Simply because CPU/ABI says "No system images installed for this target". You need to install system images.

In the Android SDK Manager check that you have installed "ARM EABI v7a System Image" (for each Android version from 4.0 and on you have to install a system image to be able to run a virtual device)

In your case only ARM system image exsits (Android 4.2). If you were running an older version, Intel has provided System Images (Intel x86 ATOM). You can check on the internet to see the comparison in performance between both.

In my case (see image below) I haven't installed a System Image for Android 4.2, whereas I have installed ARM and Intel System Images for 4.1.2

As long as I don't install the 4.2 System Image I would have the same problem as you.

UPDATE : This recent article Speeding Up the Android Emaulator on Intel Architectures explains how to use/install correctly the intel system images to speed up the emulator.

EDIT/FOLLOW UP

What I show in the picture is for Android 4.2, as it was the original question, but is true for every versions of Android.

Of course (as @RedPlanet said), if you are developing for MIPS CPU devices you have to install the "MIPS System Image".

Finally, as @SeanJA said, you have to restart eclipse to see the new installed images. But for me, I always restart a software which I updated to be sure it takes into account all the modifications, and I assume it is a good practice to do so.

enter image description here

What are the differences between .gitignore and .gitkeep?

.gitkeep isn’t documented, because it’s not a feature of Git.

Git cannot add a completely empty directory. People who want to track empty directories in Git have created the convention of putting files called .gitkeep in these directories. The file could be called anything; Git assigns no special significance to this name.

There is a competing convention of adding a .gitignore file to the empty directories to get them tracked, but some people see this as confusing since the goal is to keep the empty directories, not ignore them; .gitignore is also used to list files that should be ignored by Git when looking for untracked files.

How to "Open" and "Save" using java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Angular 4: How to include Bootstrap?

npm install --save bootstrap

afterwards, inside angular-cli.json (inside the project's root folder), find styles and add the bootstrap css file like this:

"styles": [
   "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   "styles.css"
],

UPDATE:
in angular 6+ angular-cli.json was changed to angular.json.

JavaScript math, round to two decimal places

A small variation on the accepted answer. toFixed(2) returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:

var discount = + ((price / listprice).toFixed(2));

Edited: I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to

var discount = Math.round(price / listprice * 100) / 100;

This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388

How do you roll back (reset) a Git repository to a particular commit?

git reset --hard <tag/branch/commit id>

Notes:

  • git reset without the --hard option resets the commit history, but not the files. With the --hard option the files in working tree are also reset. (credited user)

  • If you wish to commit that state so that the remote repository also points to the rolled back commit do: git push <reponame> -f (credited user)

Bootstrap select dropdown list placeholder

I think, the Dropdown box with a class and JQuery code to disable the first option for user to select, will work perfectly as Select Box placeholder.

<select class="selectboxclass">
   <option value="">- Please Select -</option>
   <option value="IN">India</option>
   <option value="US">America</option>
</select>

Make the first option disabled by JQuery.

<script>
$('select.selectboxclass option:first').attr('disabled', true);
</script>

This will make the first option of Dropdown as Placeholder and user will no longer able to select the first option.

Hope It helps!!

Resizable table columns with jQuery

So I started writing my own, just bare bones functionality for now, will be working on it next week... http://jsfiddle.net/ydTCZ/

Import regular CSS file in SCSS file?

I figured out an elegant, Rails-like way to do it. First, rename your .scss file to .scss.erb, then use syntax like this (example for highlight_js-rails4 gem CSS asset):

@import "<%= asset_path("highlight_js/github") %>";

Why you can't host the file directly via SCSS:

Doing an @import in SCSS works fine for CSS files as long as you explicitly use the full path one way or another. In development mode, rails s serves assets without compiling them, so a path like this works...

@import "highlight_js/github.css";

...because the hosted path is literally /assets/highlight_js/github.css. If you right-click on the page and "view source", then click on the link for the stylesheet with the above @import, you'll see a line in there that looks like:

@import url(highlight_js/github.css);

The SCSS engine translates "highlight_js/github.css" to url(highlight_js/github.css). This will work swimmingly until you decide to try running it in production where assets are precompiled have a hash injected into the file name. The SCSS file will still resolve to a static /assets/highlight_js/github.css that was not precompiled and doesn't exist in production.

How this solution works:

Firstly, by moving the .scss file to .scss.erb, we have effectively turned the SCSS into a template for Rails. Now, whenever we use <%= ... %> template tags, the Rails template processor will replace these snippets with the output of the code (just like any other template).

Stating asset_path("highlight_js/github") in the .scss.erb file does two things:

  1. Triggers the rake assets:precompile task to precompile the appropriate CSS file.
  2. Generates a URL that appropriately reflects the asset regardless of the Rails environment.

This also means that the SCSS engine isn't even parsing the CSS file; it's just hosting a link to it! So there's no hokey monkey patches or gross workarounds. We're serving a CSS asset via SCSS as intended, and using a URL to said CSS asset as Rails intended. Sweet!

Count number of occurrences of a pattern in a file (even on same line)

Ripgrep, which is a fast alternative to grep, has just introduced the --count-matches flag allowing counting each match in version 0.9 (I'm using the above example to stay consistent):

> echo afoobarfoobar | rg --count foo
1
> echo afoobarfoobar | rg --count-matches foo
2

As asked by OP, ripgrep allows for regex pattern as well (--regexp <PATTERN>). Also it can print each (line) match on a separate line:

> echo -e "line1foo\nline2afoobarfoobar" | rg foo
line1foo
line2afoobarfoobar

How to Split Image Into Multiple Pieces in Python

Here is a concise, pure-python solution that works in both python 3 and 2:

from PIL import Image

infile = '20190206-135938.1273.Easy8thRunnersHopefully.jpg'
chopsize = 300

img = Image.open(infile)
width, height = img.size

# Save Chops of original image
for x0 in range(0, width, chopsize):
   for y0 in range(0, height, chopsize):
      box = (x0, y0,
             x0+chopsize if x0+chopsize <  width else  width - 1,
             y0+chopsize if y0+chopsize < height else height - 1)
      print('%s %s' % (infile, box))
      img.crop(box).save('zchop.%s.x%03d.y%03d.jpg' % (infile.replace('.jpg',''), x0, y0))

Notes:

  • The crops that go over the right and bottom of the original image are adjusted to the original image limit and contain only the original pixels.
  • It's easy to choose a different chopsize for w and h by using two chopsize vars and replacing chopsize as appropriate in the code above.

  • How to close current tab in a browser window?

    Sorry for necroposting this, but I recently implemented a locally hosted site that had needed the ability to close the current browser tab and found some interesting workarounds that are not well documented anywhere I could find, so took it on myself to do so.

    Note: These workarounds were done with a locally hosted site in mind, and (with the exception of Edge) require the browser to be specifically configured, so would not be ideal for publicly hosted sites.

    Context: In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, modern browsers no longer support this script, potentially for security reasons.

    Google Chrome:

    Chrome does not allow the window.close() script to be to be run and nothing happens if you try to use it. By using the Chrome plugin TamperMonkey however we can use the window.close() method if you include the // @grant window.close in the UserScript header of TamperMonkey.

    For example, my script (which is triggered when a button with id = 'close_page' is clicked and if 'yes' is pressed on the browser popup) looks like:

    // ==UserScript==
    // @name         Close Tab Script
    // @namespace    http://tampermonkey.net/
    // @version      1.0
    // @description  Closes current tab when triggered
    // @author       Mackey Johnstone
    // @match        http://localhost/index.php
    // @grant        window.close
    // @require      http://code.jquery.com/jquery-3.4.1.min.js
    // ==/UserScript==
    
    (function() {
        'use strict';
        $("#close_page").click(function() {
            var confirm_result = confirm("Are you sure you want to quit?");
            if (confirm_result == true) {
                window.close();
            }
        });
    })();
    

    Note: This solution can only close the tab if it is NOT the last tab open however. So effectively, it cannot close the tab if it would cause window to closes by being the last tab open.

    Firefox:

    Firefox has an advanced setting that you can enable to allow scripts to close windows, effectively enabling the window.close() method. To enable this setting go to about:config then search and find the dom.allow_scripts_to_close_windows preference and switch it from false to true.

    This allows you to use the window.close() method directly in your jQuery file as you would any other script.

    For example, this script works perfectly with the preference set to true:

    <script>
      $("#close_page").click(function() {
        var confirm_result = confirm("Are you sure you want to quit?");
        if (confirm_result == true) {
          window.close();
        }
      });
    </script>
    

    This works much better than the Chrome workaround as it allows the user to close the current tab even if it is the only tab open, and doesn't require a third party plugin. The one downside however is that it also enables this script to be run by different websites (not just the one you are intending it to use on) so could potentially be a security hazard, although I cant imagine closing the current tab being particularly dangerous.

    Edge:

    Disappointingly Edge actually performed the best out of all 3 browsers I tried, and worked with the window.close() method without requiring any configuration. When the window.close() script is run, an additional popup alerts you that the page is trying to close the current tab and asks if you want to continue.

    Edit: This was on the old version of Edge not based on chromium. I have not tested it, but imagine it will act similarly to Chrome on chromium based versions

    enter image description here

    Final Note: The solutions for both Chrome and Firefox are workarounds for something that the browsers intentionally disabled, potentially for security reasons. They also both require the user to configure their browsers up to be compatible before hand, so would likely not be viable for sites intended for public use, but are ideal for locally hosted solutions like mine.

    Hope this helped! :)

    How to check if a number is a power of 2

    This program in java returns "true" if number is a power of 2 and returns "false" if its not a power of 2

    // To check if the given number is power of 2
    
    import java.util.Scanner;
    
    public class PowerOfTwo {
        int n;
        void solve() {
            while(true) {
    //          To eleminate the odd numbers
                if((n%2)!= 0){
                    System.out.println("false");
                    break;
                }
    //  Tracing the number back till 2
                n = n/2;
    //  2/2 gives one so condition should be 1
                if(n == 1) {
                    System.out.println("true");
                    break;
                }
            }
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner in = new Scanner(System.in);
            PowerOfTwo obj = new PowerOfTwo();
            obj.n = in.nextInt();
            obj.solve();
        }
    
    }
    
    OUTPUT : 
    34
    false
    
    16
    true
    

    TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

    I had the same issue on Windows 7. The cause was, that I had been connected to VPN using Cisco AnyConnect Secure Mobility Client.

    Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

    On my execution of openssl pkcs12 -export -out cacert.pkcs12 -in testca/cacert.pem, I received the following message:

    unable to load private key 140707250050712:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: ANY PRIVATE KEY`

    Got this solved by providing the key file along with the command. The switch is -inkey inkeyfile.pem

    Http Get using Android HttpURLConnection

    Here is a complete AsyncTask class

    public class GetMethodDemo extends AsyncTask<String , Void ,String> {
        String server_response;
    
        @Override
        protected String doInBackground(String... strings) {
    
            URL url;
            HttpURLConnection urlConnection = null;
    
            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
    
                int responseCode = urlConnection.getResponseCode();
    
                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                    Log.v("CatalogClient", server_response);
                }
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
    
            Log.e("Response", "" + server_response);
    
    
        }
    }
    
    // Converting InputStream to String
    
    private String readStream(InputStream in) {
            BufferedReader reader = null;
            StringBuffer response = new StringBuffer();
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return response.toString();
        }
    

    To Call this AsyncTask class

    new GetMethodDemo().execute("your web-service url");
    

    Android Studio: Unable to start the daemon process

    Try deleting your .gradle from C:\Users\<username> directory and try again.

    How to insert an element after another element in JavaScript without using a library?

    insertAdjacentHTML + outerHTML

    elementBefore.insertAdjacentHTML('afterEnd', elementAfter.outerHTML)
    

    Upsides:

    • DRYer: you don't have to store the before node in a variable and use it twice. If you rename the variable, on less occurrence to modify.
    • golfs better than the insertBefore (break even if the existing node variable name is 3 chars long)

    Downsides:

    • lower browser support since newer: https://caniuse.com/#feat=insert-adjacent
    • will lose properties of the element such as events because outerHTML converts the element to a string. We need it because insertAdjacentHTML adds content from strings rather than elements.

    how to get list of port which are in use on the server

    There are a lot of options and tools. If you just want a list of listening ports and their owner processes try.

    netstat -bano
    

    Correct way to integrate jQuery plugins in AngularJS

    Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

    There are a couple of points in the documentation that you could take a look at. You can find them here:
    Common Pitfalls

    Using controllers correctly

    Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

    EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

    Find multiple files and rename them in Linux

    If you just want to rename and don't mind using an external tool, then you can use rnm. The command would be:

    #on current folder
    rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' *
    

    -dp -1 will make it recursive to all subdirectories.

    -fo implies file only mode.

    -ssf '_dbg' searches for files with _dbg in the filename.

    -rs '/_dbg//' replaces _dbg with empty string.

    You can run the above command with the path of the CURRENT_FOLDER too:

    rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' /path/to/the/directory
    

    How to toggle (hide / show) sidebar div using jQuery

    $('#toggle').click(function() {
      $('#B').toggleClass('extended-panel');
      $('#A').toggle(/** specify a time here for an animation */);
    });
    

    and in the CSS:

    .extended-panel {
      left: 0px !important;
    }
    

    HAProxy redirecting http to https (ssl)

    According to http://parsnips.net/haproxy-http-to-https-redirect/ it should be as easy as configuring your haproxy.cfg to contain the follow.

    #---------------------------------------------------------------------
    # Redirect to secured
    #---------------------------------------------------------------------
    frontend unsecured *:80
        redirect location https://foo.bar.com
    
    #---------------------------------------------------------------------
    # frontend secured
    #---------------------------------------------------------------------
    frontend  secured *:443
       mode  tcp
       default_backend      app
    
    #---------------------------------------------------------------------
    # round robin balancing between the various backends
    #---------------------------------------------------------------------
    backend app
        mode  tcp
        balance roundrobin
        server  app1 127.0.0.1:5001 check
        server  app2 127.0.0.1:5002 check
        server  app3 127.0.0.1:5003 check
        server  app4 127.0.0.1:5004 check
    

    How can I create an object based on an interface file definition in TypeScript?

    You can set default values using Class.

    Without Class Constructor:

    interface IModal {
      content: string;
      form: string;
      href: string;
      isPopup: boolean;
    };
    
    class Modal implements IModal {
      content = "";
      form = "";
      href: string;  // will not be added to object
      isPopup = true;
    }
    
    const myModal = new Modal();
    console.log(myModal); // output: {content: "", form: "", isPopup: true}
    

    With Class Constructor

    interface IModal {
      content: string;
      form: string;
      href: string;
      isPopup: boolean;
    }
    
    class Modal implements IModal {
      constructor() {
        this.content = "";
        this.form = "";
        this.isPopup = true;
      }
    
      content: string;
    
      form: string;
    
      href: string; // not part of constructor so will not be added to object
    
      isPopup: boolean;
    }
    
    const myModal = new Modal();
    console.log(myModal); // output: {content: "", form: "", isPopup: true}
    

    Java 8, Streams to find the duplicate elements

    A multiset is a structure maintaining the number of occurrences for each element. Using Guava implementation:

    Set<Integer> duplicated =
            ImmutableMultiset.copyOf(numbers).entrySet().stream()
                    .filter(entry -> entry.getCount() > 1)
                    .map(Multiset.Entry::getElement)
                    .collect(Collectors.toSet());
    

    Set iframe content height to auto resize dynamically

    Simple solution:

    <iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>

    This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.

    How to view AndroidManifest.xml from APK file?

    In this thread, Dianne Hackborn tells us we can get info out of the AndroidManifest using aapt.

    I whipped up this quick unix command to grab the version info:

    aapt dump badging my.apk | sed -n "s/.*versionName='\([^']*\).*/\1/p"
    

    Centos/Linux setting logrotate to maximum file size for all logs

    It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

    minsize size
                  Log  files  are  rotated when they grow bigger than size bytes,
                  but not before the additionally specified time interval (daily,
                  weekly,  monthly, or yearly).  The related size option is simi-
                  lar except that it is mutually exclusive with the time interval
                  options,  and  it causes log files to be rotated without regard
                  for the last rotation time.  When minsize  is  used,  both  the
                  size and timestamp of a log file are considered.
    
    size size
                  Log files are rotated only if they grow bigger then size bytes.
                  If size is followed by k, the size is assumed to  be  in  kilo-
                  bytes.  If the M is used, the size is in megabytes, and if G is
                  used, the size is in gigabytes. So size 100,  size  100k,  size
                  100M and size 100G are all valid.
    maxsize size
                  Log files are rotated when they grow bigger than size bytes even before
                  the additionally specified time interval (daily, weekly, monthly, 
                  or yearly).  The related size option is  similar  except  that  it 
                  is mutually exclusive with the time interval options, and it causes
                  log files to be rotated without regard for the last rotation time.  
                  When maxsize is used, both the size and timestamp of a log file are                  
                  considered.
    

    Here is an example:

    "/var/log/httpd/access.log" /var/log/httpd/error.log {
               rotate 5
               mail [email protected]
               size 100k
               sharedscripts
               postrotate
                   /usr/bin/killall -HUP httpd
               endscript
           }
    

    Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

    Find first element in a sequence that matches a predicate

    J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.

    For Python version < 2.6, here's the best I can come up with:

    from itertools import repeat,ifilter,chain
    chain(ifilter(predicate,seq),repeat(None)).next()
    

    Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:

    from itertools import islice,ifilter
    list(islice(ifilter(predicate,seq),1))
    

    UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:

    from itertools import islice,chain
    chain((x for x in seq if predicate(x)),repeat(None)).next()
    

    Normalize data in pandas

    In [92]: df
    Out[92]:
               a         b          c         d
    A  -0.488816  0.863769   4.325608 -4.721202
    B -11.937097  2.993993 -12.916784 -1.086236
    C  -5.569493  4.672679  -2.168464 -9.315900
    D   8.892368  0.932785   4.535396  0.598124
    
    In [93]: df_norm = (df - df.mean()) / (df.max() - df.min())
    
    In [94]: df_norm
    Out[94]:
              a         b         c         d
    A  0.085789 -0.394348  0.337016 -0.109935
    B -0.463830  0.164926 -0.650963  0.256714
    C -0.158129  0.605652 -0.035090 -0.573389
    D  0.536170 -0.376229  0.349037  0.426611
    
    In [95]: df_norm.mean()
    Out[95]:
    a   -2.081668e-17
    b    4.857226e-17
    c    1.734723e-17
    d   -1.040834e-17
    
    In [96]: df_norm.max() - df_norm.min()
    Out[96]:
    a    1
    b    1
    c    1
    d    1
    

    Spring application context external properties?

    You can use file prefix to load the external application context file some thing like this

      <context:property-placeholder location="file:///C:/Applications/external/external.properties"/>
    

    IntelliJ - Convert a Java project/module into a Maven project/module

    Right-click on the module, select "Add framework support...", and check the "Maven" technology.

    (This also creates a pom.xml for you to modify.)

    If you mean adding source repository elements, I think you need to do that manually–not sure.

    Pre-IntelliJ 13 this won't convert the project to the Maven Standard Directory Layout, 13+ it will.

    Constructor overload in TypeScript

    Note that you can also work around the lack of overloading at the implementation level through default parameters in TypeScript, e.g.:

    interface IBox {    
        x : number;
        y : number;
        height : number;
        width : number;
    }
    
    class Box {
        public x: number;
        public y: number;
        public height: number;
        public width: number;
    
        constructor(obj : IBox = {x:0,y:0, height:0, width:0}) {    
            this.x = obj.x;
            this.y = obj.y;
            this.height = obj.height;
            this.width = obj.width;
        }   
    }
    

    Edit: As of Dec 5 '16, see Benson's answer for a more elaborate solution that allows more flexibility.

    delete all record from table in mysql

    truncate tableName

    That is what you are looking for.

    Truncate will delete all records in the table, emptying it.

    How do I know if jQuery has an Ajax request pending?

    You could use ajaxStart and ajaxStop to keep track of when requests are active.

    How to return multiple objects from a Java method?

    Apache Commons has tuple and triple for this:

    • ImmutablePair<L,R> An immutable pair consisting of two Object elements.
    • ImmutableTriple<L,M,R> An immutable triple consisting of three Object elements.
    • MutablePair<L,R> A mutable pair consisting of two Object elements.
    • MutableTriple<L,M,R> A mutable triple consisting of three Object elements.
    • Pair<L,R> A pair consisting of two elements.
    • Triple<L,M,R> A triple consisting of three elements.

    Source: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html

    Node.js Logging

    Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.

    The fix is to change logger.trace to logger.error in the body of errorLogger.

    Copy and Paste a set range in the next empty row

    The reason the code isn't working is because lastrow is measured from whatever sheet is currently active, and "A:A500" (or other number) is not a valid range reference.

    Private Sub CommandButton1_Click()
        Dim lastrow As Long
    
        lastrow = Sheets("Summary Info").Range("A65536").End(xlUp).Row    ' or + 1
        Range("A3:E3").Copy Destination:=Sheets("Summary Info").Range("A" & lastrow)
    End Sub
    

    Fastest way to add an Item to an Array

    For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.

    Module ArrayExtension
        <Extension()> _
        Public Sub Add(Of T)(ByRef arr As T(), item As T)
            If arr IsNot Nothing Then
                Array.Resize(arr, arr.Length + 1)
                arr(arr.Length - 1) = item
            Else
                ReDim arr(0)
                arr(0) = item
            End If
    
        End Sub
    End Module
    

    How to write "Html.BeginForm" in Razor

    The following code works fine:

    @using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                          new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
    

    and generates as expected:

    <form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    </form>
    

    On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

    @if (SomeCondition)
    {
        using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                          new { enctype = "multipart/form-data" }))
        {
            @Html.ValidationSummary(true)
            <fieldset>
                Select a file <input type="file" name="file" />
                <input type="submit" value="Upload" />
            </fieldset>
        }
    }
    

    As far as your server side code is concerned, here's how to proceed:

    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file) 
    {
        if (file != null && file.ContentLength > 0) 
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
            file.SaveAs(path);
        }
        return RedirectToAction("Upload");
    }
    

    error: the details of the application error from being viewed remotely

    In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

    Cheers

    How do I find the mime-type of a file with php?

    function get_mime($file) {
      if (function_exists("finfo_file")) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
        $mime = finfo_file($finfo, $file);
        finfo_close($finfo);
        return $mime;
      } else if (function_exists("mime_content_type")) {
        return mime_content_type($file);
      } else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
        // http://stackoverflow.com/a/134930/1593459
        $file = escapeshellarg($file);
        $mime = shell_exec("file -bi " . $file);
        return $mime;
      } else {
        return false;
      }
    }
    

    For me, nothing of this does work - mime_content_type is deprecated, finfo is not installed, and shell_exec is not allowed.

    Best TCP port number range for internal applications

    I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

    If they're not, then they haven't been done very well. Go back and do them properly :-)

    In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

    I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

    Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

    telnet big_honking_mainframe_box.com 1023
    

    If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

    How to create id with AUTO_INCREMENT on Oracle?

    There is no such thing as "auto_increment" or "identity" columns in Oracle as of Oracle 11g. However, you can model it easily with a sequence and a trigger:

    Table definition:

    CREATE TABLE departments (
      ID           NUMBER(10)    NOT NULL,
      DESCRIPTION  VARCHAR2(50)  NOT NULL);
    
    ALTER TABLE departments ADD (
      CONSTRAINT dept_pk PRIMARY KEY (ID));
    
    CREATE SEQUENCE dept_seq START WITH 1;
    

    Trigger definition:

    CREATE OR REPLACE TRIGGER dept_bir 
    BEFORE INSERT ON departments 
    FOR EACH ROW
    
    BEGIN
      SELECT dept_seq.NEXTVAL
      INTO   :new.id
      FROM   dual;
    END;
    /
    

    UPDATE:

    IDENTITY column is now available on Oracle 12c:

    create table t1 (
        c1 NUMBER GENERATED by default on null as IDENTITY,
        c2 VARCHAR2(10)
        );
    

    or specify starting and increment values, also preventing any insert into the identity column (GENERATED ALWAYS) (again, Oracle 12c+ only)

    create table t1 (
        c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
        c2 VARCHAR2(10)
        );
    

    Alternatively, Oracle 12 also allows to use a sequence as a default value:

    CREATE SEQUENCE dept_seq START WITH 1;
    
    CREATE TABLE departments (
      ID           NUMBER(10)    DEFAULT dept_seq.nextval NOT NULL,
      DESCRIPTION  VARCHAR2(50)  NOT NULL);
    
    ALTER TABLE departments ADD (
      CONSTRAINT dept_pk PRIMARY KEY (ID));
    

    How do I write a batch script that copies one directory to another, replaces old files?

    It seems that the latest function for this in windows 7 is robocopy.

    Usage example:

    robocopy <source> <destination> /e /xf <file to exclude> <another file>
    

    /e copies subdirectories including empty ones, /xf excludes certain files from being copied.

    More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

    <Django object > is not JSON serializable

    The easiest way is to use a JsonResponse.

    For a queryset, you should pass a list of the the values for that queryset, like so:

    from django.http import JsonResponse
    
    queryset = YourModel.objects.filter(some__filter="some value").values()
    return JsonResponse({"models_to_return": list(queryset)})
    

    How do you specify a byte literal in Java?

    You have to cast, I'm afraid:

    f((byte)0);
    

    I believe that will perform the appropriate conversion at compile-time instead of execution time, so it's not actually going to cause performance penalties. It's just inconvenient :(

    How can I drop a table if there is a foreign key constraint in SQL Server?

    The Best Answer to dropping the table containing foreign constraints is :

    • Step 1 : Drop the Primary key of the table.
    • Step 2 : Now it will prompt whether to delete all the foreign references or not.
    • Step 3 : Delete the table.

    keycloak Invalid parameter: redirect_uri

    Log in the Keycloak admin console website, select the realm and its client, then make sure all URIs of the client are prefixed with the protocol, that is, with http:// for example. An example would be http://localhost:8082/*

    Another way to solve the issue, is to view the Keycloak server console output, locate the line stating the request was refused, copy from it the redirect_uri displayed value and paste it in the * Valid Redirect URIs field of the client in the Keycloak admin console website. The requested URI is then one of the acceptables.

    How to export JavaScript array info to csv (on client side)?

    Download CSV File

      let csvContent = "data:text/csv;charset=utf-8,";
      rows.forEach(function (rowArray) {
        for (var i = 0, len = rowArray.length; i < len; i++) {
          if (typeof (rowArray[i]) == 'string')
            rowArray[i] = rowArray[i].replace(/<(?:.|\n)*?>/gm, '');
          rowArray[i] = rowArray[i].replace(/,/g, '');
        }
    
        let row = rowArray.join(",");
        csvContent += row + "\r\n"; // add carriage return
      });
      var encodedUri = encodeURI(csvContent);
      var link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", "fileName.csv");
      document.body.appendChild(link);
      link.click();
    

    Can You Get A Users Local LAN IP Address Via JavaScript?

    As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com

    This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).

    Border Height on CSS

    I have another possibility. This is of course a "newer" technique, but for my projects works sufficient.

    It only works if you need one or two borders. I've never done it with 4 borders... and to be honest, I don't know the answer for that yet.

    .your-item {
      position: relative;
    }
    
    .your-item:after {
      content: '';
      height: 100%; //You can change this if you want smaller/bigger borders
      width: 1px;
    
      position: absolute;
      right: 0;
      top: 0; // If you want to set a smaller height and center it, change this value
    
      background-color: #000000; // The color of your border
    }
    

    I hope this helps you too, as for me, this is an easy workaround.

    Is there a Social Security Number reserved for testing/examples?

    Please look at this document

    http://www.socialsecurity.gov/employer/randomization.html

    The SSA is instituting a new policy the where all previously unused sequences are will be available for use.

    Goes into affect June 25, 2011.

    Taken from the new FAQ:

    What changes will result from randomization?

    The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999. Top

    Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?

    SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.

    MAX function in where clause mysql

    This query should give you back the data you want. Replace foo with the table name you are using.

    SQL Query:

    select firstName,Lastname, id 
    from foo 
    having max(id) = id 
    

    Convert Xml to Table SQL Server

    The sp_xml_preparedocument stored procedure will parse the XML and the OPENXML rowset provider will show you a relational view of the XML data.

    For details and more examples check the OPENXML documentation.

    As for your question,

    DECLARE @XML XML
    SET @XML = '<rows><row>
        <IdInvernadero>8</IdInvernadero>
        <IdProducto>3</IdProducto>
        <IdCaracteristica1>8</IdCaracteristica1>
        <IdCaracteristica2>8</IdCaracteristica2>
        <Cantidad>25</Cantidad>
        <Folio>4568457</Folio>
    </row>
    <row>
        <IdInvernadero>3</IdInvernadero>
        <IdProducto>3</IdProducto>
        <IdCaracteristica1>1</IdCaracteristica1>
        <IdCaracteristica2>2</IdCaracteristica2>
        <Cantidad>72</Cantidad>
        <Folio>4568457</Folio>
    </row></rows>'
    
    DECLARE @handle INT  
    DECLARE @PrepareXmlStatus INT  
    
    EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  
    
    SELECT  *
    FROM    OPENXML(@handle, '/rows/row', 2)  
        WITH (
        IdInvernadero INT,
        IdProducto INT,
        IdCaracteristica1 INT,
        IdCaracteristica2 INT,
        Cantidad INT,
        Folio INT
        )  
    
    
    EXEC sp_xml_removedocument @handle 
    

    Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

    In Android studio 0.8 and after Right click on app folder then New > Image Asset

    Browse for best resolution image you have in "Image file" field

    hit Next The rest will be generated

    CSS Image size, how to fill, but not stretch?

    You can use the css property object-fit.

    _x000D_
    _x000D_
    .cover {_x000D_
      object-fit: cover;_x000D_
      width: 50px;_x000D_
      height: 100px;_x000D_
    }
    _x000D_
    <img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
    _x000D_
    _x000D_
    _x000D_

    See example here

    There's a polyfill for IE: https://github.com/anselmh/object-fit

    Using Excel as front end to Access database (with VBA)

    Just skip the excel part - the excel user forms are just a poor man's version of the way more robust Access forms. Also Access VBA is identical to Excel VBA - you just have to learn Access' object model. With a simple application you won't need to write much VBA anyways because in Access you can wire things together quite easily.

    Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

    Combining various answers :

    In MySQL 5.5, DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP cannot be added on DATETIME but only on TIMESTAMP.

    Rules:

    1) at most one TIMESTAMP column per table could be automatically (or manually[My addition]) initialized or updated to the current date and time. (MySQL Docs).

    So only one TIMESTAMP can have CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

    2) The first NOT NULL TIMESTAMP column without an explicit DEFAULT value like created_date timestamp default '0000-00-00 00:00:00' will be implicitly given a DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP and hence subsequent TIMESTAMP columns cannot be given CURRENT_TIMESTAMP on DEFAULT or ON UPDATE clause

    CREATE TABLE `address` (
      `id` int(9) NOT NULL AUTO_INCREMENT,
      `village` int(11) DEFAULT NULL,
        `created_date` timestamp default '0000-00-00 00:00:00', 
    
        -- Since explicit DEFAULT value that is not CURRENT_TIMESTAMP is assigned for a NOT NULL column, 
        -- implicit DEFAULT CURRENT_TIMESTAMP is avoided.
        -- So it allows us to set ON UPDATE CURRENT_TIMESTAMP on 'updated_date' column.
        -- How does setting DEFAULT to '0000-00-00 00:00:00' instead of CURRENT_TIMESTAMP help? 
        -- It is just a temporary value.
        -- On INSERT of explicit NULL into the column inserts current timestamp.
    
    -- `created_date` timestamp not null default '0000-00-00 00:00:00', // same as above
    
    -- `created_date` timestamp null default '0000-00-00 00:00:00', 
    -- inserting 'null' explicitly in INSERT statement inserts null (Ignoring the column inserts the default value)! 
    -- Remember we need current timestamp on insert of 'null'. So this won't work. 
    
    -- `created_date` timestamp null , // always inserts null. Equally useless as above. 
    
    -- `created_date` timestamp default 0, // alternative to '0000-00-00 00:00:00'
    
    -- `created_date` timestamp, 
    -- first 'not null' timestamp column without 'default' value. 
    -- So implicitly adds DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP. 
    -- Hence cannot add 'ON UPDATE CURRENT_TIMESTAMP' on 'updated_date' column.
    
    
       `updated_date` timestamp null on update current_timestamp,
    
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
    

    INSERT INTO address (village,created_date) VALUES (100,null);
    

    mysql> select * from address;
    +-----+---------+---------------------+--------------+
    | id  | village | created_date        | updated_date |
    +-----+---------+---------------------+--------------+
    | 132 |     100 | 2017-02-18 04:04:00 | NULL         |
    +-----+---------+---------------------+--------------+
    1 row in set (0.00 sec)
    

    UPDATE address SET village=101 WHERE village=100;
    

    mysql> select * from address;
    +-----+---------+---------------------+---------------------+
    | id  | village | created_date        | updated_date        |
    +-----+---------+---------------------+---------------------+
    | 132 |     101 | 2017-02-18 04:04:00 | 2017-02-18 04:06:14 |
    +-----+---------+---------------------+---------------------+
    1 row in set (0.00 sec)
    

    Other option (But updated_date is the first column):

    CREATE TABLE `address` (
      `id` int(9) NOT NULL AUTO_INCREMENT,
      `village` int(11) DEFAULT NULL,
      `updated_date` timestamp null on update current_timestamp,
      `created_date` timestamp not null , 
      -- implicit default is '0000-00-00 00:00:00' from 2nd timestamp onwards
    
      -- `created_date` timestamp not null default '0000-00-00 00:00:00'
      -- `created_date` timestamp
      -- `created_date` timestamp default '0000-00-00 00:00:00'
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
    

    How to view the Folder and Files in GAC?

    Install:

    gacutil -i "path_to_the_assembly"
    

    View:

    Open in Windows Explorer folder

    • .NET 1.0 - NET 3.5: c:\windows\assembly (%systemroot%\assembly)
    • .NET 4.x: %windir%\Microsoft.NET\assembly

    OR gacutil –l

    When you are going to install an assembly you have to specify where gacutil can find it, so you have to provide a full path as well. But when an assembly already is in GAC - gacutil know a folder path so it just need an assembly name.

    MSDN:

    Random state (Pseudo-random number) in Scikit learn

    If you don't specify the random_state in your code, then every time you run(execute) your code a new random value is generated and the train and test datasets would have different values each time.

    However, if a fixed value is assigned like random_state = 42 then no matter how many times you execute your code the result would be the same .i.e, same values in train and test datasets.

    Proper use of 'yield return'

    And what about this?

    public static IEnumerable<Product> GetAllProducts()
    {
        using (AdventureWorksEntities db = new AdventureWorksEntities())
        {
            var products = from product in db.Product
                           select product;
    
            return products.ToList();
        }
    }
    

    I guess this is much cleaner. I do not have VS2008 at hand to check, though. In any case, if Products implements IEnumerable (as it seems to - it is used in a foreach statement), I'd return it directly.

    How to find which columns contain any NaN value in Pandas dataframe

    i use these three lines of code to print out the column names which contain at least one null value:

    for column in dataframe:
        if dataframe[column].isnull().any():
           print('{0} has {1} null values'.format(column, dataframe[column].isnull().sum()))
    

    Foreach loop in C++ equivalent of C#

    using C++ 14:

    #include <string>
    #include <vector>
    
    
    std::vector<std::string> listbox;
    ...
    std::vector<std::string> strarr {"ram","mohan","sita"};    
    for (const auto &str : strarr)
    {
        listbox.push_back(str);
    }
    

    How to export specific request to file using postman?

    There is no direct option to export a single request from Postman.

    You can create and export collections. Here is a link to help with that.

    Regarding the single request thing, you can try a workaround. I tried with the RAW body parameters and it worked.

    What you can do is,

    1. In your request tab, click on the 3 dots in the top right corner of your request panel/box. enter image description here

    2. Select Code. This will open Generate Code Snippents window. enter image description here

    3. Copy the cURL code and save it in a text file. Share this with who you want to. enter image description here

    4. They can then import the request from the text file. enter image description here

    How do I delete specific characters from a particular String in Java?

    The best method is what Mark Byers explains:

    s = s.substring(0, s.length() - 1)
    

    For example, if we want to replace \ to space " " with ReplaceAll, it doesn't work fine

    String.replaceAll("\\", "");
    

    or

    String.replaceAll("\\$", "");   //if it is a path
    

    How to remove all of the data in a table using Django

    Using shell,

    1) For Deleting the table:

    python manage.py dbshell
    >> DROP TABLE {app_name}_{model_name}
    

    2) For removing all data from table:

    python manage.py shell
    >> from {app_name}.models import {model_name}
    >> {model_name}.objects.all().delete()
    

    Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

    To check all versions of Internet Explorer you can go to codecpack.nl and install all versions of Internet Explorer, that is, IE collection.

    Or you can use www.multibrowserviewer.com. It can check in 45 browsers and 3 OSes.

    Reading images in python

    you can try to use cv2 like this

    import cv2
    
    image= cv2.imread('image page')
    
    cv2.imshow('image', image)
    
    cv2.waitKey(0)
    
    cv2.destroyAllWindows()
    

    Git resolve conflict using --ours/--theirs for all files

    git checkout --[ours/theirs] . will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.

    Is there a REAL performance difference between INT and VARCHAR primary keys?

    You make a good point that you can avoid some number of joined queries by using what's called a natural key instead of a surrogate key. Only you can assess if the benefit of this is significant in your application.

    That is, you can measure the queries in your application that are the most important to be speedy, because they work with large volumes of data or they are executed very frequently. If these queries benefit from eliminating a join, and do not suffer by using a varchar primary key, then do it.

    Don't use either strategy for all tables in your database. It's likely that in some cases, a natural key is better, but in other cases a surrogate key is better.

    Other folks make a good point that it's rare in practice for a natural key to never change or have duplicates, so surrogate keys are usually worthwhile.

    Why does git status show branch is up-to-date when changes exist upstream?

    What the status is telling you is that you're behind the ref called origin/master which is a local ref in your local repo. In this case that ref happens to track a branch in some remote, called origin, but the status is not telling you anything about the branch on the remote. It's telling you about the ref, which is just a commit ID stored on your local filesystem (in this case, it's typically in a file called .git/refs/remotes/origin/master in your local repo).

    git pull does two operations; first it does a git fetch to get up to date with the commits in the remote repo (which updates the origin/master ref in your local repo), then it does a git merge to merge those commits into the current branch.

    Until you do the fetch step (either on its own or via git pull) your local repo has no way to know that there are additional commits upstream, and git status only looks at your local origin/master ref.

    When git status says up-to-date, it means "up-to-date with the branch that the current branch tracks", which in this case means "up-to-date with the local ref called origin/master". That only equates to "up-to-date with the upstream status that was retrieved last time we did a fetch" which is not the same as "up-to-date with the latest live status of the upstream".

    Why does it work this way? Well the fetch step is a potentially slow and expensive network operation. The design of Git (and other distributed version control systems) is to avoid network operations when unnecessary, and is a completely different model to the typical client-server system many people are used to (although as pointed out in the comments below, Git's concept of a "remote tracking branch" that causes confusion here is not shared by all DVCSs). It's entirely possible to use Git offline, with no connection to a centralized server, and the output of git status reflects this.

    Creating and switching branches (and checking their status) in Git is supposed to be lightweight, not something that performs a slow network operation to a centralized system. The assumption when designing Git, and the git status output, was that users understand this (too many Git features only make sense if you already know how Git works). With the adoption of Git by lots and lots of users who are not familiar with DVCS this assumption is not always valid.

    How to customise file type to syntax associations in Sublime Text?

    for ST3

    $language = "language u wish"

    if exists,

    go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

    else

    create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

    and set

    { "extensions": [ "yourextension" ] }

    This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )

    Select multiple columns from a table, but group by one

    mysql GROUP_CONCAT function could help https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat

    SELECT ProductID, GROUP_CONCAT(DISTINCT ProductName) as Names, SUM(OrderQuantity)
    FROM OrderDetails GROUP BY ProductID
    

    This would return:

    ProductID     Names          OrderQuantity
    1001          red            5
    1002          red,black      6
    1003          orange         8
    1004          black,orange   15
    

    Similar idea as the one @Urs Marian here posted https://stackoverflow.com/a/38779277/906265

    How do I POST form data with UTF-8 encoding by using curl?

    You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

    You should use this request:

    curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
    

    try/catch blocks with async/await

    I'd like to do this way :)

    const sthError = () => Promise.reject('sth error');
    
    const test = opts => {
      return (async () => {
    
        // do sth
        await sthError();
        return 'ok';
    
      })().catch(err => {
        console.error(err); // error will be catched there 
      });
    };
    
    test().then(ret => {
      console.log(ret);
    });
    

    It's similar to handling error with co

    const test = opts => {
      return co(function*() {
    
        // do sth
        yield sthError();
        return 'ok';
    
      }).catch(err => {
        console.error(err);
      });
    };
    

    Make a float only show two decimal places

    IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:

    printf("%.02f", your_float_var);
    

    OTOH, if what you want is to store that value on a char array you could use:

    sprintf(your_char_ptr, "%.02f", your_float_var);
    

    How to terminate the script in JavaScript?

    i use this piece of code to stop execution:

    throw new FatalError("!! Stop JS !!");
    

    you will get a console error though but it works good for me.

    Plot multiple boxplot in one graph

    Since you don't mention a plot package , I propose here using Lattice version( I think there is more ggplot2 answers than lattice ones, at least since I am here in SO).

     ## reshaping the data( similar to the other answer)
     library(reshape2)
     dat.m <- melt(TestData,id.vars='Label')
     library(lattice)
     bwplot(value~Label |variable,    ## see the powerful conditional formula 
            data=dat.m,
            between=list(y=1),
            main="Bad or Good")
    

    enter image description here

    javascript: detect scroll end

    Take a look at this example: MDN Element.scrollHeight

    I recommend that check out this example: stackoverflow.com/a/24815216... which implements a cross-browser handling for the scroll action.

    You may use the following snippet:

    //attaches the "scroll" event
    $(window).scroll(function (e) {
        var target = e.currentTarget,
            scrollTop = target.scrollTop || window.pageYOffset,
            scrollHeight = target.scrollHeight || document.body.scrollHeight;
        if (scrollHeight - scrollTop === $(target).innerHeight()) {
          console.log("? End of scroll");
        }
    });
    

    "Warning: iPhone apps should include an armv6 architecture" even with build config set

    Using Xcode 4.2 on Snow Leopard, I used the following settings to build an app that worked on both armv6 (Iphone 3G and lower) AND armv7 (everything newer than 3G including 3GS).

    architectures: armv6 and armv7 (removed $(ARCHS_STANDARD_32_BIT))
    build active architecture only: no
    required device capabilities: armv6

    do not put armv7 in required device capabilities if you want the app to run on 3G and lower as well.

    how concatenate two variables in batch script?

    You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

    To do that use this code:

    set var1=A
    
    set var2=B
    
    set AB=hi
    
    call set newvar=%%%var1%%var2%%%
    
    echo %newvar% 
    

    Note: You MUST use call before you set the variable or it won't work.

    How do I center an anchor element in CSS?

    You can try this code:

    /**code starts here**/
    
    a.class_name { display : block;text-align : center; }
    

    SQL 'like' vs '=' performance

    You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

    So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

    So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

    How do I speed up the gwt compiler?

    • Split your application into multiple modules or entry points and re-compile then only when needed.
    • Analyse your application using the trunk version - which provides the Story of your compile. This may or may not be relevant to the 1.6 compiler but it can indicate what's going on.

    Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

    For Windows (Thanks to the owner f040225), go to here: https://github.com/fo40225/tensorflow-windows-wheel to fetch the url for your environment based on the combination of "tf + python + cpu_instruction_extension". Then use this cmd to install:

    pip install --ignore-installed --upgrade "URL"
    

    If you encounter the "File is not a zip file" error, download the .whl to your local computer, and use this cmd to install:

    pip install --ignore-installed --upgrade /path/target.whl
    

    How to get first/top row of the table in Sqlite via Sql Query

    LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

    Return Type for jdbcTemplate.queryForList(sql, object, classType)

    A complete solution for JdbcTemplate, NamedParameterJdbcTemplate with or without RowMapper Example.

    // Create a Employee table

    create table employee(  
    id number(10),  
    name varchar2(100),  
    salary number(10)  
    );
    

    ======================================================================= //Employee.java

    public class Employee {
    private int id;  
    private String name;  
    private float salary;  
    
    //no-arg and parameterized constructors  
    
    public Employee(){};
    
    public Employee(int  id, String name, float salary){
        this.id=id;
        this.name=name;
        this.salary=salary;
    }
    
    //getters and setters  
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getSalary() {
        return salary;
    }
    public void setSalary(float salary) {
        this.salary = salary;
    }
    public String toString(){  
       return id+" "+name+" "+salary;  
    }   
    
    }
    

    ========================================================================= //EmployeeDao.java

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
    
    public class EmployeeDao {  
      private JdbcTemplate jdbcTemplate;  
      private NamedParameterJdbcTemplate nameTemplate;  
    
      public void setnameTemplate(NamedParameterJdbcTemplate template) {  
        this.nameTemplate = template;  
     }   
    
     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
      this.jdbcTemplate = jdbcTemplate;  
     }  
    
     // BY using JdbcTemplate
     public int saveEmployee(Employee e){  
     int id = e.getId();
     String name = e.getName();
     float salary = e.getSalary();
     Object p[] = {id, name, salary};
        String query="insert into employee values(?,?,?)";
          return jdbcTemplate.update(query, p);
        /*String query="insert into employee     values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; 
          return jdbcTemplate.update(query);
        */
    
    }  
    
    //By using NameParameterTemplate
    public void insertEmploye(Employee e) {  
    String query="insert into employee values (:id,:name,:salary)";  
    Map<String,Object> map=new HashMap<String,Object>();  
    map.put("id",e.getId());  
    map.put("name",e.getName());  
    map.put("salary",e.getSalary());  
    
    nameTemplate.execute(query,map,new MyPreparedStatement());
    
     }
    // Updating Employee
    public int updateEmployee(Employee e){  
    String query="update employee set  name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
      return jdbcTemplate.update(query);  
     }
     // Deleting a Employee row
     public int deleteEmployee(Employee e){  
     String query="delete from employee where id='"+e.getId()+"' ";  
     return jdbcTemplate.update(query);  
     }  
     //Selecting Single row with condition and also all rows
        public int selectEmployee(Employee e){  
         //String query="select * from employee where id='"+e.getId()+"' ";
          String query="select * from employee";
          List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
           for(Map<String, Object> row : rows){
              String id = row.get("id").toString();
              String name = (String)row.get("name");
              String salary = row.get("salary").toString();
              System.out.println(id + " " + name + " " + salary );
            }
    
          return 1;
       }  
    
       // Can use MyrowMapper class an implementation class for RowMapper interface
        public void getAllEmployee()
        {
    
        String query="select * from employee";
        List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());
    
        Iterator it=l.iterator();
        while(it.hasNext())
        {
          Employee e=(Employee)it.next();
          System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
        }
       }  
    
      //Can use directly a RowMapper implementation class without an object creation
      public List<Employee> getAllEmployee1(){
        return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){  
          @Override  
          public Employee mapRow(ResultSet rs, int rownumber) throws  SQLException    {  
                Employee e=new Employee();  
                e.setId(rs.getInt(1));  
                e.setName(rs.getString(2));  
                e.setSalary(rs.getFloat(3));  
                return e;  
              }  
          });  
          }
         // End of all the function
    
         }
    

    ================================================================ //MyrowMapper.java

     import java.sql.ResultSet;
     import java.sql.SQLException;
     import org.springframework.jdbc.core.RowMapper;
    
     public class MyrowMapper implements RowMapper<Employee> {
    
      @Override  
      public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
       {  
        System.out.println("mapRow()====:"+rownumber);
        Employee e=new Employee();  
         e.setId(rs.getInt("id"));  
         e.setName(rs.getString("name"));  
         e.setSalary(rs.getFloat("salary"));  
         return e;  
          }
        } 
    

    ========================================================== //MyPreparedStatement.java

    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import org.springframework.dao.DataAccessException;
    import org.springframework.jdbc.core.PreparedStatementCallback;
    
    
     public class MyPreparedStatement implements  PreparedStatementCallback<Object> {
    
     @Override
     public Object doInPreparedStatement(PreparedStatement ps)
            throws SQLException, DataAccessException {
    
         return ps.executeUpdate(); 
      } 
    
     } 
    

    ===================================================================== //Test.java

    import java.util.List;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Test {  
    
    public static void main(String[] args) {  
     ApplicationContext ctx=new     ClassPathXmlApplicationContext("applicationContext.xml");  
    
     EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); 
    
      // By calling constructor for insert
     /* 
        int status=dao.saveEmployee(new Employee(103,"Ajay",35000));  
        System.out.println(status);  
     */
     // By calling PreparedStatement
      dao.insertEmploye(new Employee(103,"Roh",25000));
    
    
     // By calling setter-getter for update
     /* 
        Employee e=new Employee(); 
        e.setId(102);
        e.setName("Rohit");
        e.setSalary(8000000);
        int status=dao.updateEmployee(e);
    */
     // By calling constructor for update
     /*
        int status=dao.updateEmployee(new Employee(102,"Sadhan",15000)); 
        System.out.println(status); 
     */ 
     // Deleting a record 
     /*      
        Employee e=new Employee(); 
        e.setId(102); 
        int status=dao.deleteEmployee(e); 
        System.out.println(status);
     */
     // Selecting single or all rows
     /*
        Employee e=new Employee(); 
        e.setId(102);
        int status=dao.selectEmployee(e);
        System.out.println(status);
    */
    // Can use MyrowMapper class an implementation class for RowMapper interface
    
        dao.getAllEmployee();
    
    // Can use directly a RowMapper implementation class without an object creation
     /*
        List<Employee> list=dao.getAllEmployee1();  
        for(Employee e1:list)  
        System.out.println(e1);  
      */   
       }  
    
     } 
    

    ================================================================== //applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>  
    <beans  
     xmlns="http://www.springframework.org/schema/beans"  
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     xmlns:p="http://www.springframework.org/schema/p"  
     xsi:schemaLocation="http://www.springframework.org/schema/beans   
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
    
    <bean id="ds"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
     <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
     <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
     <property name="username" value="hr" />  
     <property name="password" value="hr" />  
     </bean>  
    
     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
     <property name="dataSource" ref="ds"></property>  
     </bean>  
    
    <bean id="nameTemplate"   
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
    <constructor-arg ref="ds"></constructor-arg>  
    </bean>  
    
    <bean id="edao" class="EmployeeDao"> 
    <!-- Can use both --> 
    <property name="nameTemplate" ref="nameTemplate"></property>
    <property name="jdbcTemplate" ref="jdbcTemplate"></property> 
    </bean>  
    

    ===================================================================

    Check if a row exists, otherwise insert

    The best approach to this problem is first making the database column UNIQUE

    ALTER TABLE table_name ADD UNIQUE KEY

    THEN INSERT IGNORE INTO table_name ,the value won't be inserted if it results in a duplicate key/already exists in the table.

    jQuery $("#radioButton").change(...) not firing during de-selection

    Let's say those radio buttons are inside a div that has the id radioButtons and that the radio buttons have the same name (for example commonName) then:

    $('#radioButtons').on('change', 'input[name=commonName]:radio', function (e) {
        console.log('You have changed the selected radio button!');
    });
    

    How to catch SQLServer timeout exceptions

    here: http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.adonet/2006-10/msg00064.html

    You can read also that Thomas Weingartner wrote:

    Timeout: SqlException.Number == -2 (This is an ADO.NET error code)
    General Network Error: SqlException.Number == 11
    Deadlock: SqlException.Number == 1205 (This is an SQL Server error code)

    ...

    We handle the "General Network Error" as a timeout exception too. It only occurs under rare circumstances e.g. when your update/insert/delete query will raise a long running trigger.

    How do I encode and decode a base64 string?

    For those that simply want to encode/decode individual base64 digits:

    public static int DecodeBase64Digit(char digit, string digit62 = "+-.~", string digit63 = "/_,")
    {
        if (digit >= 'A' && digit <= 'Z') return digit - 'A';
        if (digit >= 'a' && digit <= 'z') return digit + (26 - 'a');
        if (digit >= '0' && digit <= '9') return digit + (52 - '0');
        if (digit62.IndexOf(digit) > -1)  return 62;
        if (digit63.IndexOf(digit) > -1)  return 63;
        return -1;
    }
    
    public static char EncodeBase64Digit(int digit, char digit62 = '+', char digit63 = '/')
    {
        digit &= 63;
        if (digit < 52)
            return (char)(digit < 26 ? digit + 'A' : digit + ('a' - 26));
        else if (digit < 62)
            return (char)(digit + ('0' - 52));
        else
            return digit == 62 ? digit62 : digit63;
    }
    

    There are various versions of Base64 that disagree about what to use for digits 62 and 63, so DecodeBase64Digit can tolerate several of these.

    How to crop a CvMat in OpenCV?

    To get better results and robustness against differents types of matrices, you can do this in addition to the first answer, that copy the data :

    cv::Mat source = getYourSource();
    
    // Setup a rectangle to define your region of interest
    cv::Rect myROI(10, 10, 100, 100);
    
    // Crop the full image to that image contained by the rectangle myROI
    // Note that this doesn't copy the data
    cv::Mat croppedRef(source, myROI);
    
    cv::Mat cropped;
    // Copy the data into new matrix
    croppedRef.copyTo(cropped);
    

    What's the difference between faking, mocking, and stubbing?

    I am surprised that this question has been around for so long and nobody has as yet provided an answer based on Roy Osherove's "The Art of Unit Testing".

    In "3.1 Introducing stubs" defines a stub as:

    A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.

    And defines the difference between stubs and mocks as:

    The main thing to remember about mocks versus stubs is that mocks are just like stubs, but you assert against the mock object, whereas you do not assert against a stub.

    Fake is just the name used for both stubs and mocks. For example when you don't care about the distinction between stubs and mocks.

    The way Osherove's distinguishes between stubs and mocks, means that any class used as a fake for testing can be both a stub or a mock. Which it is for a specific test depends entirely on how you write the checks in your test.

    • When your test checks values in the class under test, or actually anywhere but the fake, the fake was used as a stub. It just provided values for the class under test to use, either directly through values returned by calls on it or indirectly through causing side effects (in some state) as a result of calls on it.
    • When your test checks values of the fake, it was used as a mock.

    Example of a test where class FakeX is used as a stub:

    const pleaseReturn5 = 5;
    var fake = new FakeX(pleaseReturn5);
    var cut = new ClassUnderTest(fake);
    
    cut.SquareIt;
    
    Assert.AreEqual(25, cut.SomeProperty);
    

    The fake instance is used as a stub because the Assert doesn't use fake at all.

    Example of a test where test class X is used as a mock:

    const pleaseReturn5 = 5;
    var fake = new FakeX(pleaseReturn5);
    var cut = new ClassUnderTest(fake);
    
    cut.SquareIt;
    
    Assert.AreEqual(25, fake.SomeProperty);
    

    In this case the Assert checks a value on fake, making that fake a mock.

    Now, of course these examples are highly contrived, but I see great merit in this distinction. It makes you aware of how you are testing your stuff and where the dependencies of your test are.

    I agree with Osherove's that

    from a pure maintainability perspective, in my tests using mocks creates more trouble than not using them. That has been my experience, but I’m always learning something new.

    Asserting against the fake is something you really want to avoid as it makes your tests highly dependent upon the implementation of a class that isn't the one under test at all. Which means that the tests for class ActualClassUnderTest can start breaking because the implementation for ClassUsedAsMock changed. And that sends up a foul smell to me. Tests for ActualClassUnderTest should preferably only break when ActualClassUnderTest is changed.

    I realize that writing asserts against the fake is a common practice, especially when you are a mockist type of TDD subscriber. I guess I am firmly with Martin Fowler in the classicist camp (See Martin Fowler's "Mocks aren't Stubs") and like Osherove avoid interaction testing (which can only be done by asserting against the fake) as much as possible.

    For fun reading on why you should avoid mocks as defined here, google for "fowler mockist classicist". You'll find a plethora of opinions.

    Using union and order by clause in mysql

    You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:

    select *
    from (
        select 1 as Rank, id, add_date from Table 
        union all
        select 2 as Rank, id, add_date from Table where distance < 5
        union all
        select 3 as Rank, id, add_date from Table where distance between 5 and 15
    ) a
    order by rank, id, add_date desc
    

    Align contents inside a div

    All the answers talk about horizontal align.

    For vertical aligning multiple content elements, take a look at this approach:

    _x000D_
    _x000D_
    <div style="display: flex; align-items: center; width: 200px; height: 140px; padding: 10px 40px; border: solid 1px black;">_x000D_
        <div>_x000D_
            <p>Paragraph #1</p>_x000D_
            <p>Paragraph #2</p>_x000D_
        </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    What's the easiest way to install a missing Perl module?

    Lots of recommendation for CPAN.pm, which is great, but if you're using Perl 5.10 then you've also got access to CPANPLUS.pm which is like CPAN.pm but better.

    And, of course, it's available on CPAN for people still using older versions of Perl. Why not try:

    $ cpan CPANPLUS
    

    how to avoid a new line with p tag?

    The <p> paragraph tag is meant for specifying paragraphs of text. If you don't want the text to start on a new line, I would suggest you're using the <p> tag incorrectly. Perhaps the <span> tag more closely fits what you want to achieve...?

    How to set the font style to bold, italic and underlined in an Android TextView?

    Programmatialy:

    You can do programmatically using setTypeface() method:

    Below is the code for default Typeface

    textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
    textView.setTypeface(null, Typeface.BOLD);        // for Bold only
    textView.setTypeface(null, Typeface.ITALIC);      // for Italic
    textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic
    

    and if you want to set custom Typeface:

    textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      // for Normal Text
    textView.setTypeface(textView.getTypeface(), Typeface.BOLD);        // for Bold only
    textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      // for Italic
    textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic
    

    XML:

    You can set Directly in XML file in like:

    android:textStyle="normal"
    android:textStyle="normal|bold"
    android:textStyle="normal|italic"
    android:textStyle="bold"
    android:textStyle="bold|italic"
    

    System.BadImageFormatException: Could not load file or assembly

    It seems that you are using the 64-bit version of the tool to install a 32-bit/x86 architecture application. Look for the 32-bit version of the tool here:

    C:\Windows\Microsoft.NET\Framework\v4.0.30319
    

    and it should install your 32-bit application just fine.