Programs & Examples On #Merge replication

How to add Drop-Down list (<select>) programmatically?

This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.

_x000D_
_x000D_
var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];_x000D_
_x000D_
var sEle = document.createElement('select');_x000D_
document.getElementsByTagName('body')[0].appendChild(sEle);_x000D_
_x000D_
for (var i = 0; i < array.length; ++i) {_x000D_
  var oEle = document.createElement('option');_x000D_
_x000D_
  if (i == 0) {_x000D_
    oEle.setAttribute('disabled', 'disabled');_x000D_
    oEle.setAttribute('selected', 'selected');_x000D_
  } // end of if loop_x000D_
_x000D_
  var oTxt = document.createTextNode(array[i]);_x000D_
  oEle.appendChild(oTxt);_x000D_
_x000D_
  document.getElementsByTagName('select')[0].appendChild(oEle);_x000D_
} // end of for loop
_x000D_
_x000D_
_x000D_

Decorators with parameters?

Edit : for an in-depth understanding of the mental model of decorators, take a look at this awesome Pycon Talk. well worth the 30 minutes.

One way of thinking about decorators with arguments is

@decorator
def foo(*args, **kwargs):
    pass

translates to

foo = decorator(foo)

So if the decorator had arguments,

@decorator_with_args(arg)
def foo(*args, **kwargs):
    pass

translates to

foo = decorator_with_args(arg)(foo)

decorator_with_args is a function which accepts a custom argument and which returns the actual decorator (that will be applied to the decorated function).

I use a simple trick with partials to make my decorators easy

from functools import partial

def _pseudo_decor(fun, argument):
    def ret_fun(*args, **kwargs):
        #do stuff here, for eg.
        print ("decorator arg is %s" % str(argument))
        return fun(*args, **kwargs)
    return ret_fun

real_decorator = partial(_pseudo_decor, argument=arg)

@real_decorator
def foo(*args, **kwargs):
    pass

Update:

Above, foo becomes real_decorator(foo)

One effect of decorating a function is that the name foo is overridden upon decorator declaration. foo is "overridden" by whatever is returned by real_decorator. In this case, a new function object.

All of foo's metadata is overridden, notably docstring and function name.

>>> print(foo)
<function _pseudo_decor.<locals>.ret_fun at 0x10666a2f0>

functools.wraps gives us a convenient method to "lift" the docstring and name to the returned function.

from functools import partial, wraps

def _pseudo_decor(fun, argument):
    # magic sauce to lift the name and doc of the function
    @wraps(fun)
    def ret_fun(*args, **kwargs):
        # pre function execution stuff here, for eg.
        print("decorator argument is %s" % str(argument))
        returned_value =  fun(*args, **kwargs)
        # post execution stuff here, for eg.
        print("returned value is %s" % returned_value)
        return returned_value

    return ret_fun

real_decorator1 = partial(_pseudo_decor, argument="some_arg")
real_decorator2 = partial(_pseudo_decor, argument="some_other_arg")

@real_decorator1
def bar(*args, **kwargs):
    pass

>>> print(bar)
<function __main__.bar(*args, **kwargs)>

>>> bar(1,2,3, k="v", x="z")
decorator argument is some_arg
returned value is None

Regex match digits, comma and semicolon?

boolean foundMatch = Pattern.matches("[0-9,;]+", "131;23,87");

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

How to prevent long words from breaking my div?

This is a complex issue, as we know, and not supported in any common way between browsers. Most browsers don't support this feature natively at all.

In some work done with HTML emails, where user content was being used, but script is not available (and even CSS is not supported very well) the following bit of CSS in a wrapper around your unspaced content block should at least help somewhat:

.word-break {
  /* The following styles prevent unbroken strings from breaking the layout */
  width: 300px; /* set to whatever width you need */
  overflow: auto;
  white-space: -moz-pre-wrap; /* Mozilla */
  white-space: -hp-pre-wrap; /* HP printers */
  white-space: -o-pre-wrap; /* Opera 7 */
  white-space: -pre-wrap; /* Opera 4-6 */
  white-space: pre-wrap; /* CSS 2.1 */
  white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
  word-wrap: break-word; /* IE */
  -moz-binding: url('xbl.xml#wordwrap'); /* Firefox (using XBL) */
}

In the case of Mozilla-based browsers, the XBL file mentioned above contains:

<?xml version="1.0" encoding="utf-8"?>
<bindings xmlns="http://www.mozilla.org/xbl" 
          xmlns:html="http://www.w3.org/1999/xhtml">
  <!--
  More information on XBL:
  http://developer.mozilla.org/en/docs/XBL:XBL_1.0_Reference

  Example of implementing the CSS 'word-wrap' feature:
  http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/
  -->
  <binding id="wordwrap" applyauthorstyles="false">
    <implementation>
      <constructor>
        //<![CDATA[
        var elem = this;

        doWrap();
        elem.addEventListener('overflow', doWrap, false);

        function doWrap() {
          var walker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, null, false);
          while (walker.nextNode()) {
            var node = walker.currentNode;
            node.nodeValue = node.nodeValue.split('').join(String.fromCharCode('8203'));
          }
        }
        //]]>
      </constructor>
    </implementation>
  </binding>
</bindings>

Unfortunately, Opera 8+ don't seem to like any of the above solutions, so JavaScript will have to be the solution for those browsers (like Mozilla/Firefox.) Another cross-browser solution (JavaScript) that includes the later editions of Opera would be to use Hedger Wang's script found here: http://www.hedgerwow.com/360/dhtml/css-word-break.html

Other useful links/thoughts:

Incoherent Babble » Blog Archive » Emulating CSS word-wrap for Mozilla/Firefox
http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/

[OU] No word wrap in Opera, displays fine in IE
http://list.opera.com/pipermail/opera-users/2004-November/024467.html
http://list.opera.com/pipermail/opera-users/2004-November/024468.html

A top-like utility for monitoring CUDA activity on a GPU

you can use nvidia-smi pmon -i 0 to monitor every process in GPU 0. including compute mode, sm usage, memory usage, encoder usage, decoder usage.

Create PDF from a list of images

If your images are in landscape mode, you can do like this.

from fpdf import FPDF
import os, sys, glob
from tqdm import tqdm

pdf = FPDF('L', 'mm', 'A4')
im_width = 1920
im_height = 1080

aspect_ratio = im_height/im_width
page_width = 297
# page_height = aspect_ratio * page_width
page_height = 200
left_margin = 0
right_margin = 0

# imagelist is the list with all image filenames
for image in tqdm(sorted(glob.glob('test_images/*.png'))):
pdf.add_page()
pdf.image(image, left_margin, right_margin, page_width, page_height)
pdf.output("mypdf.pdf", "F")
print('Conversion completed!')

Here page_width and page_height is the size of 'A4' paper where in landscape its width will 297mm and height will be 210mm; but here I have adjusted the height as per my image. OR you can use either maintaining the aspect ratio as I have commented above for proper scaling of both width and height of the image.

How to iterate for loop in reverse order in swift?

Xcode 6 beta 4 added two functions to iterate on ranges with a step other than one: stride(from: to: by:), which is used with exclusive ranges and stride(from: through: by:), which is used with inclusive ranges.

To iterate on a range in reverse order, they can be used as below:

for index in stride(from: 5, to: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2

for index in stride(from: 5, through: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2, 1

Note that neither of those is a Range member function. They are global functions that return either a StrideTo or a StrideThrough struct, which are defined differently from the Range struct.

A previous version of this answer used the by() member function of the Range struct, which was removed in beta 4. If you want to see how that worked, check the edit history.

Insert json file into mongodb

Use

mongoimport --jsonArray --db test --collection docs --file example2.json

Its probably messing up because of the newline characters.

UIView bottom border?

The problem with these extension methods is that when the UIView/UIButton later adjusts it's size, you have no chance to change the CALayer's size to match the new size. Which will leave you with a misplaced border. I found it was better to subclass my UIButton, you could of course subclass other UIViews as well. Here is some code:

enum BorderedButtonSide {
    case Top, Right, Bottom, Left
}


class BorderedButton : UIButton {

    private var borderTop: CALayer?
    private var borderTopWidth: CGFloat?
    private var borderRight: CALayer?
    private var borderRightWidth: CGFloat?
    private var borderBottom: CALayer?
    private var borderBottomWidth: CGFloat?
    private var borderLeft: CALayer?
    private var borderLeftWidth: CGFloat?


    func setBorder(side: BorderedButtonSide, _ color: UIColor, _ width: CGFloat) {

        let border = CALayer()
        border.backgroundColor = color.CGColor

        switch side {
        case .Top:
            border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: width)
            borderTop?.removeFromSuperlayer()
            borderTop = border
            borderTopWidth = width
        case .Right:
            border.frame = CGRect(x: frame.size.width - width, y: 0, width: width, height: frame.size.height)
            borderRight?.removeFromSuperlayer()
            borderRight = border
            borderRightWidth = width
        case .Bottom:
            border.frame = CGRect(x: 0, y: frame.size.height - width, width: frame.size.width, height: width)
            borderBottom?.removeFromSuperlayer()
            borderBottom = border
            borderBottomWidth = width
        case .Left:
            border.frame = CGRect(x: 0, y: 0, width: width, height: frame.size.height)
            borderLeft?.removeFromSuperlayer()
            borderLeft = border
            borderLeftWidth = width
        }

        layer.addSublayer(border)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        borderTop?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderTopWidth!)
        borderRight?.frame = CGRect(x: frame.size.width - borderRightWidth!, y: 0, width: borderRightWidth!, height: frame.size.height)
        borderBottom?.frame = CGRect(x: 0, y: frame.size.height - borderBottomWidth!, width: frame.size.width, height: borderBottomWidth!)
        borderLeft?.frame = CGRect(x: 0, y: 0, width: borderLeftWidth!, height: frame.size.height)
    }

}

HTML CSS Button Positioning

as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float them so that they don't affect each other. the simpler solution is to just set the :active button to position:relative; and use top instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/

Difference between "module.exports" and "exports" in the CommonJs Module System

Also, one things that may help to understand:

math.js

this.add = function (a, b) {
    return a + b;
};

client.js

var math = require('./math');
console.log(math.add(2,2); // 4;

Great, in this case:

console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(module.exports === exports); // true

Thus, by default, "this" is actually equals to module.exports.

However, if you change your implementation to:

math.js

var add = function (a, b) {
    return a + b;
};

module.exports = {
    add: add
};

In this case, it will work fine, however, "this" is not equal to module.exports anymore, because a new object was created.

console.log(this === module.exports); // false
console.log(this === exports); // true
console.log(module.exports === exports); // false

And now, what will be returned by the require is what was defined inside the module.exports, not this or exports, anymore.

Another way to do it would be:

math.js

module.exports.add = function (a, b) {
    return a + b;
};

Or:

math.js

exports.add = function (a, b) {
    return a + b;
};

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

What is object serialization?

You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation).

It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.

In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.

You can also prevent some data in your object from being serialized by marking the attribute as transient.

Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases. To do this, you use one of the hidden features in java.

It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.

Here is a very basic sample with comments to facilitate its reading:

import java.io.*;
import java.util.*;

// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {

    // These attributes conform the "value" of the object.

    // These two will be serialized;
    private String aString = "The value of that string";
    private int    someInteger = 0;

    // But this won't since it is marked as transient.
    private transient List<File> unInterestingLongLongList;

    // Main method to test.
    public static void main( String [] args ) throws IOException  { 

        // Create a sample object, that contains the default values.
        SerializationSample instance = new SerializationSample();

        // The "ObjectOutputStream" class has the default 
        // definition to serialize an object.
        ObjectOutputStream oos = new ObjectOutputStream( 
                               // By using "FileOutputStream" we will 
                               // Write it to a File in the file system
                               // It could have been a Socket to another 
                               // machine, a database, an in memory array, etc.
                               new FileOutputStream(new File("o.ser")));

        // do the magic  
        oos.writeObject( instance );
        // close the writing.
        oos.close();
    }
}

When we run this program, the file "o.ser" is created and we can see what happened behind.

If we change the value of: someInteger to, for example Integer.MAX_VALUE, we may compare the output to see what the difference is.

Here's a screenshot showing precisely that difference:

alt text

Can you spot the differences? ;)

There is an additional relevant field in Java serialization: The serialversionUID but I guess this is already too long to cover it.

get an element's id

You need to check if is a string to avoid getting a child element

var getIdFromDomObj = function(domObj){
   var id = domObj.id;
   return typeof id  === 'string' ? id : false;
};

TextView bold via xml file?

use textstyle property as bold

android:textStyle = "bold";

how to access parent window object using jquery?

If you are in a po-up and you want to access the opening window, use window.opener. The easiest would be if you could load JQuery in the parent window as well:

window.opener.$("#serverMsg").html // this uses JQuery in the parent window

or you could use plain old document.getElementById to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):

element = window.opener.document.getElementById("serverMsg");
element = $(element);

If you are in an iframe or frameset and want to access the parent frame, use window.parent instead of window.opener.

According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.

Importing Excel into a DataTable Quickly

 class DataReader
    {
        Excel.Application xlApp;
        Excel.Workbook xlBook;
        Excel.Range xlRange;
        Excel.Worksheet xlSheet;
        public DataTable GetSheetDataAsDataTable(String filePath, String sheetName)
        {
            DataTable dt = new DataTable();
            try
            {
                xlApp = new Excel.Application();
                xlBook = xlApp.Workbooks.Open(filePath);
                xlSheet = xlBook.Worksheets[sheetName];
                xlRange = xlSheet.UsedRange;
                DataRow row=null;
                for (int i = 1; i <= xlRange.Rows.Count; i++)
                {
                    if (i != 1)
                        row = dt.NewRow();
                    for (int j = 1; j <= xlRange.Columns.Count; j++)
                    {
                        if (i == 1)
                            dt.Columns.Add(xlRange.Cells[1, j].value);
                        else
                            row[j-1] = xlRange.Cells[i, j].value;
                    }
                    if(row !=null)
                        dt.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                xlBook.Close();
                xlApp.Quit();
            }
            return dt;
        }
    }

Use .corr to get the correlation between two columns

I solved this problem by changing the data type. If you see the 'Energy Supply per Capita' is a numerical type while the 'Citable docs per Capita' is an object type. I converted the column to float using astype. I had the same problem with some np functions: count_nonzero and sum worked while mean and std didn't.

How to prevent a double-click using jQuery?

If what you really want is to avoid multiple form submissions, and not just prevent double click, using jQuery one() on a button's click event can be problematic if there's client-side validation (such as text fields marked as required). That's because click triggers client-side validation, and if the validation fails you cannot use the button again. To avoid this, one() can still be used directly on the form's submit event. This is the cleanest jQuery-based solution I found for that:

<script type="text/javascript">
$("#my-signup-form").one("submit", function() {
    // Just disable the button.
    // There will be only one form submission.
    $("#my-signup-btn").prop("disabled", true);
});
</script>

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

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

Use set -e

#!/bin/bash

set -e

/bin/command-that-fails
/bin/command-that-fails2

The script will terminate after the first line that fails (returns nonzero exit code). In this case, command-that-fails2 will not run.

If you were to check the return status of every single command, your script would look like this:

#!/bin/bash

# I'm assuming you're using make

cd /project-dir
make
if [[ $? -ne 0 ]] ; then
    exit 1
fi

cd /project-dir2
make
if [[ $? -ne 0 ]] ; then
    exit 1
fi

With set -e it would look like:

#!/bin/bash

set -e

cd /project-dir
make

cd /project-dir2
make

Any command that fails will cause the entire script to fail and return an exit status you can check with $?. If your script is very long or you're building a lot of stuff it's going to get pretty ugly if you add return status checks everywhere.

Saving lists to txt file

Assuming your Generic List is of type String:

TextWriter tw = new StreamWriter("SavedList.txt");

foreach (String s in Lists.verbList)
   tw.WriteLine(s);

tw.Close();

Alternatively, with the using keyword:

using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
   foreach (String s in Lists.verbList)
      tw.WriteLine(s);
}

return error message with actionResult

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}

What does the return keyword do in a void method in Java?

See this example, you want to add to the list conditionally. Without the word "return", all ifs will be executed and add to the ArrayList!

    Arraylist<String> list =  new ArrayList<>();

    public void addingToTheList() {

    if(isSunday()) {
        list.add("Pray today")
        return;
    }

    if(isMonday()) {
        list.add("Work today"
        return;
    }

    if(isTuesday()) {
        list.add("Tr today")
        return;
    }
}

MySQL select query with multiple conditions

Lets suppose there is a table with following describe command for table (hello)- name char(100), id integer, count integer, city char(100).

we have following basic commands for MySQL -

select * from hello;
select name, city from hello;
etc 

select name from hello where id = 8;
select id from hello where name = 'GAURAV';

now lets see multiple where condition -

select name from hello where id = 3 or id = 4 or id = 8 or id = 22;

select name from hello where id =3 and count = 3 city = 'Delhi';

This is how we can use multiple where commands in MySQL.

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

I had the same problem, my code is below:

private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
private Statement stmt = conn.createStatement();

I have not loaded the driver class, but it works locally, I can query the results from MySQL, however, it does not work when I deploy it to Tomcat, and the errors below occur:

No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud

so I loaded the driver class, as below, when I saw other answers posted:

Class.forName("com.mysql.jdbc.Driver");

It works now! I don't know why it works well locally, I need your help, thank you so much!

IIS_IUSRS and IUSR permissions in IIS8

@EvilDr You can create an IUSR_[identifier] account within your AD environment and let the particular application pool run under that IUSR_[identifier] account:

"Application pool" > "Advanced Settings" > "Identity" > "Custom account"

Set your website to "Applicaton user (pass-through authentication)" and not "Specific user", in the Advanced Settings.

Now give that IUSR_[identifier] the appropriate NTFS permissions on files and folders, for example: modify on companydata.

C# Wait until condition is true

After digging a lot of stuff, finally, I came up with a good solution that doesn't hang the CI :) Suit it to your needs!

public static Task WaitUntil<T>(T elem, Func<T, bool> predicate, int seconds = 10)
{
    var tcs = new TaskCompletionSource<int>();
    using(var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
    {
        cancellationTokenSource.Token.Register(() =>
        {
            tcs.SetException(
                new TimeoutException($"Waiting predicate {predicate} for {elem.GetType()} timed out!"));
            tcs.TrySetCanceled();
        });

        while(!cancellationTokenSource.IsCancellationRequested)
        {
            try
            {
                if (!predicate(elem))
                {
                    continue;
                }
            }
            catch(Exception e)
            {
                tcs.TrySetException(e);
            }

            tcs.SetResult(0);
            break;
        }

        return tcs.Task;
    }
}

How do you run a .exe with parameters using vba's shell()?

Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.

Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
 " -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)

Open some text file.

Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")

Open some application.

Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)

Hope this helps!

How can I see an the output of my C programs using Dev-C++?

Add this to your header file #include and then in the end add this line : getch();

error MSB6006: "cmd.exe" exited with code 1

I solved this. double click this error leads to behavior.

  1. open .vcxproj file of your project
  2. search for tag
  3. check carefully what's going inside this tag, the path is right? difference between debug and release, and fix it
  4. clean and rebuild

for my case. a miss match of debug and release mod kills my afternoon.

          <Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">copy %(Filename)%(Extension) ..\..\cvd\
</Command>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
    </CustomBuild>

Combine multiple Collections into a single logical Collection?

With Guava, you can use Iterables.concat(Iterable<T> ...), it creates a live view of all the iterables, concatenated into one (if you change the iterables, the concatenated version also changes). Then wrap the concatenated iterable with Iterables.unmodifiableIterable(Iterable<T>) (I hadn't seen the read-only requirement earlier).

From the Iterables.concat( .. ) JavaDocs:

Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary. The returned iterable's iterator supports remove() when the corresponding input iterator supports it.

While this doesn't explicitly say that this is a live view, the last sentence implies that it is (supporting the Iterator.remove() method only if the backing iterator supports it is not possible unless using a live view)

Sample Code:

final List<Integer> first  = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third  = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
    Iterables.unmodifiableIterable(
        Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9999999]


Edit:

By Request from Damian, here's a similar method that returns a live Collection View

public final class CollectionsX {

    static class JoinedCollectionView<E> implements Collection<E> {

        private final Collection<? extends E>[] items;

        public JoinedCollectionView(final Collection<? extends E>[] items) {
            this.items = items;
        }

        @Override
        public boolean addAll(final Collection<? extends E> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void clear() {
            for (final Collection<? extends E> coll : items) {
                coll.clear();
            }
        }

        @Override
        public boolean contains(final Object o) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean containsAll(final Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean isEmpty() {
            return !iterator().hasNext();
        }

        @Override
        public Iterator<E> iterator() {
            return Iterables.concat(items).iterator();
        }

        @Override
        public boolean remove(final Object o) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean removeAll(final Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean retainAll(final Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public int size() {
            int ct = 0;
            for (final Collection<? extends E> coll : items) {
                ct += coll.size();
            }
            return ct;
        }

        @Override
        public Object[] toArray() {
            throw new UnsupportedOperationException();
        }

        @Override
        public <T> T[] toArray(T[] a) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean add(E e) {
            throw new UnsupportedOperationException();
        }

    }

    /**
     * Returns a live aggregated collection view of the collections passed in.
     * <p>
     * All methods except {@link Collection#size()}, {@link Collection#clear()},
     * {@link Collection#isEmpty()} and {@link Iterable#iterator()}
     *  throw {@link UnsupportedOperationException} in the returned Collection.
     * <p>
     * None of the above methods is thread safe (nor would there be an easy way
     * of making them).
     */
    public static <T> Collection<T> combine(
        final Collection<? extends T>... items) {
        return new JoinedCollectionView<T>(items);
    }

    private CollectionsX() {
    }

}

is the + operator less performant than StringBuffer.append()

Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.

Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis

join() once, concat() once, join() for, += for, concat() for

More:
Ajaxian >> String Performance in IE: Array.join vs += continued

case statement in where clause - SQL Server

You don't need case in the where statement, just use parentheses and or:

Select * From Times
WHERE StartDate <= @Date AND EndDate >= @Date
AND (
    (@day = 'Monday' AND Monday = 1)
    OR (@day = 'Tuesday' AND Tuesday = 1)
    OR Wednesday = 1
)

Additionally, your syntax is wrong for a case. It doesn't append things to the string--it returns a single value. You'd want something like this, if you were actually going to use a case statement (which you shouldn't):

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND 1 = CASE WHEN @day = 'Monday' THEN Monday
             WHEN @day = 'Tuesday' THEN Tuesday
             ELSE Wednesday
        END 

And just for an extra umph, you can use the between operator for your date:

where @Date between StartDate and EndDate

Making your final query:

select
    * 
from 
    Times
where
    @Date between StartDate and EndDate
    and (
        (@day = 'Monday' and Monday = 1)
        or (@day = 'Tuesday' and Tuesday = 1)
        or Wednesday = 1
    )

TERM environment variable not set

SOLVED: On Debian 10 by adding "EXPORT TERM=xterm" on the Script executed by CRONTAB (root) but executed as www-data.

$ crontab -e

*/15 * * * * /bin/su - www-data -s /bin/bash -c '/usr/local/bin/todos.sh'

FILE=/usr/local/bin/todos.sh

#!/bin/bash -p
export TERM=xterm && cd /var/www/dokuwiki/data/pages && clear && grep -r -h '|(TO-DO)' > /var/www/todos.txt && chmod 664 /var/www/todos.txt && chown www-data:www-data /var/www/todos.txt

font awesome icon in select option

If you want the caret down symbol, remove the "appearence: none" it implies to remove webkit and moz- as well from select in css.

Taking multiple inputs from user in python

# the more input you want to add variable accordingly
x,y,z=input("enter the numbers: ").split( ) 
#for printing 
print("value of x: ",x)
print("value of y: ",y)
print("value of z: ",z)

#for multiple inputs    
#using list, map
#split seperates values by ( )single space in this case

x=list(map(int,input("enter the numbers: ").split( )))

#we will get list of our desired elements 

print("print list: ",x)

hope you got your answer :)

How to specify a port to run a create-react-app based project?

In your package.json, go to scripts and use --port 4000 or set PORT=4000, like in the example below:

package.json (Windows):

"scripts": {
    "start": "set PORT=4000 && react-scripts start"
}

package.json (Ubuntu):

"scripts": {
    "start": "export PORT=4000 && react-scripts start"
}

How to run a SQL query on an Excel table?

Might I suggest giving QueryStorm a try - it's a plugin for Excel that makes it quite convenient to use SQL in Excel.

Also, it's freemium. If you don't care about autocomplete, error squigglies etc, you can use it for free. Just download and install, and you have SQL support in Excel.

Disclaimer: I'm the author.

How do I install a plugin for vim?

I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.

Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).

What do parentheses surrounding an object/function/class declaration mean?

Juts to follow up on what Andy Hume and others have said:

The '()' surrounding the anonymous function is the 'grouping operator' as defined in section 11.1.6 of the ECMA spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.

Taken verbatim from the docs:

11.1.6 The Grouping Operator

The production PrimaryExpression : ( Expression ) is evaluated as follows:

  1. Return the result of evaluating Expression. This may be of type Reference.

In this context the function is treated as an expression.

How do I retrieve an HTML element's actual width and height?

You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:

<style type="text/css">
    html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
    body {display:table-cell; vertical-align:middle;}
    div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>

This is the perfect solution. It centers <div> of any size, and shrink-wraps it to size of its content.

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

Intellij idea subversion checkout error: `Cannot run program "svn"`

If you're going with Manoj's solution (https://stackoverflow.com/a/29509007/2024713) and still having the problem try switching off "Enable interactive mode" if available in your version of IntelliJ. It worked for me

expected assignment or function call: no-unused-expressions ReactJS

This happens because you put bracket of return on the next line. That might be a common mistake if you write js without semicolons and use a style where you put opened braces on the next line.

Interpreter thinks that you return undefined and doesn't check your next line. That's the return operator thing.

Put your opened bracket on the same line with the return.

overlay a smaller image on a larger image python OpenCv

A simple way to achieve what you want:

import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

the result image

Update

I suppose you want to take care of the alpha channel too. Here is a quick and dirty way of doing so:

s_img = cv2.imread("smaller_image.png", -1)

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])

result image with alpha

Which icon sizes should my Windows application's icon include?

TL;DR. In Visual Studio 2019, when you add an Icon resource to a Win32 (desktop) application you get an auto-generated icon file that has the formats below. I assume that the #1 developer tool for Windows does this right. Thus, a Windows compatible should have the following formats:

| Resolution | Color depth | Format |
|:-----------|------------:|:------:|
| 256x256    |      32-bit |  PNG   |
| 64x64      |      32-bit |  BMP   |
| 48x48      |      32-bit |  BMP   |
| 32x32      |      32-bit |  BMP   |
| 16x16      |      32-bit |  BMP   |
| 48x48      |       8-bit |  BMP   |
| 32x32      |       8-bit |  BMP   |
| 16x16      |       8-bit |  BMP   |

Output ("echo") a variable to a text file

Note: The answer below is written from the perspective of Windows PowerShell.
However, it applies to the cross-platform PowerShell Core edition (v6+) as well, except that the latter - commendably - consistently defaults to BOM-less UTF-8 character encoding, which is the most widely compatible one across platforms and cultures.
.


To complement bigtv's helpful answer helpful answer with a more concise alternative and background information:

# > $file is effectively the same as | Out-File $file
# Objects are written the same way they display in the console.
# Default character encoding is UTF-16LE (mostly 2 bytes per char.), with BOM.
# Use Out-File -Encoding <name> to change the encoding.
$env:computername > $file

# Set-Content calls .ToString() on each object to output.
# Default character encoding is "ANSI" (culture-specific, single-byte).
# Use Set-Content -Encoding <name> to change the encoding.
# Use Set-Content rather than Add-Content; the latter is for *appending* to a file.
$env:computername | Set-Content $file 

When outputting to a text file, you have 2 fundamental choices that use different object representations and, in Windows PowerShell (as opposed to PowerShell Core), also employ different default character encodings:

  • Out-File (or >) / Out-File -Append (or >>):

    • Suitable for output objects of any type, because PowerShell's default output formatting is applied to the output objects.

      • In other words: you get the same output as when printing to the console.
    • The default encoding, which can be changed with the -Encoding parameter, is Unicode, which is UTF-16LE in which most characters are encoded as 2 bytes. The advantage of a Unicode encoding such as UTF-16LE is that it is a global alphabet, capable of encoding all characters from all human languages.

      • In PSv5.1+, you can change the encoding used by > and >>, via the $PSDefaultParameterValues preference variable, taking advantage of the fact that > and >> are now effectively aliases of Out-File and Out-File -Append. To change to UTF-8, for instance, use:
        $PSDefaultParameterValues['Out-File:Encoding']='UTF8'
  • Set-Content / Add-Content:

    • For writing strings and instances of types known to have meaningful string representations, such as the .NET primitive data types (Booleans, integers, ...).

      • .psobject.ToString() method is called on each output object, which results in meaningless representations for types that don't explicitly implement a meaningful representation; [hashtable] instances are an example:
        @{ one = 1 } | Set-Content t.txt writes literal System.Collections.Hashtable to t.txt, which is the result of @{ one = 1 }.ToString().
    • The default encoding, which can be changed with the -Encoding parameter, is Default, which is the system's "ANSI" code page, a the single-byte culture-specific legacy encoding for non-Unicode applications, most commonly Windows-1252.
      Note that the documentation currently incorrectly claims that ASCII is the default encoding.

    • Note that Add-Content's purpose is to append content to an existing file, and it is only equivalent to Set-Content if the target file doesn't exist yet.
      Furthermore, the default or specified encoding is blindly applied, irrespective of the file's existing contents' encoding.

Out-File / > / Set-Content / Add-Content all act culture-sensitively, i.e., they produce representations suitable for the current culture (locale), if available (though custom formatting data is free to define its own, culture-invariant representation - see Get-Help about_format.ps1xml). This contrasts with PowerShell's string expansion (string interpolation in double-quoted strings), which is culture-invariant - see this answer of mine.

As for performance: Since Set-Content doesn't have to apply default formatting to its input, it performs better.


As for the OP's symptom with Add-Content:

Since $env:COMPUTERNAME cannot contain non-ASCII characters, Add-Content's output, using "ANSI" encoding, should not result in ? characters in the output, and the likeliest explanation is that the ? were part of the preexisting content in output file $file, which Add-Content appended to.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

Pls Update .env file

 DB_HOST=localhost
 DB_DATABASE=homestead
 DB_USERNAME=homestead
 DB_PASSWORD=secret

After then restart server

How to add a where clause in a MySQL Insert statement?

In an insert statement you wouldn't have an existing row to do a where claues on? You are inserting a new row, did you mean to do an update statment?

update users set username='JACK' and password='123' WHERE id='1';

Creating a byte array from a stream

It really depends on whether or not you can trust s.Length. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

With .NET 4 and above, I'd use Stream.CopyTo, which is basically equivalent to the loop in my code - create the MemoryStream, call stream.CopyTo(ms) and then return ms.ToArray(). Job done.

I should perhaps explain why my answer is longer than the others. Stream.Read doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. BinaryReader.Read will keep going until the end of the stream or your specified size, but you still have to know the size to start with.

The above method will keep reading (and copying into a MemoryStream) until it runs out of data. It then asks the MemoryStream to return a copy of the data in an array. If you know the size to start with - or think you know the size, without being sure - you can construct the MemoryStream to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by MemoryStream.GetBuffer) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.

See this article for more info (and an alternative implementation).

Java - removing first character of a string

substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.

The substring begins at the specified start and extends to the character at index end - 1.

It has two forms. The first is

  1. String substring(int FirstIndex)

Here, FirstIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at FirstIndex and runs to the end of the invoking string.

  1. String substring(int FirstIndex, int endIndex)

Here, FirstIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.

Example

   String str = "Amiyo";
   // prints substring from index 3
   System.out.println("substring is = " + str.substring(3)); // Output 'yo'

Getting a list item by index

You can use the ElementAt extension method on the list.

For example:

// Get the first item from the list

using System.Linq;

var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);

// Do something with firstItem

Calculate days between two Dates in Java 8

get days between two dates date is instance of java.util.Date

public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
            return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
        }

Sorting rows in a data table

try this:

DataTable DT = new DataTable();
DataTable sortedDT = DT;
sortedDT.Clear();
foreach (DataRow row in DT.Select("", "DiffTotal desc"))
{
    sortedDT.NewRow();
    sortedDT.Rows.Add(row);
}
DT = sortedDT;

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

How do you set your pythonpath in an already-created virtualenv?

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

Forward declaration of a typedef in C++

Like @BillKotsias, I used inheritance, and it worked for me.

I changed this mess (which required all the boost headers in my declaration *.h)

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>

typedef boost::accumulators::accumulator_set<float,
 boost::accumulators::features<
  boost::accumulators::tag::median,
  boost::accumulators::tag::mean,
  boost::accumulators::tag::min,
  boost::accumulators::tag::max
 >> VanillaAccumulator_t ;
std::unique_ptr<VanillaAccumulator_t> acc;

into this declaration (*.h)

class VanillaAccumulator;
std::unique_ptr<VanillaAccumulator> acc;

and the implementation (*.cpp) was

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>

class VanillaAccumulator : public
  boost::accumulators::accumulator_set<float,
    boost::accumulators::features<
      boost::accumulators::tag::median,
      boost::accumulators::tag::mean,
      boost::accumulators::tag::min,
      boost::accumulators::tag::max
>>
{
};

What is a user agent stylesheet?

I have a solution. Check this:

Error

<link href="assets/css/bootstrap.min.css" rel="text/css" type="stylesheet">

Correct

<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">

How to dismiss notification after action has been clicked

You will need to run the following code after your intent is fired to remove the notification.

NotificationManagerCompat.from(this).cancel(null, notificationId);

NB: notificationId is the same id passed to run your notification

How to implement common bash idioms in Python?

If your textfile manipulation usually is one-time, possibly done on the shell-prompt, you will not get anything better from python.

On the other hand, if you usually have to do the same (or similar) task over and over, and you have to write your scripts for doing that, then python is great - and you can easily create your own libraries (you can do that with shell scripts too, but it's more cumbersome).

A very simple example to get a feeling.

import popen2
stdout_text, stdin_text=popen2.popen2("your-shell-command-here")
for line in stdout_text:
  if line.startswith("#"):
    pass
  else
    jobID=int(line.split(",")[0].split()[1].lstrip("<").rstrip(">"))
    # do something with jobID

Check also sys and getopt module, they are the first you will need.

Resource leak: 'in' is never closed

Okay, seriously, in many cases at least, this is actually a bug. It shows up in VS Code as well, and it's the linter noticing that you've reached the end of the enclosing scope without closing the scanner object, but not recognizing that closing all open file descriptors is part of process termination. There's no resource leak because the resources are all cleaned up at termination, and the process goes away, leaving nowhere for the resource to be held.

How do I fix 'ImportError: cannot import name IncompleteRead'?

  1. sudo apt-get remove python-pip
  2. sudo easy_install requests==2.3.0
  3. sudo apt-get install python-pip

Where is shared_ptr?

There are at least three places where you may find shared_ptr:

  1. If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.

  2. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.

  3. Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.

How can I compare strings in C using a `switch` statement?

My preferred method for doing this is via a hash function (borrowed from here). This allows you to utilize the efficiency of a switch statement even when working with char *'s:

#include "stdio.h"

#define LS 5863588
#define CD 5863276
#define MKDIR 210720772860
#define PWD 193502992

const unsigned long hash(const char *str) {
    unsigned long hash = 5381;  
    int c;

    while ((c = *str++))
        hash = ((hash << 5) + hash) + c;
    return hash;
}

int main(int argc, char *argv[]) {
    char *p_command = argv[1];
    switch(hash(p_command)) {
    case LS:
        printf("Running ls...\n");
        break;
    case CD:
        printf("Running cd...\n");
        break;
    case MKDIR:
        printf("Running mkdir...\n");
        break;
    case PWD:
        printf("Running pwd...\n");
        break;
    default:
        printf("[ERROR] '%s' is not a valid command.\n", p_command);
    }
}

Of course, this approach requires that the hash values for all possible accepted char *'s are calculated in advance. I don't think this is too much of an issue; however, since the switch statement operates on fixed values regardless. A simple program can be made to pass char *'s through the hash function and output their results. These results can then be defined via macros as I have done above.

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib

download a file from Spring boot rest service

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Difference between git pull and git pull --rebase

For this is important to understand the difference between Merge and Rebase.

Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards.

For details refer - http://www.derekgourlay.com/archives/428

How to download file in swift?

Swift 4 and Swift 5 Version if Anyone still needs this

import Foundation

class FileDownloader {

    static func loadFileSync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else if let dataFromURL = NSData(contentsOf: url)
        {
            if dataFromURL.write(to: destinationUrl, atomically: true)
            {
                print("file saved [\(destinationUrl.path)]")
                completion(destinationUrl.path, nil)
            }
            else
            {
                print("error saving file")
                let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                completion(destinationUrl.path, error)
            }
        }
        else
        {
            let error = NSError(domain:"Error downloading file", code:1002, userInfo:nil)
            completion(destinationUrl.path, error)
        }
    }

    static func loadFileAsync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else
        {
            let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            let task = session.dataTask(with: request, completionHandler:
            {
                data, response, error in
                if error == nil
                {
                    if let response = response as? HTTPURLResponse
                    {
                        if response.statusCode == 200
                        {
                            if let data = data
                            {
                                if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                                {
                                    completion(destinationUrl.path, error)
                                }
                                else
                                {
                                    completion(destinationUrl.path, error)
                                }
                            }
                            else
                            {
                                completion(destinationUrl.path, error)
                            }
                        }
                    }
                }
                else
                {
                    completion(destinationUrl.path, error)
                }
            })
            task.resume()
        }
    }
}

Here is how to call this method :-

let url = URL(string: "http://www.filedownloader.com/mydemofile.pdf")
FileDownloader.loadFileAsync(url: url!) { (path, error) in
    print("PDF File downloaded to : \(path!)")
}

Scatter plots in Pandas/Pyplot: How to plot by category

From matplotlib 3.1 onwards you can use .legend_elements(). An example is shown in Automated legend creation. The advantage is that a single scatter call can be used.

In this case:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), 
                  index = pd.date_range('2010-01-01', freq = 'M', periods = 10), 
                  columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)


fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ax.legend(*sc.legend_elements())
plt.show()

enter image description here

In case the keys were not directly given as numbers, it would look as

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), 
                  index = pd.date_range('2010-01-01', freq = 'M', periods = 10), 
                  columns = ('one', 'two', 'three'))
df['key1'] = list("AAABBBCCCC")

labels, index = np.unique(df["key1"], return_inverse=True)

fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = index, alpha = 0.8)
ax.legend(sc.legend_elements()[0], labels)
plt.show()

enter image description here

MySQL "Or" Condition

Wrap your AND logic in parenthesis, like this:

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

Remove file from SVN repository without deleting local copy

When you want to remove one xxx.java file from SVN:

  1. Go to workspace path where the file is located.
  2. Delete that file from the folder (xxx.java)
  3. Right click and commit, then a window will open.
  4. Select the file you deleted (xxx.java) from the folder, and again right click and delete.. it will remove the file from SVN.

How do I format a String in an email so Outlook will print the line breaks?

If you can add in a '.' (dot) character at the end of each line, this seems to prevent Outlook ruining text formatting.

JQuery show and hide div on mouse click (animate)

Use slideToggle(500) function with a duration in milliseconds for getting a better effect.

Sample Html

<body>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">2.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details ">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">3.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
</body>

In your js file, if you need child propagation for the animation then remove the second click event function and its codes.

$(document).ready(function(){
    $(".js--growth-step").click(function(event){
       $(this).children(".step-details").slideToggle(500);
         return false;
    });
//for stoping child to manipulate the animation
    $(".js--growth-step .step-details").click(function(event) {
        event.stopPropagation();
   });
});

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Set the absolute position of a view

A more cleaner and dynamic way without hardcoding any pixel values in the code.

I wanted to position a dialog (which I inflate on the fly) exactly below a clicked button.

and solved it this way :

    // get the yoffset of the position where your View has to be placed 
    final int yoffset = < calculate the position of the view >

    // position using top margin
    if(myView.getLayoutParams() instanceof MarginLayoutParams) {
        ((MarginLayoutParams) myView.getLayoutParams()).topMargin = yOffset;
    }

However you have to make sure the parent layout of myView is an instance of RelativeLayout.

more complete code :

    // identify the button
    final Button clickedButton = <... code to find the button here ...>

    // inflate the dialog - the following style preserves xml layout params
    final View floatingDialog = 
        this.getLayoutInflater().inflate(R.layout.floating_dialog,
            this.floatingDialogContainer, false);

    this.floatingDialogContainer.addView(floatingDialog);

    // get the buttons position
    final int[] buttonPos = new int[2];
    clickedButton.getLocationOnScreen(buttonPos);        
    final int yOffset =  buttonPos[1] + clickedButton.getHeight();

    // position using top margin
    if(floatingDialog.getLayoutParams() instanceof MarginLayoutParams) {
        ((MarginLayoutParams) floatingDialog.getLayoutParams()).topMargin = yOffset;
    }

This way you can still expect the target view to adjust to any layout parameters set using layout XML files, instead of hardcoding those pixels/dps in your Java code.

Compiling simple Hello World program on OS X via command line

user@host> g++ hw.cpp
user@host> ./a.out

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

How to retrieve field names from temporary table (SQL Server 2008)

select * from tempdb.sys.columns where object_id =
object_id('tempdb..#mytemptable');

How to install SQL Server Management Studio 2008 component only

If you have the SQL Server 2008 Installation media, you can install just the Client/Workstation Components. You don't have to install the database engine to install the workstation tools, but if you plan to do Integration Services development, you do need to install the Integration Services Engine on the workstation for BIDS to be able to be used for development. Keep in mind that Visual Studio 2010 does not have BI development support currently, so you have to install BIDS from the SQL Installation media and use the Visual Studio 2008 BI Development Studio that installs under the SQL Server 2008 folder in Program Files if you need to do any SSIS, SSRS, or SSAS development from the workstation.

As mentioned in the comments you can download Management Studio Express free from Microsoft, but if you already have the installation media for SQL Server Standard/Enterprise/Developer edition, you'd be better off using what you have.

Download SSMS 2008 Express

Utils to read resource text file to String (Java)

package test;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            String fileContent = getFileFromResources("resourcesFile.txt");
            System.out.println(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //USE THIS FUNCTION TO READ CONTENT OF A FILE, IT MUST EXIST IN "RESOURCES" FOLDER
    public static String getFileFromResources(String fileName) throws Exception {
        ClassLoader classLoader = Main.class.getClassLoader();
        InputStream stream = classLoader.getResourceAsStream(fileName);
        String text = null;
        try (Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) {
            text = scanner.useDelimiter("\\A").next();
        }
        return text;
    }
}

Is null reference possible?

clang++ 3.5 even warns on it:

/tmp/a.C:3:7: warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to
      always evaluate to false [-Wtautological-undefined-compare]
if( & nullReference == 0 ) // null reference
      ^~~~~~~~~~~~~    ~
1 warning generated.

How to merge every two lines into one from the command line?

A more-general solution (allows for more than one follow-up line to be joined) as a shell script. This adds a line between each, because I needed visibility, but that is easily remedied. This example is where the "key" line ended in : and no other lines did.

#!/bin/bash
#
# join "The rest of the story" when the first line of each   story
# matches $PATTERN
# Nice for looking for specific changes in bart output
#

PATTERN='*:';
LINEOUT=""
while read line; do
    case $line in
        $PATTERN)
                echo ""
                echo $LINEOUT
                LINEOUT="$line"
                        ;;
        "")
                LINEOUT=""
                echo ""
                ;;

        *)      LINEOUT="$LINEOUT $line"
                ;;
    esac        
done

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

How to reset Android Studio

If you are using Windows and Android Studio 4 and above, the location to the directory is C:\Users(your name)\AppData\Roaming\Google\

Simple delete the Google folder to reset all settings. Open Android Studio and do not import settings when asked

How to directly move camera to current location in Google Maps Android API v2?

Just change moveCamera to animateCamera like below

Googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16F))

What is a deadlock?

Above some explanations are nice. Hope this may also useful: https://ora-data.blogspot.in/2017/04/deadlock-in-oracle.html

In a database, when a session (e.g. ora) wants a resource held by another session (e.g. data), but that session (data) also wants a resource which is held by the first session (ora). There can be more than 2 sessions involved also but idea will be the same. Actually, Deadlocks prevent some transactions from continuing to work. For example: Suppose, ORA-DATA holds lock A and requests lock B And SKU holds lock B and requests lock A.

Thanks,

Count number of objects in list

length(x)

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

lengths(x)

Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.

Download multiple files as a zip-file using php

Create a zip file, then download the file, by setting the header, read the zip contents and output the file.

http://www.php.net/manual/en/function.ziparchive-addfile.php

http://php.net/manual/en/function.header.php

foreach with index

You can do the following

foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
{
   if (it.Index > SomeNumber) //      
}

This will create an anonymous type value for every entry in the collection. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection

What is 'Context' on Android?

Think of it as the VM that has siloed the process the app or service is running in. The siloed environment has access to a bunch of underlying system information and certain permitted resources. You need that context to get at those services.

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

Jenkins/Hudson - accessing the current build number?

As per Jenkins Documentation,

BUILD_NUMBER

is used. This number is identify how many times jenkins run this build process $BUILD_NUMBER is general syntax for it.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Here's what's working for me

on windows

1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)

Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.

  1. Click Start -> All Programs -> Accessories

  2. Right click Notepad and select Run as administrator

  3. Click Continue on the "Windows needs your permission" UAC window.

  4. When Notepad opens Click File -> Open

  5. In the filename field type C:\Windows\System32\Drivers\etc\hosts

  6. Click Open

  7. Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net

  8. Save

  9. Close and restart browsers

On Mac or Linux:

  1. Open /etc/hosts with su permission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it

When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.

Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.

2) create the certificate using that localdev.url

TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.

3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

Windows Scipy Install: No Lapack/Blas Resources Found

Sorry to necro, but this is the first google search result. This is the solution that worked for me:

  1. Download numpy+mkl wheel from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy. Use the version that is the same as your python version (check using python -V). Eg. if your python is 3.5.2, download the wheel which shows cp35

  2. Open command prompt and navigate to the folder where you downloaded the wheel. Run the command: pip install [file name of wheel]

  3. Download the SciPy wheel from: http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy (similar to the step above).

  4. As above, pip install [file name of wheel]

Does C have a "foreach" loop construct?

Here is a full program example of a for-each macro in C99:

#include <stdio.h>

typedef struct list_node list_node;
struct list_node {
    list_node *next;
    void *data;
};

#define FOR_EACH(item, list) \
    for (list_node *(item) = (list); (item); (item) = (item)->next)

int
main(int argc, char *argv[])
{
    list_node list[] = {
        { .next = &list[1], .data = "test 1" },
        { .next = &list[2], .data = "test 2" },
        { .next = NULL,     .data = "test 3" }
    };

    FOR_EACH(item, list)
        puts((char *) item->data);

    return 0;
}

Display date/time in user's locale format and time offset

getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.

There's a few more options discussed in the answer to this question

python replace single backslash with double backslash

Use:

string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")

Escape the \ character.

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

Changing navigation bar color in Swift

simply call the this extension and pass the color it will automatically change the color of nav bar

extension UINavigationController {
    
     func setNavigationBarColor(color : UIColor){
            self.navigationBar.barTintColor = color
        }
    }

in the view didload or in viewwill appear call

self.navigationController?.setNavigationBarColor(color: <#T##UIColor#>)

Update built-in vim on Mac OS X

I just installed vim by:

brew install vim

now the new vim is accessed by vim and the old vim (built-in vim) by vi

URL.Action() including route values

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

How to print the number of characters in each line of a text file

Here is example using xargs:

$ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file

_tkinter.TclError: no display name and no $DISPLAY environment variable

I want to add an answer here that noone has explicitly stated with implementation.

This is a great resource to refer to for this failure: https://matplotlib.org/faq/usage_faq.html

In my case, using matplotlib.use did not work because it was somehow already set somewhere else. However, I was able to get beyond the error by defining an environment variable:

export MPLBACKEND=Agg

This takes care of the issue.

My error was in a CircleCI flow specifically, and this resolved the failing tests. One wierd thing was, my tests would pass when run using pytest, however would fail when using parallelism along with circleci tests split feature. However, declaring this env variable resolved the issue.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Your receiver:

public class MyReceiver extends BroadcastReceiver {   

    @Override
    public void onReceive(Context context, Intent intent) {

     Intent myIntent = new Intent(context, YourService.class);
     context.startService(myIntent);

    }
}

Your AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.broadcast.receiver.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

        <activity android:name=".BR_Example"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
        <receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

    <!-- Adding the permission -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

</manifest>

gradlew: Permission Denied

This issue occur when you migrate your android project build in windows to any unix operating system (Linux). So you need to run the below command in your project directory to convert dos Line Break to Unix Line Break.

find . -type f -print0 | xargs -0 dos2unix

If you dont have dos2unix installed. Install it using

In CentOs/Fedora

yum install dos2unix

In Ubuntu and other distributions

sudo apt install dos2unix

Convert a row of a data frame to vector

When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:

as.numeric(df[1,])

As @Roland suggests, unlist(df[1,]) will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,])) is another, slightly more explicit way to get to the same result.

As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,]) instead.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

You can disable caching globally using $.ajaxSetup(), for example:

$.ajaxSetup({ cache: false });

This appends a timestamp to the querystring when making the request. To turn cache off for a particular $.ajax() call, set cache: false on it locally, like this:

$.ajax({
  cache: false,
  //other options...
});

How to get browser width using JavaScript code?

It's a pain in the ass. I recommend skipping the nonsense and using jQuery, which lets you just do $(window).width().

What is the best way to manage a user's session in React?

This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.

jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
    res.json({
      token
  });

user object in here is the user data which you want to keep in the session

localStorage.setItem('session',JSON.stringify(token));

String Resource new line /n not possible?

Although the actual problem was with the forward slash still for those using backslash but still saw \n in their layout.

Well i was also puzzled at first by why \n is not working in the layout but it seems that when you actually see that layout in an actual device it creates a line break so no need to worry what it shows on layout display screen your line breaks would be working perfectly fine on devices.

How to change TextBox's Background color?

in web application in .cs page

   txtbox.Style.Add("background-color","black");

in css specify it by using backcolor property

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

How to extract custom header value in Web API message handler?

For ASP.NET you can get the header directly from parameter in controller method using this simple library/package. It provides a [FromHeader] attribute just like you have in ASP.NET Core :). For example:

    ...
    using RazHeaderAttribute.Attributes;

    [Route("api/{controller}")]
    public class RandomController : ApiController 
    {
        ...
        // GET api/random
        [HttpGet]
        public IEnumerable<string> Get([FromHeader("pages")] int page, [FromHeader] string rows)
        {
            // Print in the debug window to be sure our bound stuff are passed :)
            Debug.WriteLine($"Rows {rows}, Page {page}");
            ...
        }
    }

Does Python SciPy need BLAS?

On Fedora, this works:

 yum install lapack lapack-devel blas blas-devel
 pip install numpy
 pip install scipy

Remember to install 'lapack-devel' and 'blas-devel' in addition to 'blas' and 'lapack' otherwise you'll get the error you mentioned or the "numpy.distutils.system_info.LapackNotFoundError" error.

Yes or No confirm box using jQuery

All the example I've seen aren't reusable for different "yes/no" type questions. I was looking for something that would allow me to specify a callback so I could call for any situation.

The following is working well for me:

$.extend({ confirm: function (title, message, yesText, yesCallback) {
    $("<div></div>").dialog( {
        buttons: [{
            text: yesText,
            click: function() {
                yesCallback();
                $( this ).remove();
            }
        },
        {
            text: "Cancel",
            click: function() {
                $( this ).remove();
            }
        }
        ],
        close: function (event, ui) { $(this).remove(); },
        resizable: false,
        title: title,
        modal: true
    }).text(message).parent().addClass("alert");
}
});

I then call it like this:

var deleteOk = function() {
    uploadFile.del(fileid, function() {alert("Deleted")})
};

$.confirm(
    "CONFIRM", //title
    "Delete " + filename + "?", //message
    "Delete", //button text
    deleteOk //"yes" callback
);

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

Using the standard CustomCreationConverter, I was struggling to work how to generate the correct type (Person or Employee), because in order to determine this you need to analyse the JSON and there is no built in way to do this using the Create method.

I found a discussion thread pertaining to type conversion and it turned out to provide the answer. Here is a link: Type converting.

What's required is to subclass JsonConverter, overriding the ReadJson method and creating a new abstract Create method which accepts a JObject.

The JObject class provides a means to load a JSON object and provides access to the data within this object.

The overridden ReadJson method creates a JObject and invokes the Create method (implemented by our derived converter class), passing in the JObject instance.

This JObject instance can then be analysed to determine the correct type by checking existence of certain fields.

Example

string json = "[{
        \"Department\": \"Department1\",
        \"JobTitle\": \"JobTitle1\",
        \"FirstName\": \"FirstName1\",
        \"LastName\": \"LastName1\"
    },{
        \"Department\": \"Department2\",
        \"JobTitle\": \"JobTitle2\",
        \"FirstName\": \"FirstName2\",
        \"LastName\": \"LastName2\"
    },
        {\"Skill\": \"Painter\",
        \"FirstName\": \"FirstName3\",
        \"LastName\": \"LastName3\"
    }]";

List<Person> persons = 
    JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());

...

public class PersonConverter : JsonCreationConverter<Person>
{
    protected override Person Create(Type objectType, JObject jObject)
    {
        if (FieldExists("Skill", jObject))
        {
            return new Artist();
        }
        else if (FieldExists("Department", jObject))
        {
            return new Employee();
        }
        else
        {
            return new Person();
        }
    }

    private bool FieldExists(string fieldName, JObject jObject)
    {
        return jObject[fieldName] != null;
    }
}

public abstract class JsonCreationConverter<T> : JsonConverter
{
    /// <summary>
    /// Create an instance of objectType, based properties in the JSON object
    /// </summary>
    /// <param name="objectType">type of object expected</param>
    /// <param name="jObject">
    /// contents of JSON object that will be deserialized
    /// </param>
    /// <returns></returns>
    protected abstract T Create(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, 
                                    Type objectType, 
                                     object existingValue, 
                                     JsonSerializer serializer)
    {
        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        T target = Create(objectType, jObject);

        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
}

Algorithm for Determining Tic Tac Toe Game Over

If you have boarder field 5*5 for examle, I used next method of checking:

public static boolean checkWin(char symb) {
  int SIZE = 5;

        for (int i = 0; i < SIZE-1; i++) {
            for (int j = 0; j <SIZE-1 ; j++) {
                //vertical checking
            if (map[0][j] == symb && map[1][j] == symb && map[2][j] == symb && map[3][j] == symb && map[4][j] == symb) return true;      // j=0
            }
            //horisontal checking
            if(map[i][0] == symb && map[i][1] == symb && map[i][2] == symb && map[i][3] == symb && map[i][4] == symb) return true;  // i=0
        }
        //diagonal checking (5*5)
        if (map[0][0] == symb && map[1][1] == symb && map[2][2] == symb && map[3][3] == symb && map[4][4] == symb) return true;
        if (map[4][0] == symb && map[3][1] == symb && map[2][2] == symb && map[1][3] == symb && map[0][4] == symb) return true;

        return false; 
        }

I think, it's more clear, but probably is not the most optimal way.

Genymotion Android emulator - adb access?

I know it's way too late to answer this question, but I'll just post the solution that worked for me, in case someone runs into trouble again in the future.

I tried using genymotion's own adb tools and the original Android SDK ones, and even purging and reinstalling adb from my system, but nothing worked. I kept getting the error:

adb server is out of date. killing... cannot bind 'tcp:5037' ADB server didn't ACK *failed to start daemon* error:
So I tried adb connect [ip] as suggested here, but I didn't work either, the same error came up.

What finally worked for me was downloading ADT, and running adb directly from the downloaded folder, instead of the system-wide command. So adb devices will give me the error above, but /yourdownloadpath/adb devices works just fine for me.

Hope it helped.

SQL: Return "true" if list of records exists?

Here's how I usually do it:

Just replace your query with this statement SELECT * FROM table WHERE 1

   SELECT
      CASE WHEN EXISTS 
      (
            SELECT * FROM table WHERE 1
      )
      THEN 'TRUE'
      ELSE 'FALSE'
   END

Converting pixels to dp

The best answer comes from the Android framework itself: just use this equality...

public static int dpToPixels(final DisplayMetrics display_metrics, final float dps) {
    final float scale = display_metrics.density;
    return (int) (dps * scale + 0.5f);
}

(converts dp to px)

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

You can get around this problem by writing a custom function that uses curl, as in:

function file_get_contents_curl( $url ) {

  $ch = curl_init();

  curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
  curl_setopt( $ch, CURLOPT_HEADER, 0 );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  curl_setopt( $ch, CURLOPT_URL, $url );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );

  $data = curl_exec( $ch );
  curl_close( $ch );

  return $data;

}

Then just use file_get_contents_curl instead of file_get_contents whenever you're calling a url that begins with https.

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

PHP: Return all dates between two dates in an array

Short function. PHP 5.3 and up. Can take optional third param of any date format that strtotime can understand. Automatically reverses direction if end < start.

function getDatesFromRange($start, $end, $format='Y-m-d') {
    return array_map(function($timestamp) use($format) {
        return date($format, $timestamp);
    },
    range(strtotime($start) + ($start < $end ? 4000 : 8000), strtotime($end) + ($start < $end ? 8000 : 4000), 86400));
}

Test:

date_default_timezone_set('Europe/Berlin');
print_r(getDatesFromRange( '2016-7-28','2016-8-2' ));
print_r(getDatesFromRange( '2016-8-2','2016-7-28' ));
print_r(getDatesFromRange( '2016-10-28','2016-11-2' ));
print_r(getDatesFromRange( '2016-11-2','2016-10-28' ));
print_r(getDatesFromRange( '2016-4-2','2016-3-25' ));
print_r(getDatesFromRange( '2016-3-25','2016-4-2' ));
print_r(getDatesFromRange( '2016-8-2','2016-7-25' ));
print_r(getDatesFromRange( '2016-7-25','2016-8-2' ));

Output:

Array ( [0] => 2016-07-28 [1] => 2016-07-29 [2] => 2016-07-30 [3] => 2016-07-31 [4] => 2016-08-01 [5] => 2016-08-02 ) 
Array ( [0] => 2016-08-02 [1] => 2016-08-01 [2] => 2016-07-31 [3] => 2016-07-30 [4] => 2016-07-29 [5] => 2016-07-28 ) 
Array ( [0] => 2016-10-28 [1] => 2016-10-29 [2] => 2016-10-30 [3] => 2016-10-31 [4] => 2016-11-01 [5] => 2016-11-02 ) 
Array ( [0] => 2016-11-02 [1] => 2016-11-01 [2] => 2016-10-31 [3] => 2016-10-30 [4] => 2016-10-29 [5] => 2016-10-28 ) 
Array ( [0] => 2016-04-02 [1] => 2016-04-01 [2] => 2016-03-31 [3] => 2016-03-30 [4] => 2016-03-29 [5] => 2016-03-28 [6] => 2016-03-27 [7] => 2016-03-26 [8] => 2016-03-25 ) 
Array ( [0] => 2016-03-25 [1] => 2016-03-26 [2] => 2016-03-27 [3] => 2016-03-28 [4] => 2016-03-29 [5] => 2016-03-30 [6] => 2016-03-31 [7] => 2016-04-01 [8] => 2016-04-02 ) 
Array ( [0] => 2016-08-02 [1] => 2016-08-01 [2] => 2016-07-31 [3] => 2016-07-30 [4] => 2016-07-29 [5] => 2016-07-28 [6] => 2016-07-27 [7] => 2016-07-26 [8] => 2016-07-25 ) 
Array ( [0] => 2016-07-25 [1] => 2016-07-26 [2] => 2016-07-27 [3] => 2016-07-28 [4] => 2016-07-29 [5] => 2016-07-30 [6] => 2016-07-31 [7] => 2016-08-01 [8] => 2016-08-02 )

python: changing row index of pandas data frame

you can do

followers_df.index = range(20)

How to add users to Docker container?

To avoid the interactive questions by adduser, you can call it with these parameters:

RUN adduser --disabled-password --gecos '' newuser

The --gecos parameter is used to set the additional information. In this case it is just empty.

On systems with busybox (like Alpine), use

RUN adduser -D -g '' newuser

See busybox adduser

How to change legend title in ggplot

None of the above code worked for me.

Here's what I found and it worked.

labs(color = "sale year")

You can also give a space between the title and the display by adding \n at the end.

labs(color = 'sale year\n")

Select all 'tr' except the first one

Another option:

tr:nth-child(n + 2) {
    /* properties */
}

Enabling WiFi on Android Emulator

Wifi is not available on the emulator if you are using below of API level 25.

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

More Information: https://developer.android.com/studio/run/emulator.html#wifi

How to install a private NPM module without my own registry?

Very simple -

npm config set registry https://path-to-your-registry/

It actually sets registry = "https://path-to-your-registry" this line to /Users/<ur-machine-user-name>/.npmrc

All the value you have set explicitly or have been set by default can be seen by - npm config list

Truncating all tables in a Postgres database

Could you use dynamic SQL to execute each statement in turn? You would probably have to write a PL/pgSQL script to do this.

http://www.postgresql.org/docs/8.3/static/plpgsql-statements.html (section 38.5.4. Executing Dynamic Commands)

Init method in Spring Controller (annotation version)

You can use

@PostConstruct
public void init() {
   // ...
}

Test if string is a number in Ruby on Rails

If you prefer not to use exceptions as part of the logic, you might try this:

class String
   def numeric?
    !!(self =~ /^-?\d+(\.\d*)?$/)
  end
end

Or, if you want it to work across all object classes, replace class String with class Object an convert self to a string: !!(self.to_s =~ /^-?\d+(\.\d*)?$/)

Sequel Pro Alternative for Windows

You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.

But if you want alternative suggestions, here are a few that I know of and have used:

MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.

Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.

(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)

Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.

Lookup City and State by Zip Google Geocode Api

function getCityState($zip, $blnUSA = true) {
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";

    $address_info = file_get_contents($url);
    $json = json_decode($address_info);
    $city = "";
    $state = "";
    $country = "";
    if (count($json->results) > 0) {
        //break up the components
        $arrComponents = $json->results[0]->address_components;

        foreach($arrComponents as $index=>$component) {
            $type = $component->types[0];

            if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                $city = trim($component->short_name);
            }
            if ($state == "" && $type=="administrative_area_level_1") {
                $state = trim($component->short_name);
            }
            if ($country == "" && $type=="country") {
                $country = trim($component->short_name);

                if ($blnUSA && $country!="US") {
                    $city = "";
                    $state = "";
                    break;
                }
            }
            if ($city != "" && $state != "" && $country != "") {
                //we're done
                break;
            }
        }
    }
    $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);

    die(json_encode($arrReturn));
}

@import vs #import - iOS 7

It currently only works for the built in system frameworks. If you use #import like apple still do importing the UIKit framework in the app delegate it is replaced (if modules is on and its recognised as a system framework) and the compiler will remap it to be a module import and not an import of the header files anyway. So leaving the #import will be just the same as its converted to a module import where possible anyway

How do you clear a slice in Go?

It all depends on what is your definition of 'clear'. One of the valid ones certainly is:

slice = slice[:0]

But there's a catch. If slice elements are of type T:

var slice []T

then enforcing len(slice) to be zero, by the above "trick", doesn't make any element of

slice[:cap(slice)]

eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of "memory leaks" - memory not used, but potentially reachable (after re-slicing of 'slice') and thus not garbage "collectable".

How to combine paths in Java?

Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.

If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path; Path.resolve can be used to combine one path with another, or with a string. The Paths helper class is useful too. For example:

Path path = Paths.get("foo", "bar", "baz.txt");

If you need to cater for pre-Java-7 environments, you can use java.io.File, like this:

File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine(String path1, String path2)
{
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

Replace whole line containing a string using Sed

You need to use wildards (.*) before and after to replace the whole line:

sed 's/.*TEXT_TO_BE_REPLACED.*/This line is removed by the admin./'

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

Default value of 'boolean' and 'Boolean' in Java

An uninitialized Boolean member (actually a reference to an object of type Boolean) will have the default value of null.

An uninitialized boolean (primitive) member will have the default value of false.

Select multiple columns in data.table by their numeric indices

@Tom, thank you very much for pointing out this solution. It works great for me.

I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this

library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]

Using import fs from 'fs'

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

How to install a Mac application using Terminal

To disable inputting password:

sudo visudo

Then add a new line like below and save then:

# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer

Then you run installer without password:

sudo installer -pkg ...

Could not open input file: composer.phar

I am using Windows 7, and I got the same problem as yours while using Composer via cmd.

The problem is solved when I use

php C:\ProgramData\ComposerSetup\bin\composer.phar create-project slim/slim-skeleton

instead of

php composer.phar create-project slim/slim-skeleton

Hope this is useful for people who got the same problem.

Replace multiple whitespaces with single whitespace in JavaScript string

I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?

If that's the case, you'll need a regex like this:

mystring = mystring.replace(/(^\s+|\s+$)/g,' ');

This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:

mystring = mystring.replace(/\s+$/g,' ');

Hope that helps.

Add custom header in HttpWebRequest

You use the Headers property with a string index:

request.Headers["X-My-Custom-Header"] = "the-value";

According to MSDN, this has been available since:

  • Universal Windows Platform 4.5
  • .NET Framework 1.1
  • Portable Class Library
  • Silverlight 2.0
  • Windows Phone Silverlight 7.0
  • Windows Phone 8.1

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx

How to get PID by process name?

you can also use pgrep, in prgep you can also give pattern for match

import subprocess
child = subprocess.Popen(['pgrep','program_name'], stdout=subprocess.PIPE, shell=True)
result = child.communicate()[0]

you can also use awk with ps like this

ps aux | awk '/name/{print $2}'

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

How to get the path of current worksheet in VBA?

Use Application.ActiveWorkbook.Path for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName for the path with the workbook name.

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

How do I get the fragment identifier (value after hash #) from a URL?

You may do it by using following code:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

How to apply slide animation between two activities in Android?

Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.

Slide animations can be slid right, slide left, slide up and slide down.

Slide up

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:toXScale="1.0"
        android:toYScale="0.0" />
</set>

Slide down

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

overridePendingTransition(R.anim.slide_down, R.anim.slide_up);

See activity transition animation examples for more activity transition examples.

Passing a method parameter using Task.Factory.StartNew

Construct the first parameter as an instance of Action, e.g.

var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
    () => CheckFiles(inputID, col),
    cancelCheckFile.Token,
    TaskCreationOptions.LongRunning,
    TaskScheduler.Default);

Call method in directive controller from other controller

You could also expose the directive's controller to the parent scope, like ngForm with name attribute does: http://docs.angularjs.org/api/ng.directive:ngForm

Here you could find a very basic example how it could be achieved http://plnkr.co/edit/Ps8OXrfpnePFvvdFgYJf?p=preview

In this example I have myDirective with dedicated controller with $clear method (sort of very simple public API for the directive). I can publish this controller to the parent scope and use call this method outside the directive.

What does mvn install in maven exactly do

Short answer

mvn install

  • adds all artifact (dependencies) specified in pom, to the local repository (from remote sources).

Evaluate a string with a switch in C++

You can only use switch-case on types castable to an int.

You could, however, define a std::map<std::string, std::function> dispatcher and use it like dispatcher[str]() to achieve same effect.

get all the elements of a particular form

Use this

var theForm = document.forms['formname']
[].slice.call(theForm).forEach(function (el, i) {
    console.log(el.value);
});

The el stands for the particular form element. It is better to use this than the foreach loop, as the foreach loop also returns a function as one of the element. However this only returns the DOM elements of the form.

Java - Check Not Null/Empty else assign default value

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

random.seed(): What does it do?

random.seed(a, version) in python is used to initialize the pseudo-random number generator (PRNG).

PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value. So, if you provide seed value, PRNG starts from an arbitrary starting state using a seed.

Argument a is the seed value. If the a value is None, then by default, current system time is used.

and version is An integer specifying how to convert the a parameter into a integer. Default value is 2.

import random
random.seed(9001)
random.randint(1, 10) #this gives output of 1
# 1

If you want the same random number to be reproduced then provide the same seed again

random.seed(9001)
random.randint(1, 10) # this will give the same output of 1
# 1

If you don't provide the seed, then it generate different number and not 1 as before

random.randint(1, 10) # this gives 7 without providing seed
# 7

If you provide different seed than before, then it will give you a different random number

random.seed(9002)
random.randint(1, 10) # this gives you 5 not 1
# 5

So, in summary, if you want the same random number to be reproduced, provide the seed. Specifically, the same seed.

What is the list of valid @SuppressWarnings warning names in Java?

All values are permitted (unrecognized ones are ignored). The list of recognized ones is compiler specific.

In The Java Tutorials unchecked and deprecation are listed as the two warnings required by The Java Language Specification, therefore, they should be valid with all compilers:

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked.

The specific sections inside The Java Language Specification where they are defined is not consistent across versions. In the Java SE 8 Specification unchecked and deprecation are listed as compiler warnings in sections 9.6.4.5. @SuppressWarnings and 9.6.4.6 @Deprecated, respectively.

For Sun's compiler, running javac -X gives a list of all values recognized by that version. For 1.5.0_17, the list appears to be:

  • all
  • deprecation
  • unchecked
  • fallthrough
  • path
  • serial
  • finally

Get the latest record from mongodb collection

This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)

db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{   allowDiskUse:true  })

you can add or remove from the group

help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group

https://docs.mongodb.com/manual/reference/operator/aggregation/last/

Is there a way to add/remove several classes in one single instruction with classList?

The new spread operator makes it even easier to apply multiple CSS classes as array:

const list = ['first', 'second', 'third'];
element.classList.add(...list);

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

Is there a way to call a stored procedure with Dapper?

I think the answer depends on which features of stored procedures you need to use.

Stored procedures returning a result set can be run using Query; stored procedures which don't return a result set can be run using Execute - in both cases (using EXEC <procname>) as the SQL command (plus input parameters as necessary). See the documentation for more details.

As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT parameters; you could add this, or alternatively construct a more complex Query command which declared TSQL variables, executed the SP collecting OUTPUT parameters into the local variables and finallyreturned them in a result set:

DECLARE @output int

EXEC <some stored proc> @i = @output OUTPUT

SELECT @output AS output1

Dynamically change color to lighter or darker by percentage CSS (Javascript)

Try:

a {
  color: hsl(240, 100%, 50%);
}

a:hover {
  color: hsl(240, 100%, 70%);
}

Convert file: Uri to File in Android

@CommonsWare explained all things quite well. And we really should use the solution he proposed.

By the way, only information we could rely on when querying ContentResolver is a file's name and size as mentioned here: Retrieving File Information | Android developers

As you could see there is an interface OpenableColumns that contains only two fields: DISPLAY_NAME and SIZE.

In my case I was need to retrieve EXIF information about a JPEG image and rotate it if needed before sending to a server. To do that I copied a file content into a temporary file using ContentResolver and openInputStream()

Using Spring 3 autowire in a standalone Java application

For Spring 4, using Spring Boot we can have the following example without using the anti-pattern of getting the Bean from the ApplicationContext directly:

package com.yourproject;

@SpringBootApplication
public class TestBed implements CommandLineRunner {

    private MyService myService;

    @Autowired
    public TestBed(MyService myService){
        this.myService = myService;
    }

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

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("myService: " + MyService );
    }

}

@Service 
public class MyService{
    public String getSomething() {
        return "something";
    }
}

Make sure that all your injected services are under com.yourproject or its subpackages.

How do I change the default library path for R packages

Facing the very same problem (avoiding the default path in a network) I came up to this solution with the hints given in other answers.

The solution is editing the Rprofile file to overwrite the variable R_LIBS_USER which by default points to the home directory.

Here the steps:

  1. Create the target destination folder for the libraries, e.g., ~\target.
  2. Find the Rprofile file. In my case it was at C:\Program Files\R\R-3.3.3\library\base\R\Rprofile.
  3. Edit the file and change the definition the variable R_LIBS_USER. In my case, I replaced the this line file.path(Sys.getenv("R_USER"), "R", with file.path("~\target", "R",.

The documentation that support this solution is here

Original file with:

 if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path(Sys.getenv("R_USER"), "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          )) 

Modified file:

if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path("~\target", "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          ))

Programmatically add new column to DataGridView

Add new column to DataTable and use column Expression property to set your Status expression.

Here you can find good example: DataColumn.Expression Property

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

UPDATE

Code sample:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));

dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));

demoGridView.DataSource = dt;

UPDATE #2

dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

How can I view live MySQL queries?

In addition to previous answers describing how to enable general logging, I had to modify one additional variable in my vanilla MySql 5.6 installation before any SQL was written to the log:

SET GLOBAL log_output = 'FILE';

The default setting was 'NONE'.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

The meaning of the completely undocumented error 800A03EC (shame on Microsoft!) is something like "OPERATION NOT SUPPORTED".

It may happen

  • when you open a document that has a content created by a newer Excel version, which your current Excel version does not understand.
  • when you save a document to the same path where you have loaded it from (file is already open and locked)

But mostly you will see this error due to severe bugs in Excel.

  • For example Microsoft.Office.Interop.Excel.Picture has a property "Enabled". When you call it you should receive a bool value. But instead you get an error 800A03EC. This is a bug.
  • And there is a very fat bug in Exel 2013 and 2016: When you automate an Excel process and set Application.Visible=true and Application.WindowState = XlWindowState.xlMinimized then you will get hundreds of 800A03EC errors from different functions (like Range.Merge(), CheckBox.Text, Shape.TopLeftCell, Shape.Locked and many more). This bug does not exist in Excel 2007 and 2010.

Valid characters in a Java class name

What other rules govern Java class names (for instance, Java class names cannot begin with a number)?

  • Java class names usually begin with a capital letter.
  • Java class names cannot begin with a number.
  • if there are multiple words in the class name like "MyClassName" each word should begin with a capital letter. eg- "MyClassName".This naming convention is based on CamelCase Type.

How to add values in a variable in Unix shell scripting?

I don't have a unix system under my hands, but try this:

count7=$((${count7} + ${count1}))

Or maybe you have a shell that doesn't support this expression. I think bash does support it, but sh doesn't.

EDIT: There is another syntax, try:

count7=`expr $count7 + $count1`

Converting HTML element to string in JavaScript / JQuery

You can do this:

_x000D_
_x000D_
var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>');    _x000D_
var str = $html.prop('outerHTML');_x000D_
console.log(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

FIDDLE DEMO

Best way to display data via JSON using jQuery

JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.

How to make flexbox items the same size?

None of these answers solved my problem, which was that the items weren't the same width in my makeshift flexbox table when it was shrunk to a width too small.

The solution for me was simply to put overflow: hidden; on the flex-grow: 1; cells.

PHP - Session destroy after closing browser

This might help you,

session_set_cookie_params(0);
session_start();

Your session cookie will be destroyed... so your session will be good until the browser is open. please view http://www.php.net//manual/en/function.session-set-cookie-params.php this may help you.

Passing an Array as Arguments, not an Array, in PHP

Also note that if you want to apply an instance method to an array, you need to pass the function as:

call_user_func_array(array($instance, "MethodName"), $myArgs);

How to get a list of installed Jenkins plugins with name and version pair

Behe's answer with sorting plugins did not work on my Jenkins machine. I received the error java.lang.UnsupportedOperationException due to trying to sort an immutable collection i.e. Jenkins.instance.pluginManager.plugins. Simple fix for the code:

List<String> jenkinsPlugins = new ArrayList<String>(Jenkins.instance.pluginManager.plugins);
jenkinsPlugins.sort { it.displayName }
              .each { plugin ->
                   println ("${plugin.shortName}:${plugin.version}")
              }

Use the http://<jenkins-url>/script URL to run the code.

jQuery.inArray(), how to use it right?

If we want to check an element is inside a set of elements we can do for example:

var checkboxes_checked = $('input[type="checkbox"]:checked');

// Whenever a checkbox or input text is changed
$('input[type="checkbox"], input[type="text"]').change(function() {
    // Checking if the element was an already checked checkbox
    if($.inArray( $(this)[0], checkboxes_checked) !== -1) {
        alert('this checkbox was already checked');
    }
}

MySQL dump by query

This should work

mysqldump --databases X --tables Y --where="1 limit 1000000"

PHP: How to use array_filter() to filter array keys?

Here is a more flexible solution using a closure:

$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$result = array_flip(array_filter(array_flip($my_array), function ($key) use ($allowed)
{
    return in_array($key, $allowed);
}));
var_dump($result);

Outputs:

array(1) {
  'foo' =>
  int(1)
}

So in the function, you can do other specific tests.

How do I use PHP namespaces with autoload?

I found this gem from Flysystem

spl_autoload_register(function($class) {
    $prefix = 'League\\Flysystem\\';

    if ( ! substr($class, 0, 17) === $prefix) {
        return;
    }

    $class = substr($class, strlen($prefix));
    $location = __DIR__ . 'path/to/flysystem/src/' . str_replace('\\', '/', $class) . '.php';

    if (is_file($location)) {
        require_once($location);
    }
});

Git says remote ref does not exist when I delete remote branch

git push origin --delete origin/test 

should work as well

jQuery append() vs appendChild()

No longer

now append is a method in JavaScript

MDN documentation on append method

Quoting MDN

The ParentNode.append method inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.

This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).

The JavaScript's append is similar to jQuery's append.

You can pass multiple arguments.

_x000D_
_x000D_
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
_x000D_
_x000D_

Bootstrap: wider input field

Use the bootstrap built in classes input-large, input-medium, ... : <input type="text" class="input-large search-query">

Or use your own css:

  1. Give the element a unique classname class="search-query input-mysize"
  2. Add this in your css file (not the bootstrap.less or css files):
    .input-mysize { width: 150px }

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

THis issue has been fixed with new mysql connectors, please use http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38

I used to get this error after updating the connector jar, issue resolved.

How to split a dos path into its components in Python

I'm not actually sure if this fully answers the question, but I had a fun time writing this little function that keeps a stack, sticks to os.path-based manipulations, and returns the list/stack of items.

def components(path):
    ret = []
    while len(path) > 0:
        path, crust = split(path)
        ret.insert(0, crust)
    return ret

Truncate all tables in a MySQL database in one command?

mysqldump -u root -p --no-data dbname > schema.sql
mysqldump -u root -p drop dbname
mysqldump -u root -p < schema.sql

How to escape a single quote inside awk

For small scripts an optional way to make it readable is to use a variable like this:

awk -v fmt="'%s'\n" '{printf fmt, $1}'

I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

Biggest advantage to using ASP.Net MVC vs web forms

I can see the only two advantages for smaller sites being: 6) RESTful urls that enables SEO. 7) No ViewState and PostBack events (and greater performance in general)

Testing for small sites is not an issue, neither are the design advantages when a site is coded properly anyway, MVC in many ways obfuscates and makes changes harder to make. I'm still deciding whether these advantages are worth it.

I can clearly see the advantage of MVC in larger multi-developer sites.

Django Rest Framework -- no module named rest_framework

try this if you are using JWT pip install djangorestframework-jwt

Two arrays in foreach loop

I solved a problem like yours by this way:

foreach(array_keys($idarr) as $i) {
 echo "Student ID: ".$idarr[$i]."<br />";
 echo "Present: ".$presentarr[$i]."<br />";
 echo "Reason: ".$reasonarr[$i]."<br />";
 echo "Mark: ".$markarr[$i]."<br />";
}

COALESCE Function in TSQL

declare @store table (store_id varchar(300))
insert into @store 
values ('aa'),('bb'),('cc')
declare @str varchar (4000)
select @str = concat(@str+',',store_id) from @store
select @str